Add a couple llvm_unreachables.
[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 "X86.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.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 using namespace llvm;
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
58                        SDValue V2);
59
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference.  Idx is an index in the 128 bits we
63 /// want.  It need not be aligned to a 128-bit bounday.  That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66                                    SelectionDAG &DAG, DebugLoc dl) {
67   EVT VT = Vec.getValueType();
68   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69   EVT ElVT = VT.getVectorElementType();
70   int Factor = VT.getSizeInBits()/128;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
79   // we can match to VEXTRACTF128.
80   unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
81
82   // This is the index of the first element of the 128-bit chunk
83   // we want.
84   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
85                                * ElemsPerChunk);
86
87   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
89                                VecIdx);
90
91   return Result;
92 }
93
94 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference.  Idx is an index in the 128 bits
97 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100                                   unsigned IdxVal, SelectionDAG &DAG,
101                                   DebugLoc dl) {
102   EVT VT = Vec.getValueType();
103   assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
104
105   EVT ElVT = VT.getVectorElementType();
106   EVT ResultVT = Result.getValueType();
107
108   // Insert the relevant 128 bits.
109   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
110
111   // This is the index of the first element of the 128-bit chunk
112   // we want.
113   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
114                                * ElemsPerChunk);
115
116   SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117   Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
118                        VecIdx);
119   return Result;
120 }
121
122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
125 /// large BUILD_VECTORS.
126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
127                                    unsigned NumElems, SelectionDAG &DAG,
128                                    DebugLoc dl) {
129   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
130   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
131 }
132
133 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
134   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
135   bool is64Bit = Subtarget->is64Bit();
136
137   if (Subtarget->isTargetEnvMacho()) {
138     if (is64Bit)
139       return new X8664_MachoTargetObjectFile();
140     return new TargetLoweringObjectFileMachO();
141   }
142
143   if (Subtarget->isTargetELF())
144     return new TargetLoweringObjectFileELF();
145   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
146     return new TargetLoweringObjectFileCOFF();
147   llvm_unreachable("unknown subtarget type");
148 }
149
150 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
151   : TargetLowering(TM, createTLOF(TM)) {
152   Subtarget = &TM.getSubtarget<X86Subtarget>();
153   X86ScalarSSEf64 = Subtarget->hasSSE2();
154   X86ScalarSSEf32 = Subtarget->hasSSE1();
155   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
156
157   RegInfo = TM.getRegisterInfo();
158   TD = getTargetData();
159
160   // Set up the TargetLowering object.
161   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
162
163   // X86 is weird, it always uses i8 for shift amounts and setcc results.
164   setBooleanContents(ZeroOrOneBooleanContent);
165   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
166   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167
168   // For 64-bit since we have so many registers use the ILP scheduler, for
169   // 32-bit code use the register pressure specific scheduling.
170   // For 32 bit Atom, use Hybrid (register pressure + latency) scheduling.
171   if (Subtarget->is64Bit())
172     setSchedulingPreference(Sched::ILP);
173   else if (Subtarget->isAtom()) 
174     setSchedulingPreference(Sched::Hybrid);
175   else
176     setSchedulingPreference(Sched::RegPressure);
177   setStackPointerRegisterToSaveRestore(X86StackPtr);
178
179   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
180     // Setup Windows compiler runtime calls.
181     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
182     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
183     setLibcallName(RTLIB::SREM_I64, "_allrem");
184     setLibcallName(RTLIB::UREM_I64, "_aullrem");
185     setLibcallName(RTLIB::MUL_I64, "_allmul");
186     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
187     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
188     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
189     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
190     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
191
192     // The _ftol2 runtime function has an unusual calling conv, which
193     // is modeled by a special pseudo-instruction.
194     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
195     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
196     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
197     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
198   }
199
200   if (Subtarget->isTargetDarwin()) {
201     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
202     setUseUnderscoreSetJmp(false);
203     setUseUnderscoreLongJmp(false);
204   } else if (Subtarget->isTargetMingw()) {
205     // MS runtime is weird: it exports _setjmp, but longjmp!
206     setUseUnderscoreSetJmp(true);
207     setUseUnderscoreLongJmp(false);
208   } else {
209     setUseUnderscoreSetJmp(true);
210     setUseUnderscoreLongJmp(true);
211   }
212
213   // Set up the register classes.
214   addRegisterClass(MVT::i8, &X86::GR8RegClass);
215   addRegisterClass(MVT::i16, &X86::GR16RegClass);
216   addRegisterClass(MVT::i32, &X86::GR32RegClass);
217   if (Subtarget->is64Bit())
218     addRegisterClass(MVT::i64, &X86::GR64RegClass);
219
220   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
221
222   // We don't accept any truncstore of integer registers.
223   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
224   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
225   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
226   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
227   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
228   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
229
230   // SETOEQ and SETUNE require checking two conditions.
231   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
232   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
233   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
234   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
235   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
236   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
237
238   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
239   // operation.
240   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
241   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
242   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
243
244   if (Subtarget->is64Bit()) {
245     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
246     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
247   } else if (!TM.Options.UseSoftFloat) {
248     // We have an algorithm for SSE2->double, and we turn this into a
249     // 64-bit FILD followed by conditional FADD for other targets.
250     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
251     // We have an algorithm for SSE2, and we turn this into a 64-bit
252     // FILD for other targets.
253     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
254   }
255
256   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
257   // this operation.
258   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
259   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
260
261   if (!TM.Options.UseSoftFloat) {
262     // SSE has no i16 to fp conversion, only i32
263     if (X86ScalarSSEf32) {
264       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
265       // f32 and f64 cases are Legal, f80 case is not
266       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
267     } else {
268       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
269       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
270     }
271   } else {
272     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
273     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
274   }
275
276   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
277   // are Legal, f80 is custom lowered.
278   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
279   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
280
281   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
282   // this operation.
283   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
284   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
285
286   if (X86ScalarSSEf32) {
287     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
288     // f32 and f64 cases are Legal, f80 case is not
289     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
290   } else {
291     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
292     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
293   }
294
295   // Handle FP_TO_UINT by promoting the destination to a larger signed
296   // conversion.
297   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
298   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
299   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
300
301   if (Subtarget->is64Bit()) {
302     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
303     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
304   } else if (!TM.Options.UseSoftFloat) {
305     // Since AVX is a superset of SSE3, only check for SSE here.
306     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
307       // Expand FP_TO_UINT into a select.
308       // FIXME: We would like to use a Custom expander here eventually to do
309       // the optimal thing for SSE vs. the default expansion in the legalizer.
310       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
311     else
312       // With SSE3 we can use fisttpll to convert to a signed i64; without
313       // SSE, we're stuck with a fistpll.
314       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
315   }
316
317   if (isTargetFTOL()) {
318     // Use the _ftol2 runtime function, which has a pseudo-instruction
319     // to handle its weird calling convention.
320     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
321   }
322
323   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
324   if (!X86ScalarSSEf64) {
325     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
326     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
327     if (Subtarget->is64Bit()) {
328       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
329       // Without SSE, i64->f64 goes through memory.
330       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
331     }
332   }
333
334   // Scalar integer divide and remainder are lowered to use operations that
335   // produce two results, to match the available instructions. This exposes
336   // the two-result form to trivial CSE, which is able to combine x/y and x%y
337   // into a single instruction.
338   //
339   // Scalar integer multiply-high is also lowered to use two-result
340   // operations, to match the available instructions. However, plain multiply
341   // (low) operations are left as Legal, as there are single-result
342   // instructions for this in x86. Using the two-result multiply instructions
343   // when both high and low results are needed must be arranged by dagcombine.
344   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
345     MVT VT = IntVTs[i];
346     setOperationAction(ISD::MULHS, VT, Expand);
347     setOperationAction(ISD::MULHU, VT, Expand);
348     setOperationAction(ISD::SDIV, VT, Expand);
349     setOperationAction(ISD::UDIV, VT, Expand);
350     setOperationAction(ISD::SREM, VT, Expand);
351     setOperationAction(ISD::UREM, VT, Expand);
352
353     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
354     setOperationAction(ISD::ADDC, VT, Custom);
355     setOperationAction(ISD::ADDE, VT, Custom);
356     setOperationAction(ISD::SUBC, VT, Custom);
357     setOperationAction(ISD::SUBE, VT, Custom);
358   }
359
360   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
361   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
362   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
363   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
364   if (Subtarget->is64Bit())
365     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
366   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
367   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
368   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
369   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
370   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
371   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
372   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
373   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
374
375   // Promote the i8 variants and force them on up to i32 which has a shorter
376   // encoding.
377   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
378   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
379   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
380   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
383     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
384     if (Subtarget->is64Bit())
385       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
386   } else {
387     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
388     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
391   }
392
393   if (Subtarget->hasLZCNT()) {
394     // When promoting the i8 variants, force them to i32 for a shorter
395     // encoding.
396     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
397     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
398     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
399     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
400     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
401     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
402     if (Subtarget->is64Bit())
403       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
404   } else {
405     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
406     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
407     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
408     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
409     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
410     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
411     if (Subtarget->is64Bit()) {
412       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
413       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
414     }
415   }
416
417   if (Subtarget->hasPOPCNT()) {
418     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
419   } else {
420     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
421     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
422     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
423     if (Subtarget->is64Bit())
424       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
425   }
426
427   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
428   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
429
430   // These should be promoted to a larger select which is supported.
431   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
432   // X86 wants to expand cmov itself.
433   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
434   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
435   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
436   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
437   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
438   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
439   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
440   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
441   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
442   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
443   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
444   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
447     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
448   }
449   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
450
451   // Darwin ABI issue.
452   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
453   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
454   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
455   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
456   if (Subtarget->is64Bit())
457     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
458   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
459   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
462     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
463     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
464     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
465     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
466   }
467   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
468   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
469   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
470   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
471   if (Subtarget->is64Bit()) {
472     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
473     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
474     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
475   }
476
477   if (Subtarget->hasSSE1())
478     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
479
480   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
481   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
482
483   // On X86 and X86-64, atomic operations are lowered to locked instructions.
484   // Locked instructions, in turn, have implicit fence semantics (all memory
485   // operations are flushed before issuing the locked instruction, and they
486   // are not buffered), so we can fold away the common pattern of
487   // fence-atomic-fence.
488   setShouldFoldAtomicFences(true);
489
490   // Expand certain atomics
491   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
492     MVT VT = IntVTs[i];
493     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
494     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
496   }
497
498   if (!Subtarget->is64Bit()) {
499     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
500     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
501     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
502     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
503     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
504     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
505     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
506     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
507   }
508
509   if (Subtarget->hasCmpxchg16b()) {
510     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
511   }
512
513   // FIXME - use subtarget debug flags
514   if (!Subtarget->isTargetDarwin() &&
515       !Subtarget->isTargetELF() &&
516       !Subtarget->isTargetCygMing()) {
517     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
518   }
519
520   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
521   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
522   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
523   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
524   if (Subtarget->is64Bit()) {
525     setExceptionPointerRegister(X86::RAX);
526     setExceptionSelectorRegister(X86::RDX);
527   } else {
528     setExceptionPointerRegister(X86::EAX);
529     setExceptionSelectorRegister(X86::EDX);
530   }
531   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
532   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
533
534   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
535   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
536
537   setOperationAction(ISD::TRAP, MVT::Other, Legal);
538
539   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
541   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
542   if (Subtarget->is64Bit()) {
543     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
544     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
545   } else {
546     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
547     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
548   }
549
550   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
551   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
552
553   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
554     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
555                        MVT::i64 : MVT::i32, Custom);
556   else if (TM.Options.EnableSegmentedStacks)
557     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
558                        MVT::i64 : MVT::i32, Custom);
559   else
560     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561                        MVT::i64 : MVT::i32, Expand);
562
563   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
564     // f32 and f64 use SSE.
565     // Set up the FP register classes.
566     addRegisterClass(MVT::f32, &X86::FR32RegClass);
567     addRegisterClass(MVT::f64, &X86::FR64RegClass);
568
569     // Use ANDPD to simulate FABS.
570     setOperationAction(ISD::FABS , MVT::f64, Custom);
571     setOperationAction(ISD::FABS , MVT::f32, Custom);
572
573     // Use XORP to simulate FNEG.
574     setOperationAction(ISD::FNEG , MVT::f64, Custom);
575     setOperationAction(ISD::FNEG , MVT::f32, Custom);
576
577     // Use ANDPD and ORPD to simulate FCOPYSIGN.
578     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
579     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
580
581     // Lower this to FGETSIGNx86 plus an AND.
582     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
583     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
584
585     // We don't support sin/cos/fmod
586     setOperationAction(ISD::FSIN , MVT::f64, Expand);
587     setOperationAction(ISD::FCOS , MVT::f64, Expand);
588     setOperationAction(ISD::FSIN , MVT::f32, Expand);
589     setOperationAction(ISD::FCOS , MVT::f32, Expand);
590
591     // Expand FP immediates into loads from the stack, except for the special
592     // cases we handle.
593     addLegalFPImmediate(APFloat(+0.0)); // xorpd
594     addLegalFPImmediate(APFloat(+0.0f)); // xorps
595   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
596     // Use SSE for f32, x87 for f64.
597     // Set up the FP register classes.
598     addRegisterClass(MVT::f32, &X86::FR32RegClass);
599     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
600
601     // Use ANDPS to simulate FABS.
602     setOperationAction(ISD::FABS , MVT::f32, Custom);
603
604     // Use XORP to simulate FNEG.
605     setOperationAction(ISD::FNEG , MVT::f32, Custom);
606
607     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
608
609     // Use ANDPS and ORPS to simulate FCOPYSIGN.
610     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
612
613     // We don't support sin/cos/fmod
614     setOperationAction(ISD::FSIN , MVT::f32, Expand);
615     setOperationAction(ISD::FCOS , MVT::f32, Expand);
616
617     // Special cases we handle for FP constants.
618     addLegalFPImmediate(APFloat(+0.0f)); // xorps
619     addLegalFPImmediate(APFloat(+0.0)); // FLD0
620     addLegalFPImmediate(APFloat(+1.0)); // FLD1
621     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
623
624     if (!TM.Options.UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628   } else if (!TM.Options.UseSoftFloat) {
629     // f32 and f64 in x87.
630     // Set up the FP register classes.
631     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
633
634     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
635     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
636     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
637     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
638
639     if (!TM.Options.UnsafeFPMath) {
640       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
641       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
642     }
643     addLegalFPImmediate(APFloat(+0.0)); // FLD0
644     addLegalFPImmediate(APFloat(+1.0)); // FLD1
645     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
648     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
649     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
650     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
651   }
652
653   // We don't support FMA.
654   setOperationAction(ISD::FMA, MVT::f64, Expand);
655   setOperationAction(ISD::FMA, MVT::f32, Expand);
656
657   // Long double always uses X87.
658   if (!TM.Options.UseSoftFloat) {
659     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
660     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
661     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
662     {
663       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
664       addLegalFPImmediate(TmpFlt);  // FLD0
665       TmpFlt.changeSign();
666       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
667
668       bool ignored;
669       APFloat TmpFlt2(+1.0);
670       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
671                       &ignored);
672       addLegalFPImmediate(TmpFlt2);  // FLD1
673       TmpFlt2.changeSign();
674       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
675     }
676
677     if (!TM.Options.UnsafeFPMath) {
678       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
679       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
680     }
681
682     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
683     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
684     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
685     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
686     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
687     setOperationAction(ISD::FMA, MVT::f80, Expand);
688   }
689
690   // Always use a library call for pow.
691   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
692   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
693   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
694
695   setOperationAction(ISD::FLOG, MVT::f80, Expand);
696   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
697   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
698   setOperationAction(ISD::FEXP, MVT::f80, Expand);
699   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
700
701   // First set operation action for all vector types to either promote
702   // (for widening) or expand (for scalarization). Then we will selectively
703   // turn on ones that can be effectively codegen'd.
704   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
705        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
706     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
742     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
743     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
744     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
745     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
746     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
747     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
748     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
749     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
750     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
751     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
752     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
753     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
754     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
755     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
758     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
759     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
760     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
761     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
762     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
763     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
764          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
765       setTruncStoreAction((MVT::SimpleValueType)VT,
766                           (MVT::SimpleValueType)InnerVT, Expand);
767     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
770   }
771
772   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
773   // with -msoft-float, disable use of MMX as well.
774   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
775     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
776     // No operations on x86mmx supported, everything uses intrinsics.
777   }
778
779   // MMX-sized vectors (other than x86mmx) are expected to be expanded
780   // into smaller operations.
781   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
782   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
783   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
784   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
785   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
786   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
787   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
788   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
789   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
790   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
791   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
792   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
793   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
794   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
795   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
796   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
797   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
798   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
799   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
800   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
801   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
802   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
803   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
804   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
805   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
806   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
807   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
808   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
809   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
810
811   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
812     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
813
814     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
815     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
816     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
817     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
818     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
819     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
820     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
821     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
822     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
823     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
825     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
826   }
827
828   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
829     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
830
831     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
832     // registers cannot be used even for integer operations.
833     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
834     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
835     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
836     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
837
838     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
839     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
840     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
841     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
842     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
843     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
844     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
845     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
846     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
847     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
848     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
849     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
850     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
851     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
852     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
853     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
854
855     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
856     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
857     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
858     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
859
860     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
861     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
863     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
864     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
865
866     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
867     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
868     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
869     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
870     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
871
872     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
874       EVT VT = (MVT::SimpleValueType)i;
875       // Do not attempt to custom lower non-power-of-2 vectors
876       if (!isPowerOf2_32(VT.getVectorNumElements()))
877         continue;
878       // Do not attempt to custom lower non-128-bit vectors
879       if (!VT.is128BitVector())
880         continue;
881       setOperationAction(ISD::BUILD_VECTOR,
882                          VT.getSimpleVT().SimpleTy, Custom);
883       setOperationAction(ISD::VECTOR_SHUFFLE,
884                          VT.getSimpleVT().SimpleTy, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
886                          VT.getSimpleVT().SimpleTy, Custom);
887     }
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
899     }
900
901     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
902     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
903       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
904       EVT VT = SVT;
905
906       // Do not attempt to promote non-128-bit vectors
907       if (!VT.is128BitVector())
908         continue;
909
910       setOperationAction(ISD::AND,    SVT, Promote);
911       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
912       setOperationAction(ISD::OR,     SVT, Promote);
913       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
914       setOperationAction(ISD::XOR,    SVT, Promote);
915       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
916       setOperationAction(ISD::LOAD,   SVT, Promote);
917       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
918       setOperationAction(ISD::SELECT, SVT, Promote);
919       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
920     }
921
922     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
923
924     // Custom lower v2i64 and v2f64 selects.
925     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
926     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
927     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
928     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
929
930     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
931     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
932   }
933
934   if (Subtarget->hasSSE41()) {
935     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
936     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
937     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
938     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
939     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
940     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
941     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
942     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
943     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
944     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
945
946     // FIXME: Do we need to handle scalar-to-vector here?
947     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
948
949     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
950     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
951     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
952     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
953     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
954
955     // i8 and i16 vectors are custom , because the source register and source
956     // source memory operand types are not the same width.  f32 vectors are
957     // custom since the immediate controlling the insert encodes additional
958     // information.
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
960     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
961     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
962     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
963
964     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
968
969     // FIXME: these should be Legal but thats only for the case where
970     // the index is constant.  For now custom expand to deal with that.
971     if (Subtarget->is64Bit()) {
972       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
973       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
974     }
975   }
976
977   if (Subtarget->hasSSE2()) {
978     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
979     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
980
981     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
982     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
983
984     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
985     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
986
987     if (Subtarget->hasAVX2()) {
988       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
989       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
990
991       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
992       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
993
994       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
995     } else {
996       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
997       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
998
999       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1000       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1001
1002       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1003     }
1004   }
1005
1006   if (Subtarget->hasSSE42())
1007     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
1008
1009   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1011     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1013     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1014     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1015     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1016
1017     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1018     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1019     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1020
1021     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1022     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1023     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1024     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1025     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1026     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1027
1028     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1029     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1030     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1031     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1032     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1033     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1034
1035     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1036     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1037     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1038
1039     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1040     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1041     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1042     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1043     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1044     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1045
1046     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1047     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1048
1049     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1050     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1051
1052     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1053     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1054
1055     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1056     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1057     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1058     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1059
1060     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1061     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1062     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1065     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1066     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1067     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1068
1069     if (Subtarget->hasAVX2()) {
1070       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1071       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1072       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1073       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1074
1075       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1076       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1077       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1078       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1079
1080       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1081       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1082       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1083       // Don't lower v32i8 because there is no 128-bit byte mul
1084
1085       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1094     } else {
1095       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1096       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1097       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1098       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1099
1100       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1101       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1102       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1103       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1104
1105       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1106       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1107       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1108       // Don't lower v32i8 because there is no 128-bit byte mul
1109
1110       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1111       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1112
1113       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1114       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1115
1116       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1117     }
1118
1119     // Custom lower several nodes for 256-bit types.
1120     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1121                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1122       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1123       EVT VT = SVT;
1124
1125       // Extract subvector is special because the value type
1126       // (result) is 128-bit but the source is 256-bit wide.
1127       if (VT.is128BitVector())
1128         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1129
1130       // Do not attempt to custom lower other non-256-bit vectors
1131       if (!VT.is256BitVector())
1132         continue;
1133
1134       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1135       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1136       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1137       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1138       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1139       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1140     }
1141
1142     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1143     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1144       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1145       EVT VT = SVT;
1146
1147       // Do not attempt to promote non-256-bit vectors
1148       if (!VT.is256BitVector())
1149         continue;
1150
1151       setOperationAction(ISD::AND,    SVT, Promote);
1152       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1153       setOperationAction(ISD::OR,     SVT, Promote);
1154       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1155       setOperationAction(ISD::XOR,    SVT, Promote);
1156       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1157       setOperationAction(ISD::LOAD,   SVT, Promote);
1158       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1159       setOperationAction(ISD::SELECT, SVT, Promote);
1160       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1161     }
1162   }
1163
1164   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1165   // of this type with custom code.
1166   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1167          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1168     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1169                        Custom);
1170   }
1171
1172   // We want to custom lower some of our intrinsics.
1173   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1174
1175
1176   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1177   // handle type legalization for these operations here.
1178   //
1179   // FIXME: We really should do custom legalization for addition and
1180   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1181   // than generic legalization for 64-bit multiplication-with-overflow, though.
1182   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1183     // Add/Sub/Mul with overflow operations are custom lowered.
1184     MVT VT = IntVTs[i];
1185     setOperationAction(ISD::SADDO, VT, Custom);
1186     setOperationAction(ISD::UADDO, VT, Custom);
1187     setOperationAction(ISD::SSUBO, VT, Custom);
1188     setOperationAction(ISD::USUBO, VT, Custom);
1189     setOperationAction(ISD::SMULO, VT, Custom);
1190     setOperationAction(ISD::UMULO, VT, Custom);
1191   }
1192
1193   // There are no 8-bit 3-address imul/mul instructions
1194   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1195   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1196
1197   if (!Subtarget->is64Bit()) {
1198     // These libcalls are not available in 32-bit.
1199     setLibcallName(RTLIB::SHL_I128, 0);
1200     setLibcallName(RTLIB::SRL_I128, 0);
1201     setLibcallName(RTLIB::SRA_I128, 0);
1202   }
1203
1204   // We have target-specific dag combine patterns for the following nodes:
1205   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1206   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1207   setTargetDAGCombine(ISD::VSELECT);
1208   setTargetDAGCombine(ISD::SELECT);
1209   setTargetDAGCombine(ISD::SHL);
1210   setTargetDAGCombine(ISD::SRA);
1211   setTargetDAGCombine(ISD::SRL);
1212   setTargetDAGCombine(ISD::OR);
1213   setTargetDAGCombine(ISD::AND);
1214   setTargetDAGCombine(ISD::ADD);
1215   setTargetDAGCombine(ISD::FADD);
1216   setTargetDAGCombine(ISD::FSUB);
1217   setTargetDAGCombine(ISD::SUB);
1218   setTargetDAGCombine(ISD::LOAD);
1219   setTargetDAGCombine(ISD::STORE);
1220   setTargetDAGCombine(ISD::ZERO_EXTEND);
1221   setTargetDAGCombine(ISD::ANY_EXTEND);
1222   setTargetDAGCombine(ISD::SIGN_EXTEND);
1223   setTargetDAGCombine(ISD::TRUNCATE);
1224   setTargetDAGCombine(ISD::SINT_TO_FP);
1225   if (Subtarget->is64Bit())
1226     setTargetDAGCombine(ISD::MUL);
1227   if (Subtarget->hasBMI())
1228     setTargetDAGCombine(ISD::XOR);
1229
1230   computeRegisterProperties();
1231
1232   // On Darwin, -Os means optimize for size without hurting performance,
1233   // do not reduce the limit.
1234   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1235   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1236   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1237   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1238   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1239   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1240   setPrefLoopAlignment(4); // 2^4 bytes.
1241   benefitFromCodePlacementOpt = true;
1242
1243   setPrefFunctionAlignment(4); // 2^4 bytes.
1244 }
1245
1246
1247 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1248   if (!VT.isVector()) return MVT::i8;
1249   return VT.changeVectorElementTypeToInteger();
1250 }
1251
1252
1253 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1254 /// the desired ByVal argument alignment.
1255 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1256   if (MaxAlign == 16)
1257     return;
1258   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1259     if (VTy->getBitWidth() == 128)
1260       MaxAlign = 16;
1261   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1262     unsigned EltAlign = 0;
1263     getMaxByValAlign(ATy->getElementType(), EltAlign);
1264     if (EltAlign > MaxAlign)
1265       MaxAlign = EltAlign;
1266   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1267     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1268       unsigned EltAlign = 0;
1269       getMaxByValAlign(STy->getElementType(i), EltAlign);
1270       if (EltAlign > MaxAlign)
1271         MaxAlign = EltAlign;
1272       if (MaxAlign == 16)
1273         break;
1274     }
1275   }
1276 }
1277
1278 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1279 /// function arguments in the caller parameter area. For X86, aggregates
1280 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1281 /// are at 4-byte boundaries.
1282 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1283   if (Subtarget->is64Bit()) {
1284     // Max of 8 and alignment of type.
1285     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1286     if (TyAlign > 8)
1287       return TyAlign;
1288     return 8;
1289   }
1290
1291   unsigned Align = 4;
1292   if (Subtarget->hasSSE1())
1293     getMaxByValAlign(Ty, Align);
1294   return Align;
1295 }
1296
1297 /// getOptimalMemOpType - Returns the target specific optimal type for load
1298 /// and store operations as a result of memset, memcpy, and memmove
1299 /// lowering. If DstAlign is zero that means it's safe to destination
1300 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1301 /// means there isn't a need to check it against alignment requirement,
1302 /// probably because the source does not need to be loaded. If
1303 /// 'IsZeroVal' is true, that means it's safe to return a
1304 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1305 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1306 /// constant so it does not need to be loaded.
1307 /// It returns EVT::Other if the type should be determined using generic
1308 /// target-independent logic.
1309 EVT
1310 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1311                                        unsigned DstAlign, unsigned SrcAlign,
1312                                        bool IsZeroVal,
1313                                        bool MemcpyStrSrc,
1314                                        MachineFunction &MF) const {
1315   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1316   // linux.  This is because the stack realignment code can't handle certain
1317   // cases like PR2962.  This should be removed when PR2962 is fixed.
1318   const Function *F = MF.getFunction();
1319   if (IsZeroVal &&
1320       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1321     if (Size >= 16 &&
1322         (Subtarget->isUnalignedMemAccessFast() ||
1323          ((DstAlign == 0 || DstAlign >= 16) &&
1324           (SrcAlign == 0 || SrcAlign >= 16))) &&
1325         Subtarget->getStackAlignment() >= 16) {
1326       if (Subtarget->getStackAlignment() >= 32) {
1327         if (Subtarget->hasAVX2())
1328           return MVT::v8i32;
1329         if (Subtarget->hasAVX())
1330           return MVT::v8f32;
1331       }
1332       if (Subtarget->hasSSE2())
1333         return MVT::v4i32;
1334       if (Subtarget->hasSSE1())
1335         return MVT::v4f32;
1336     } else if (!MemcpyStrSrc && Size >= 8 &&
1337                !Subtarget->is64Bit() &&
1338                Subtarget->getStackAlignment() >= 8 &&
1339                Subtarget->hasSSE2()) {
1340       // Do not use f64 to lower memcpy if source is string constant. It's
1341       // better to use i32 to avoid the loads.
1342       return MVT::f64;
1343     }
1344   }
1345   if (Subtarget->is64Bit() && Size >= 8)
1346     return MVT::i64;
1347   return MVT::i32;
1348 }
1349
1350 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1351 /// current function.  The returned value is a member of the
1352 /// MachineJumpTableInfo::JTEntryKind enum.
1353 unsigned X86TargetLowering::getJumpTableEncoding() const {
1354   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1355   // symbol.
1356   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1357       Subtarget->isPICStyleGOT())
1358     return MachineJumpTableInfo::EK_Custom32;
1359
1360   // Otherwise, use the normal jump table encoding heuristics.
1361   return TargetLowering::getJumpTableEncoding();
1362 }
1363
1364 const MCExpr *
1365 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1366                                              const MachineBasicBlock *MBB,
1367                                              unsigned uid,MCContext &Ctx) const{
1368   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1369          Subtarget->isPICStyleGOT());
1370   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1371   // entries.
1372   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1373                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1374 }
1375
1376 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1377 /// jumptable.
1378 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1379                                                     SelectionDAG &DAG) const {
1380   if (!Subtarget->is64Bit())
1381     // This doesn't have DebugLoc associated with it, but is not really the
1382     // same as a Register.
1383     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1384   return Table;
1385 }
1386
1387 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1388 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1389 /// MCExpr.
1390 const MCExpr *X86TargetLowering::
1391 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1392                              MCContext &Ctx) const {
1393   // X86-64 uses RIP relative addressing based on the jump table label.
1394   if (Subtarget->isPICStyleRIPRel())
1395     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1396
1397   // Otherwise, the reference is relative to the PIC base.
1398   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1399 }
1400
1401 // FIXME: Why this routine is here? Move to RegInfo!
1402 std::pair<const TargetRegisterClass*, uint8_t>
1403 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1404   const TargetRegisterClass *RRC = 0;
1405   uint8_t Cost = 1;
1406   switch (VT.getSimpleVT().SimpleTy) {
1407   default:
1408     return TargetLowering::findRepresentativeClass(VT);
1409   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1410     RRC = Subtarget->is64Bit() ?
1411       (const TargetRegisterClass*)&X86::GR64RegClass :
1412       (const TargetRegisterClass*)&X86::GR32RegClass;
1413     break;
1414   case MVT::x86mmx:
1415     RRC = &X86::VR64RegClass;
1416     break;
1417   case MVT::f32: case MVT::f64:
1418   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1419   case MVT::v4f32: case MVT::v2f64:
1420   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1421   case MVT::v4f64:
1422     RRC = &X86::VR128RegClass;
1423     break;
1424   }
1425   return std::make_pair(RRC, Cost);
1426 }
1427
1428 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1429                                                unsigned &Offset) const {
1430   if (!Subtarget->isTargetLinux())
1431     return false;
1432
1433   if (Subtarget->is64Bit()) {
1434     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1435     Offset = 0x28;
1436     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1437       AddressSpace = 256;
1438     else
1439       AddressSpace = 257;
1440   } else {
1441     // %gs:0x14 on i386
1442     Offset = 0x14;
1443     AddressSpace = 256;
1444   }
1445   return true;
1446 }
1447
1448
1449 //===----------------------------------------------------------------------===//
1450 //               Return Value Calling Convention Implementation
1451 //===----------------------------------------------------------------------===//
1452
1453 #include "X86GenCallingConv.inc"
1454
1455 bool
1456 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1457                                   MachineFunction &MF, bool isVarArg,
1458                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1459                         LLVMContext &Context) const {
1460   SmallVector<CCValAssign, 16> RVLocs;
1461   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1462                  RVLocs, Context);
1463   return CCInfo.CheckReturn(Outs, RetCC_X86);
1464 }
1465
1466 SDValue
1467 X86TargetLowering::LowerReturn(SDValue Chain,
1468                                CallingConv::ID CallConv, bool isVarArg,
1469                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1470                                const SmallVectorImpl<SDValue> &OutVals,
1471                                DebugLoc dl, SelectionDAG &DAG) const {
1472   MachineFunction &MF = DAG.getMachineFunction();
1473   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1474
1475   SmallVector<CCValAssign, 16> RVLocs;
1476   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1477                  RVLocs, *DAG.getContext());
1478   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1479
1480   // Add the regs to the liveout set for the function.
1481   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1482   for (unsigned i = 0; i != RVLocs.size(); ++i)
1483     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1484       MRI.addLiveOut(RVLocs[i].getLocReg());
1485
1486   SDValue Flag;
1487
1488   SmallVector<SDValue, 6> RetOps;
1489   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1490   // Operand #1 = Bytes To Pop
1491   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1492                    MVT::i16));
1493
1494   // Copy the result values into the output registers.
1495   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1496     CCValAssign &VA = RVLocs[i];
1497     assert(VA.isRegLoc() && "Can only return in registers!");
1498     SDValue ValToCopy = OutVals[i];
1499     EVT ValVT = ValToCopy.getValueType();
1500
1501     // If this is x86-64, and we disabled SSE, we can't return FP values,
1502     // or SSE or MMX vectors.
1503     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1504          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1505           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1506       report_fatal_error("SSE register return with SSE disabled");
1507     }
1508     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1509     // llvm-gcc has never done it right and no one has noticed, so this
1510     // should be OK for now.
1511     if (ValVT == MVT::f64 &&
1512         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1513       report_fatal_error("SSE2 register return with SSE2 disabled");
1514
1515     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1516     // the RET instruction and handled by the FP Stackifier.
1517     if (VA.getLocReg() == X86::ST0 ||
1518         VA.getLocReg() == X86::ST1) {
1519       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1520       // change the value to the FP stack register class.
1521       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1522         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1523       RetOps.push_back(ValToCopy);
1524       // Don't emit a copytoreg.
1525       continue;
1526     }
1527
1528     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1529     // which is returned in RAX / RDX.
1530     if (Subtarget->is64Bit()) {
1531       if (ValVT == MVT::x86mmx) {
1532         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1533           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1534           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1535                                   ValToCopy);
1536           // If we don't have SSE2 available, convert to v4f32 so the generated
1537           // register is legal.
1538           if (!Subtarget->hasSSE2())
1539             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1540         }
1541       }
1542     }
1543
1544     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1545     Flag = Chain.getValue(1);
1546   }
1547
1548   // The x86-64 ABI for returning structs by value requires that we copy
1549   // the sret argument into %rax for the return. We saved the argument into
1550   // a virtual register in the entry block, so now we copy the value out
1551   // and into %rax.
1552   if (Subtarget->is64Bit() &&
1553       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1554     MachineFunction &MF = DAG.getMachineFunction();
1555     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1556     unsigned Reg = FuncInfo->getSRetReturnReg();
1557     assert(Reg &&
1558            "SRetReturnReg should have been set in LowerFormalArguments().");
1559     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1560
1561     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1562     Flag = Chain.getValue(1);
1563
1564     // RAX now acts like a return value.
1565     MRI.addLiveOut(X86::RAX);
1566   }
1567
1568   RetOps[0] = Chain;  // Update chain.
1569
1570   // Add the flag if we have it.
1571   if (Flag.getNode())
1572     RetOps.push_back(Flag);
1573
1574   return DAG.getNode(X86ISD::RET_FLAG, dl,
1575                      MVT::Other, &RetOps[0], RetOps.size());
1576 }
1577
1578 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1579   if (N->getNumValues() != 1)
1580     return false;
1581   if (!N->hasNUsesOfValue(1, 0))
1582     return false;
1583
1584   SDValue TCChain = Chain;
1585   SDNode *Copy = *N->use_begin();
1586   if (Copy->getOpcode() == ISD::CopyToReg) {
1587     // If the copy has a glue operand, we conservatively assume it isn't safe to
1588     // perform a tail call.
1589     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1590       return false;
1591     TCChain = Copy->getOperand(0);
1592   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1593     return false;
1594
1595   bool HasRet = false;
1596   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1597        UI != UE; ++UI) {
1598     if (UI->getOpcode() != X86ISD::RET_FLAG)
1599       return false;
1600     HasRet = true;
1601   }
1602
1603   if (!HasRet)
1604     return false;
1605
1606   Chain = TCChain;
1607   return true;
1608 }
1609
1610 EVT
1611 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1612                                             ISD::NodeType ExtendKind) const {
1613   MVT ReturnMVT;
1614   // TODO: Is this also valid on 32-bit?
1615   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1616     ReturnMVT = MVT::i8;
1617   else
1618     ReturnMVT = MVT::i32;
1619
1620   EVT MinVT = getRegisterType(Context, ReturnMVT);
1621   return VT.bitsLT(MinVT) ? MinVT : VT;
1622 }
1623
1624 /// LowerCallResult - Lower the result values of a call into the
1625 /// appropriate copies out of appropriate physical registers.
1626 ///
1627 SDValue
1628 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1629                                    CallingConv::ID CallConv, bool isVarArg,
1630                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1631                                    DebugLoc dl, SelectionDAG &DAG,
1632                                    SmallVectorImpl<SDValue> &InVals) const {
1633
1634   // Assign locations to each value returned by this call.
1635   SmallVector<CCValAssign, 16> RVLocs;
1636   bool Is64Bit = Subtarget->is64Bit();
1637   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1638                  getTargetMachine(), RVLocs, *DAG.getContext());
1639   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1640
1641   // Copy all of the result registers out of their specified physreg.
1642   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1643     CCValAssign &VA = RVLocs[i];
1644     EVT CopyVT = VA.getValVT();
1645
1646     // If this is x86-64, and we disabled SSE, we can't return FP values
1647     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1648         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1649       report_fatal_error("SSE register return with SSE disabled");
1650     }
1651
1652     SDValue Val;
1653
1654     // If this is a call to a function that returns an fp value on the floating
1655     // point stack, we must guarantee the the value is popped from the stack, so
1656     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1657     // if the return value is not used. We use the FpPOP_RETVAL instruction
1658     // instead.
1659     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1660       // If we prefer to use the value in xmm registers, copy it out as f80 and
1661       // use a truncate to move it from fp stack reg to xmm reg.
1662       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1663       SDValue Ops[] = { Chain, InFlag };
1664       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1665                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1666       Val = Chain.getValue(0);
1667
1668       // Round the f80 to the right size, which also moves it to the appropriate
1669       // xmm register.
1670       if (CopyVT != VA.getValVT())
1671         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1672                           // This truncation won't change the value.
1673                           DAG.getIntPtrConstant(1));
1674     } else {
1675       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1676                                  CopyVT, InFlag).getValue(1);
1677       Val = Chain.getValue(0);
1678     }
1679     InFlag = Chain.getValue(2);
1680     InVals.push_back(Val);
1681   }
1682
1683   return Chain;
1684 }
1685
1686
1687 //===----------------------------------------------------------------------===//
1688 //                C & StdCall & Fast Calling Convention implementation
1689 //===----------------------------------------------------------------------===//
1690 //  StdCall calling convention seems to be standard for many Windows' API
1691 //  routines and around. It differs from C calling convention just a little:
1692 //  callee should clean up the stack, not caller. Symbols should be also
1693 //  decorated in some fancy way :) It doesn't support any vector arguments.
1694 //  For info on fast calling convention see Fast Calling Convention (tail call)
1695 //  implementation LowerX86_32FastCCCallTo.
1696
1697 /// CallIsStructReturn - Determines whether a call uses struct return
1698 /// semantics.
1699 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1700   if (Outs.empty())
1701     return false;
1702
1703   return Outs[0].Flags.isSRet();
1704 }
1705
1706 /// ArgsAreStructReturn - Determines whether a function uses struct
1707 /// return semantics.
1708 static bool
1709 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1710   if (Ins.empty())
1711     return false;
1712
1713   return Ins[0].Flags.isSRet();
1714 }
1715
1716 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1717 /// by "Src" to address "Dst" with size and alignment information specified by
1718 /// the specific parameter attribute. The copy will be passed as a byval
1719 /// function parameter.
1720 static SDValue
1721 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1722                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1723                           DebugLoc dl) {
1724   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1725
1726   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1727                        /*isVolatile*/false, /*AlwaysInline=*/true,
1728                        MachinePointerInfo(), MachinePointerInfo());
1729 }
1730
1731 /// IsTailCallConvention - Return true if the calling convention is one that
1732 /// supports tail call optimization.
1733 static bool IsTailCallConvention(CallingConv::ID CC) {
1734   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1735 }
1736
1737 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1738   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1739     return false;
1740
1741   CallSite CS(CI);
1742   CallingConv::ID CalleeCC = CS.getCallingConv();
1743   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1744     return false;
1745
1746   return true;
1747 }
1748
1749 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1750 /// a tailcall target by changing its ABI.
1751 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1752                                    bool GuaranteedTailCallOpt) {
1753   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1754 }
1755
1756 SDValue
1757 X86TargetLowering::LowerMemArgument(SDValue Chain,
1758                                     CallingConv::ID CallConv,
1759                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1760                                     DebugLoc dl, SelectionDAG &DAG,
1761                                     const CCValAssign &VA,
1762                                     MachineFrameInfo *MFI,
1763                                     unsigned i) const {
1764   // Create the nodes corresponding to a load from this parameter slot.
1765   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1766   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1767                               getTargetMachine().Options.GuaranteedTailCallOpt);
1768   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1769   EVT ValVT;
1770
1771   // If value is passed by pointer we have address passed instead of the value
1772   // itself.
1773   if (VA.getLocInfo() == CCValAssign::Indirect)
1774     ValVT = VA.getLocVT();
1775   else
1776     ValVT = VA.getValVT();
1777
1778   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1779   // changed with more analysis.
1780   // In case of tail call optimization mark all arguments mutable. Since they
1781   // could be overwritten by lowering of arguments in case of a tail call.
1782   if (Flags.isByVal()) {
1783     unsigned Bytes = Flags.getByValSize();
1784     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1785     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1786     return DAG.getFrameIndex(FI, getPointerTy());
1787   } else {
1788     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1789                                     VA.getLocMemOffset(), isImmutable);
1790     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1791     return DAG.getLoad(ValVT, dl, Chain, FIN,
1792                        MachinePointerInfo::getFixedStack(FI),
1793                        false, false, false, 0);
1794   }
1795 }
1796
1797 SDValue
1798 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1799                                         CallingConv::ID CallConv,
1800                                         bool isVarArg,
1801                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1802                                         DebugLoc dl,
1803                                         SelectionDAG &DAG,
1804                                         SmallVectorImpl<SDValue> &InVals)
1805                                           const {
1806   MachineFunction &MF = DAG.getMachineFunction();
1807   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1808
1809   const Function* Fn = MF.getFunction();
1810   if (Fn->hasExternalLinkage() &&
1811       Subtarget->isTargetCygMing() &&
1812       Fn->getName() == "main")
1813     FuncInfo->setForceFramePointer(true);
1814
1815   MachineFrameInfo *MFI = MF.getFrameInfo();
1816   bool Is64Bit = Subtarget->is64Bit();
1817   bool IsWindows = Subtarget->isTargetWindows();
1818   bool IsWin64 = Subtarget->isTargetWin64();
1819
1820   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1821          "Var args not supported with calling convention fastcc or ghc");
1822
1823   // Assign locations to all of the incoming arguments.
1824   SmallVector<CCValAssign, 16> ArgLocs;
1825   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1826                  ArgLocs, *DAG.getContext());
1827
1828   // Allocate shadow area for Win64
1829   if (IsWin64) {
1830     CCInfo.AllocateStack(32, 8);
1831   }
1832
1833   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1834
1835   unsigned LastVal = ~0U;
1836   SDValue ArgValue;
1837   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1838     CCValAssign &VA = ArgLocs[i];
1839     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1840     // places.
1841     assert(VA.getValNo() != LastVal &&
1842            "Don't support value assigned to multiple locs yet");
1843     (void)LastVal;
1844     LastVal = VA.getValNo();
1845
1846     if (VA.isRegLoc()) {
1847       EVT RegVT = VA.getLocVT();
1848       const TargetRegisterClass *RC;
1849       if (RegVT == MVT::i32)
1850         RC = &X86::GR32RegClass;
1851       else if (Is64Bit && RegVT == MVT::i64)
1852         RC = &X86::GR64RegClass;
1853       else if (RegVT == MVT::f32)
1854         RC = &X86::FR32RegClass;
1855       else if (RegVT == MVT::f64)
1856         RC = &X86::FR64RegClass;
1857       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1858         RC = &X86::VR256RegClass;
1859       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1860         RC = &X86::VR128RegClass;
1861       else if (RegVT == MVT::x86mmx)
1862         RC = &X86::VR64RegClass;
1863       else
1864         llvm_unreachable("Unknown argument type!");
1865
1866       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1867       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1868
1869       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1870       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1871       // right size.
1872       if (VA.getLocInfo() == CCValAssign::SExt)
1873         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1874                                DAG.getValueType(VA.getValVT()));
1875       else if (VA.getLocInfo() == CCValAssign::ZExt)
1876         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1877                                DAG.getValueType(VA.getValVT()));
1878       else if (VA.getLocInfo() == CCValAssign::BCvt)
1879         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1880
1881       if (VA.isExtInLoc()) {
1882         // Handle MMX values passed in XMM regs.
1883         if (RegVT.isVector()) {
1884           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1885                                  ArgValue);
1886         } else
1887           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1888       }
1889     } else {
1890       assert(VA.isMemLoc());
1891       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1892     }
1893
1894     // If value is passed via pointer - do a load.
1895     if (VA.getLocInfo() == CCValAssign::Indirect)
1896       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1897                              MachinePointerInfo(), false, false, false, 0);
1898
1899     InVals.push_back(ArgValue);
1900   }
1901
1902   // The x86-64 ABI for returning structs by value requires that we copy
1903   // the sret argument into %rax for the return. Save the argument into
1904   // a virtual register so that we can access it from the return points.
1905   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1906     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1907     unsigned Reg = FuncInfo->getSRetReturnReg();
1908     if (!Reg) {
1909       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1910       FuncInfo->setSRetReturnReg(Reg);
1911     }
1912     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1913     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1914   }
1915
1916   unsigned StackSize = CCInfo.getNextStackOffset();
1917   // Align stack specially for tail calls.
1918   if (FuncIsMadeTailCallSafe(CallConv,
1919                              MF.getTarget().Options.GuaranteedTailCallOpt))
1920     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1921
1922   // If the function takes variable number of arguments, make a frame index for
1923   // the start of the first vararg value... for expansion of llvm.va_start.
1924   if (isVarArg) {
1925     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1926                     CallConv != CallingConv::X86_ThisCall)) {
1927       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1928     }
1929     if (Is64Bit) {
1930       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1931
1932       // FIXME: We should really autogenerate these arrays
1933       static const uint16_t GPR64ArgRegsWin64[] = {
1934         X86::RCX, X86::RDX, X86::R8,  X86::R9
1935       };
1936       static const uint16_t GPR64ArgRegs64Bit[] = {
1937         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1938       };
1939       static const uint16_t XMMArgRegs64Bit[] = {
1940         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1941         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1942       };
1943       const uint16_t *GPR64ArgRegs;
1944       unsigned NumXMMRegs = 0;
1945
1946       if (IsWin64) {
1947         // The XMM registers which might contain var arg parameters are shadowed
1948         // in their paired GPR.  So we only need to save the GPR to their home
1949         // slots.
1950         TotalNumIntRegs = 4;
1951         GPR64ArgRegs = GPR64ArgRegsWin64;
1952       } else {
1953         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1954         GPR64ArgRegs = GPR64ArgRegs64Bit;
1955
1956         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1957                                                 TotalNumXMMRegs);
1958       }
1959       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1960                                                        TotalNumIntRegs);
1961
1962       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1963       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1964              "SSE register cannot be used when SSE is disabled!");
1965       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1966                NoImplicitFloatOps) &&
1967              "SSE register cannot be used when SSE is disabled!");
1968       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1969           !Subtarget->hasSSE1())
1970         // Kernel mode asks for SSE to be disabled, so don't push them
1971         // on the stack.
1972         TotalNumXMMRegs = 0;
1973
1974       if (IsWin64) {
1975         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1976         // Get to the caller-allocated home save location.  Add 8 to account
1977         // for the return address.
1978         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1979         FuncInfo->setRegSaveFrameIndex(
1980           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1981         // Fixup to set vararg frame on shadow area (4 x i64).
1982         if (NumIntRegs < 4)
1983           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1984       } else {
1985         // For X86-64, if there are vararg parameters that are passed via
1986         // registers, then we must store them to their spots on the stack so
1987         // they may be loaded by deferencing the result of va_next.
1988         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1989         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1990         FuncInfo->setRegSaveFrameIndex(
1991           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1992                                false));
1993       }
1994
1995       // Store the integer parameter registers.
1996       SmallVector<SDValue, 8> MemOps;
1997       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1998                                         getPointerTy());
1999       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2000       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2001         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2002                                   DAG.getIntPtrConstant(Offset));
2003         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2004                                      &X86::GR64RegClass);
2005         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2006         SDValue Store =
2007           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2008                        MachinePointerInfo::getFixedStack(
2009                          FuncInfo->getRegSaveFrameIndex(), Offset),
2010                        false, false, 0);
2011         MemOps.push_back(Store);
2012         Offset += 8;
2013       }
2014
2015       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2016         // Now store the XMM (fp + vector) parameter registers.
2017         SmallVector<SDValue, 11> SaveXMMOps;
2018         SaveXMMOps.push_back(Chain);
2019
2020         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2021         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2022         SaveXMMOps.push_back(ALVal);
2023
2024         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2025                                FuncInfo->getRegSaveFrameIndex()));
2026         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2027                                FuncInfo->getVarArgsFPOffset()));
2028
2029         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2030           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2031                                        &X86::VR128RegClass);
2032           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2033           SaveXMMOps.push_back(Val);
2034         }
2035         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2036                                      MVT::Other,
2037                                      &SaveXMMOps[0], SaveXMMOps.size()));
2038       }
2039
2040       if (!MemOps.empty())
2041         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2042                             &MemOps[0], MemOps.size());
2043     }
2044   }
2045
2046   // Some CCs need callee pop.
2047   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2048                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2049     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2050   } else {
2051     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2052     // If this is an sret function, the return should pop the hidden pointer.
2053     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2054         ArgsAreStructReturn(Ins))
2055       FuncInfo->setBytesToPopOnReturn(4);
2056   }
2057
2058   if (!Is64Bit) {
2059     // RegSaveFrameIndex is X86-64 only.
2060     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2061     if (CallConv == CallingConv::X86_FastCall ||
2062         CallConv == CallingConv::X86_ThisCall)
2063       // fastcc functions can't have varargs.
2064       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2065   }
2066
2067   FuncInfo->setArgumentStackSize(StackSize);
2068
2069   return Chain;
2070 }
2071
2072 SDValue
2073 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2074                                     SDValue StackPtr, SDValue Arg,
2075                                     DebugLoc dl, SelectionDAG &DAG,
2076                                     const CCValAssign &VA,
2077                                     ISD::ArgFlagsTy Flags) const {
2078   unsigned LocMemOffset = VA.getLocMemOffset();
2079   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2080   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2081   if (Flags.isByVal())
2082     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2083
2084   return DAG.getStore(Chain, dl, Arg, PtrOff,
2085                       MachinePointerInfo::getStack(LocMemOffset),
2086                       false, false, 0);
2087 }
2088
2089 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2090 /// optimization is performed and it is required.
2091 SDValue
2092 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2093                                            SDValue &OutRetAddr, SDValue Chain,
2094                                            bool IsTailCall, bool Is64Bit,
2095                                            int FPDiff, DebugLoc dl) const {
2096   // Adjust the Return address stack slot.
2097   EVT VT = getPointerTy();
2098   OutRetAddr = getReturnAddressFrameIndex(DAG);
2099
2100   // Load the "old" Return address.
2101   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2102                            false, false, false, 0);
2103   return SDValue(OutRetAddr.getNode(), 1);
2104 }
2105
2106 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2107 /// optimization is performed and it is required (FPDiff!=0).
2108 static SDValue
2109 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2110                          SDValue Chain, SDValue RetAddrFrIdx,
2111                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2112   // Store the return address to the appropriate stack slot.
2113   if (!FPDiff) return Chain;
2114   // Calculate the new stack slot for the return address.
2115   int SlotSize = Is64Bit ? 8 : 4;
2116   int NewReturnAddrFI =
2117     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2118   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2119   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2120   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2121                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2122                        false, false, 0);
2123   return Chain;
2124 }
2125
2126 SDValue
2127 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2128                              CallingConv::ID CallConv, bool isVarArg,
2129                              bool doesNotRet, bool &isTailCall,
2130                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2131                              const SmallVectorImpl<SDValue> &OutVals,
2132                              const SmallVectorImpl<ISD::InputArg> &Ins,
2133                              DebugLoc dl, SelectionDAG &DAG,
2134                              SmallVectorImpl<SDValue> &InVals) const {
2135   MachineFunction &MF = DAG.getMachineFunction();
2136   bool Is64Bit        = Subtarget->is64Bit();
2137   bool IsWin64        = Subtarget->isTargetWin64();
2138   bool IsWindows      = Subtarget->isTargetWindows();
2139   bool IsStructRet    = CallIsStructReturn(Outs);
2140   bool IsSibcall      = false;
2141
2142   if (MF.getTarget().Options.DisableTailCalls)
2143     isTailCall = false;
2144
2145   if (isTailCall) {
2146     // Check if it's really possible to do a tail call.
2147     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2148                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2149                                                    Outs, OutVals, Ins, DAG);
2150
2151     // Sibcalls are automatically detected tailcalls which do not require
2152     // ABI changes.
2153     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2154       IsSibcall = true;
2155
2156     if (isTailCall)
2157       ++NumTailCalls;
2158   }
2159
2160   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2161          "Var args not supported with calling convention fastcc or ghc");
2162
2163   // Analyze operands of the call, assigning locations to each operand.
2164   SmallVector<CCValAssign, 16> ArgLocs;
2165   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2166                  ArgLocs, *DAG.getContext());
2167
2168   // Allocate shadow area for Win64
2169   if (IsWin64) {
2170     CCInfo.AllocateStack(32, 8);
2171   }
2172
2173   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2174
2175   // Get a count of how many bytes are to be pushed on the stack.
2176   unsigned NumBytes = CCInfo.getNextStackOffset();
2177   if (IsSibcall)
2178     // This is a sibcall. The memory operands are available in caller's
2179     // own caller's stack.
2180     NumBytes = 0;
2181   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2182            IsTailCallConvention(CallConv))
2183     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2184
2185   int FPDiff = 0;
2186   if (isTailCall && !IsSibcall) {
2187     // Lower arguments at fp - stackoffset + fpdiff.
2188     unsigned NumBytesCallerPushed =
2189       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2190     FPDiff = NumBytesCallerPushed - NumBytes;
2191
2192     // Set the delta of movement of the returnaddr stackslot.
2193     // But only set if delta is greater than previous delta.
2194     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2195       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2196   }
2197
2198   if (!IsSibcall)
2199     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2200
2201   SDValue RetAddrFrIdx;
2202   // Load return address for tail calls.
2203   if (isTailCall && FPDiff)
2204     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2205                                     Is64Bit, FPDiff, dl);
2206
2207   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2208   SmallVector<SDValue, 8> MemOpChains;
2209   SDValue StackPtr;
2210
2211   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2212   // of tail call optimization arguments are handle later.
2213   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2214     CCValAssign &VA = ArgLocs[i];
2215     EVT RegVT = VA.getLocVT();
2216     SDValue Arg = OutVals[i];
2217     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2218     bool isByVal = Flags.isByVal();
2219
2220     // Promote the value if needed.
2221     switch (VA.getLocInfo()) {
2222     default: llvm_unreachable("Unknown loc info!");
2223     case CCValAssign::Full: break;
2224     case CCValAssign::SExt:
2225       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2226       break;
2227     case CCValAssign::ZExt:
2228       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2229       break;
2230     case CCValAssign::AExt:
2231       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2232         // Special case: passing MMX values in XMM registers.
2233         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2234         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2235         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2236       } else
2237         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2238       break;
2239     case CCValAssign::BCvt:
2240       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2241       break;
2242     case CCValAssign::Indirect: {
2243       // Store the argument.
2244       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2245       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2246       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2247                            MachinePointerInfo::getFixedStack(FI),
2248                            false, false, 0);
2249       Arg = SpillSlot;
2250       break;
2251     }
2252     }
2253
2254     if (VA.isRegLoc()) {
2255       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2256       if (isVarArg && IsWin64) {
2257         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2258         // shadow reg if callee is a varargs function.
2259         unsigned ShadowReg = 0;
2260         switch (VA.getLocReg()) {
2261         case X86::XMM0: ShadowReg = X86::RCX; break;
2262         case X86::XMM1: ShadowReg = X86::RDX; break;
2263         case X86::XMM2: ShadowReg = X86::R8; break;
2264         case X86::XMM3: ShadowReg = X86::R9; break;
2265         }
2266         if (ShadowReg)
2267           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2268       }
2269     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2270       assert(VA.isMemLoc());
2271       if (StackPtr.getNode() == 0)
2272         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2273       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2274                                              dl, DAG, VA, Flags));
2275     }
2276   }
2277
2278   if (!MemOpChains.empty())
2279     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2280                         &MemOpChains[0], MemOpChains.size());
2281
2282   // Build a sequence of copy-to-reg nodes chained together with token chain
2283   // and flag operands which copy the outgoing args into registers.
2284   SDValue InFlag;
2285   // Tail call byval lowering might overwrite argument registers so in case of
2286   // tail call optimization the copies to registers are lowered later.
2287   if (!isTailCall)
2288     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2289       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2290                                RegsToPass[i].second, InFlag);
2291       InFlag = Chain.getValue(1);
2292     }
2293
2294   if (Subtarget->isPICStyleGOT()) {
2295     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2296     // GOT pointer.
2297     if (!isTailCall) {
2298       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2299                                DAG.getNode(X86ISD::GlobalBaseReg,
2300                                            DebugLoc(), getPointerTy()),
2301                                InFlag);
2302       InFlag = Chain.getValue(1);
2303     } else {
2304       // If we are tail calling and generating PIC/GOT style code load the
2305       // address of the callee into ECX. The value in ecx is used as target of
2306       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2307       // for tail calls on PIC/GOT architectures. Normally we would just put the
2308       // address of GOT into ebx and then call target@PLT. But for tail calls
2309       // ebx would be restored (since ebx is callee saved) before jumping to the
2310       // target@PLT.
2311
2312       // Note: The actual moving to ECX is done further down.
2313       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2314       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2315           !G->getGlobal()->hasProtectedVisibility())
2316         Callee = LowerGlobalAddress(Callee, DAG);
2317       else if (isa<ExternalSymbolSDNode>(Callee))
2318         Callee = LowerExternalSymbol(Callee, DAG);
2319     }
2320   }
2321
2322   if (Is64Bit && isVarArg && !IsWin64) {
2323     // From AMD64 ABI document:
2324     // For calls that may call functions that use varargs or stdargs
2325     // (prototype-less calls or calls to functions containing ellipsis (...) in
2326     // the declaration) %al is used as hidden argument to specify the number
2327     // of SSE registers used. The contents of %al do not need to match exactly
2328     // the number of registers, but must be an ubound on the number of SSE
2329     // registers used and is in the range 0 - 8 inclusive.
2330
2331     // Count the number of XMM registers allocated.
2332     static const uint16_t XMMArgRegs[] = {
2333       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2334       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2335     };
2336     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2337     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2338            && "SSE registers cannot be used when SSE is disabled");
2339
2340     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2341                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2342     InFlag = Chain.getValue(1);
2343   }
2344
2345
2346   // For tail calls lower the arguments to the 'real' stack slot.
2347   if (isTailCall) {
2348     // Force all the incoming stack arguments to be loaded from the stack
2349     // before any new outgoing arguments are stored to the stack, because the
2350     // outgoing stack slots may alias the incoming argument stack slots, and
2351     // the alias isn't otherwise explicit. This is slightly more conservative
2352     // than necessary, because it means that each store effectively depends
2353     // on every argument instead of just those arguments it would clobber.
2354     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2355
2356     SmallVector<SDValue, 8> MemOpChains2;
2357     SDValue FIN;
2358     int FI = 0;
2359     // Do not flag preceding copytoreg stuff together with the following stuff.
2360     InFlag = SDValue();
2361     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2362       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2363         CCValAssign &VA = ArgLocs[i];
2364         if (VA.isRegLoc())
2365           continue;
2366         assert(VA.isMemLoc());
2367         SDValue Arg = OutVals[i];
2368         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2369         // Create frame index.
2370         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2371         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2372         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2373         FIN = DAG.getFrameIndex(FI, getPointerTy());
2374
2375         if (Flags.isByVal()) {
2376           // Copy relative to framepointer.
2377           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2378           if (StackPtr.getNode() == 0)
2379             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2380                                           getPointerTy());
2381           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2382
2383           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2384                                                            ArgChain,
2385                                                            Flags, DAG, dl));
2386         } else {
2387           // Store relative to framepointer.
2388           MemOpChains2.push_back(
2389             DAG.getStore(ArgChain, dl, Arg, FIN,
2390                          MachinePointerInfo::getFixedStack(FI),
2391                          false, false, 0));
2392         }
2393       }
2394     }
2395
2396     if (!MemOpChains2.empty())
2397       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2398                           &MemOpChains2[0], MemOpChains2.size());
2399
2400     // Copy arguments to their registers.
2401     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2402       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2403                                RegsToPass[i].second, InFlag);
2404       InFlag = Chain.getValue(1);
2405     }
2406     InFlag =SDValue();
2407
2408     // Store the return address to the appropriate stack slot.
2409     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2410                                      FPDiff, dl);
2411   }
2412
2413   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2414     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2415     // In the 64-bit large code model, we have to make all calls
2416     // through a register, since the call instruction's 32-bit
2417     // pc-relative offset may not be large enough to hold the whole
2418     // address.
2419   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2420     // If the callee is a GlobalAddress node (quite common, every direct call
2421     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2422     // it.
2423
2424     // We should use extra load for direct calls to dllimported functions in
2425     // non-JIT mode.
2426     const GlobalValue *GV = G->getGlobal();
2427     if (!GV->hasDLLImportLinkage()) {
2428       unsigned char OpFlags = 0;
2429       bool ExtraLoad = false;
2430       unsigned WrapperKind = ISD::DELETED_NODE;
2431
2432       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2433       // external symbols most go through the PLT in PIC mode.  If the symbol
2434       // has hidden or protected visibility, or if it is static or local, then
2435       // we don't need to use the PLT - we can directly call it.
2436       if (Subtarget->isTargetELF() &&
2437           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2438           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2439         OpFlags = X86II::MO_PLT;
2440       } else if (Subtarget->isPICStyleStubAny() &&
2441                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2442                  (!Subtarget->getTargetTriple().isMacOSX() ||
2443                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2444         // PC-relative references to external symbols should go through $stub,
2445         // unless we're building with the leopard linker or later, which
2446         // automatically synthesizes these stubs.
2447         OpFlags = X86II::MO_DARWIN_STUB;
2448       } else if (Subtarget->isPICStyleRIPRel() &&
2449                  isa<Function>(GV) &&
2450                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2451         // If the function is marked as non-lazy, generate an indirect call
2452         // which loads from the GOT directly. This avoids runtime overhead
2453         // at the cost of eager binding (and one extra byte of encoding).
2454         OpFlags = X86II::MO_GOTPCREL;
2455         WrapperKind = X86ISD::WrapperRIP;
2456         ExtraLoad = true;
2457       }
2458
2459       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2460                                           G->getOffset(), OpFlags);
2461
2462       // Add a wrapper if needed.
2463       if (WrapperKind != ISD::DELETED_NODE)
2464         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2465       // Add extra indirection if needed.
2466       if (ExtraLoad)
2467         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2468                              MachinePointerInfo::getGOT(),
2469                              false, false, false, 0);
2470     }
2471   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2472     unsigned char OpFlags = 0;
2473
2474     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2475     // external symbols should go through the PLT.
2476     if (Subtarget->isTargetELF() &&
2477         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2478       OpFlags = X86II::MO_PLT;
2479     } else if (Subtarget->isPICStyleStubAny() &&
2480                (!Subtarget->getTargetTriple().isMacOSX() ||
2481                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2482       // PC-relative references to external symbols should go through $stub,
2483       // unless we're building with the leopard linker or later, which
2484       // automatically synthesizes these stubs.
2485       OpFlags = X86II::MO_DARWIN_STUB;
2486     }
2487
2488     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2489                                          OpFlags);
2490   }
2491
2492   // Returns a chain & a flag for retval copy to use.
2493   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2494   SmallVector<SDValue, 8> Ops;
2495
2496   if (!IsSibcall && isTailCall) {
2497     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2498                            DAG.getIntPtrConstant(0, true), InFlag);
2499     InFlag = Chain.getValue(1);
2500   }
2501
2502   Ops.push_back(Chain);
2503   Ops.push_back(Callee);
2504
2505   if (isTailCall)
2506     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2507
2508   // Add argument registers to the end of the list so that they are known live
2509   // into the call.
2510   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2511     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2512                                   RegsToPass[i].second.getValueType()));
2513
2514   // Add an implicit use GOT pointer in EBX.
2515   if (!isTailCall && Subtarget->isPICStyleGOT())
2516     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2517
2518   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2519   if (Is64Bit && isVarArg && !IsWin64)
2520     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2521
2522   // Add a register mask operand representing the call-preserved registers.
2523   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2524   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2525   assert(Mask && "Missing call preserved mask for calling convention");
2526   Ops.push_back(DAG.getRegisterMask(Mask));
2527
2528   if (InFlag.getNode())
2529     Ops.push_back(InFlag);
2530
2531   if (isTailCall) {
2532     // We used to do:
2533     //// If this is the first return lowered for this function, add the regs
2534     //// to the liveout set for the function.
2535     // This isn't right, although it's probably harmless on x86; liveouts
2536     // should be computed from returns not tail calls.  Consider a void
2537     // function making a tail call to a function returning int.
2538     return DAG.getNode(X86ISD::TC_RETURN, dl,
2539                        NodeTys, &Ops[0], Ops.size());
2540   }
2541
2542   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2543   InFlag = Chain.getValue(1);
2544
2545   // Create the CALLSEQ_END node.
2546   unsigned NumBytesForCalleeToPush;
2547   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2548                        getTargetMachine().Options.GuaranteedTailCallOpt))
2549     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2550   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2551            IsStructRet)
2552     // If this is a call to a struct-return function, the callee
2553     // pops the hidden struct pointer, so we have to push it back.
2554     // This is common for Darwin/X86, Linux & Mingw32 targets.
2555     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2556     NumBytesForCalleeToPush = 4;
2557   else
2558     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2559
2560   // Returns a flag for retval copy to use.
2561   if (!IsSibcall) {
2562     Chain = DAG.getCALLSEQ_END(Chain,
2563                                DAG.getIntPtrConstant(NumBytes, true),
2564                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2565                                                      true),
2566                                InFlag);
2567     InFlag = Chain.getValue(1);
2568   }
2569
2570   // Handle result values, copying them out of physregs into vregs that we
2571   // return.
2572   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2573                          Ins, dl, DAG, InVals);
2574 }
2575
2576
2577 //===----------------------------------------------------------------------===//
2578 //                Fast Calling Convention (tail call) implementation
2579 //===----------------------------------------------------------------------===//
2580
2581 //  Like std call, callee cleans arguments, convention except that ECX is
2582 //  reserved for storing the tail called function address. Only 2 registers are
2583 //  free for argument passing (inreg). Tail call optimization is performed
2584 //  provided:
2585 //                * tailcallopt is enabled
2586 //                * caller/callee are fastcc
2587 //  On X86_64 architecture with GOT-style position independent code only local
2588 //  (within module) calls are supported at the moment.
2589 //  To keep the stack aligned according to platform abi the function
2590 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2591 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2592 //  If a tail called function callee has more arguments than the caller the
2593 //  caller needs to make sure that there is room to move the RETADDR to. This is
2594 //  achieved by reserving an area the size of the argument delta right after the
2595 //  original REtADDR, but before the saved framepointer or the spilled registers
2596 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2597 //  stack layout:
2598 //    arg1
2599 //    arg2
2600 //    RETADDR
2601 //    [ new RETADDR
2602 //      move area ]
2603 //    (possible EBP)
2604 //    ESI
2605 //    EDI
2606 //    local1 ..
2607
2608 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2609 /// for a 16 byte align requirement.
2610 unsigned
2611 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2612                                                SelectionDAG& DAG) const {
2613   MachineFunction &MF = DAG.getMachineFunction();
2614   const TargetMachine &TM = MF.getTarget();
2615   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2616   unsigned StackAlignment = TFI.getStackAlignment();
2617   uint64_t AlignMask = StackAlignment - 1;
2618   int64_t Offset = StackSize;
2619   uint64_t SlotSize = TD->getPointerSize();
2620   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2621     // Number smaller than 12 so just add the difference.
2622     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2623   } else {
2624     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2625     Offset = ((~AlignMask) & Offset) + StackAlignment +
2626       (StackAlignment-SlotSize);
2627   }
2628   return Offset;
2629 }
2630
2631 /// MatchingStackOffset - Return true if the given stack call argument is
2632 /// already available in the same position (relatively) of the caller's
2633 /// incoming argument stack.
2634 static
2635 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2636                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2637                          const X86InstrInfo *TII) {
2638   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2639   int FI = INT_MAX;
2640   if (Arg.getOpcode() == ISD::CopyFromReg) {
2641     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2642     if (!TargetRegisterInfo::isVirtualRegister(VR))
2643       return false;
2644     MachineInstr *Def = MRI->getVRegDef(VR);
2645     if (!Def)
2646       return false;
2647     if (!Flags.isByVal()) {
2648       if (!TII->isLoadFromStackSlot(Def, FI))
2649         return false;
2650     } else {
2651       unsigned Opcode = Def->getOpcode();
2652       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2653           Def->getOperand(1).isFI()) {
2654         FI = Def->getOperand(1).getIndex();
2655         Bytes = Flags.getByValSize();
2656       } else
2657         return false;
2658     }
2659   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2660     if (Flags.isByVal())
2661       // ByVal argument is passed in as a pointer but it's now being
2662       // dereferenced. e.g.
2663       // define @foo(%struct.X* %A) {
2664       //   tail call @bar(%struct.X* byval %A)
2665       // }
2666       return false;
2667     SDValue Ptr = Ld->getBasePtr();
2668     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2669     if (!FINode)
2670       return false;
2671     FI = FINode->getIndex();
2672   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2673     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2674     FI = FINode->getIndex();
2675     Bytes = Flags.getByValSize();
2676   } else
2677     return false;
2678
2679   assert(FI != INT_MAX);
2680   if (!MFI->isFixedObjectIndex(FI))
2681     return false;
2682   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2683 }
2684
2685 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2686 /// for tail call optimization. Targets which want to do tail call
2687 /// optimization should implement this function.
2688 bool
2689 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2690                                                      CallingConv::ID CalleeCC,
2691                                                      bool isVarArg,
2692                                                      bool isCalleeStructRet,
2693                                                      bool isCallerStructRet,
2694                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2695                                     const SmallVectorImpl<SDValue> &OutVals,
2696                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2697                                                      SelectionDAG& DAG) const {
2698   if (!IsTailCallConvention(CalleeCC) &&
2699       CalleeCC != CallingConv::C)
2700     return false;
2701
2702   // If -tailcallopt is specified, make fastcc functions tail-callable.
2703   const MachineFunction &MF = DAG.getMachineFunction();
2704   const Function *CallerF = DAG.getMachineFunction().getFunction();
2705   CallingConv::ID CallerCC = CallerF->getCallingConv();
2706   bool CCMatch = CallerCC == CalleeCC;
2707
2708   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2709     if (IsTailCallConvention(CalleeCC) && CCMatch)
2710       return true;
2711     return false;
2712   }
2713
2714   // Look for obvious safe cases to perform tail call optimization that do not
2715   // require ABI changes. This is what gcc calls sibcall.
2716
2717   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2718   // emit a special epilogue.
2719   if (RegInfo->needsStackRealignment(MF))
2720     return false;
2721
2722   // Also avoid sibcall optimization if either caller or callee uses struct
2723   // return semantics.
2724   if (isCalleeStructRet || isCallerStructRet)
2725     return false;
2726
2727   // An stdcall caller is expected to clean up its arguments; the callee
2728   // isn't going to do that.
2729   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2730     return false;
2731
2732   // Do not sibcall optimize vararg calls unless all arguments are passed via
2733   // registers.
2734   if (isVarArg && !Outs.empty()) {
2735
2736     // Optimizing for varargs on Win64 is unlikely to be safe without
2737     // additional testing.
2738     if (Subtarget->isTargetWin64())
2739       return false;
2740
2741     SmallVector<CCValAssign, 16> ArgLocs;
2742     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2743                    getTargetMachine(), ArgLocs, *DAG.getContext());
2744
2745     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2746     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2747       if (!ArgLocs[i].isRegLoc())
2748         return false;
2749   }
2750
2751   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2752   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2753   // this into a sibcall.
2754   bool Unused = false;
2755   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2756     if (!Ins[i].Used) {
2757       Unused = true;
2758       break;
2759     }
2760   }
2761   if (Unused) {
2762     SmallVector<CCValAssign, 16> RVLocs;
2763     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2764                    getTargetMachine(), RVLocs, *DAG.getContext());
2765     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2766     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2767       CCValAssign &VA = RVLocs[i];
2768       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2769         return false;
2770     }
2771   }
2772
2773   // If the calling conventions do not match, then we'd better make sure the
2774   // results are returned in the same way as what the caller expects.
2775   if (!CCMatch) {
2776     SmallVector<CCValAssign, 16> RVLocs1;
2777     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2778                     getTargetMachine(), RVLocs1, *DAG.getContext());
2779     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2780
2781     SmallVector<CCValAssign, 16> RVLocs2;
2782     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2783                     getTargetMachine(), RVLocs2, *DAG.getContext());
2784     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2785
2786     if (RVLocs1.size() != RVLocs2.size())
2787       return false;
2788     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2789       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2790         return false;
2791       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2792         return false;
2793       if (RVLocs1[i].isRegLoc()) {
2794         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2795           return false;
2796       } else {
2797         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2798           return false;
2799       }
2800     }
2801   }
2802
2803   // If the callee takes no arguments then go on to check the results of the
2804   // call.
2805   if (!Outs.empty()) {
2806     // Check if stack adjustment is needed. For now, do not do this if any
2807     // argument is passed on the stack.
2808     SmallVector<CCValAssign, 16> ArgLocs;
2809     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2810                    getTargetMachine(), ArgLocs, *DAG.getContext());
2811
2812     // Allocate shadow area for Win64
2813     if (Subtarget->isTargetWin64()) {
2814       CCInfo.AllocateStack(32, 8);
2815     }
2816
2817     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2818     if (CCInfo.getNextStackOffset()) {
2819       MachineFunction &MF = DAG.getMachineFunction();
2820       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2821         return false;
2822
2823       // Check if the arguments are already laid out in the right way as
2824       // the caller's fixed stack objects.
2825       MachineFrameInfo *MFI = MF.getFrameInfo();
2826       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2827       const X86InstrInfo *TII =
2828         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2829       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2830         CCValAssign &VA = ArgLocs[i];
2831         SDValue Arg = OutVals[i];
2832         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2833         if (VA.getLocInfo() == CCValAssign::Indirect)
2834           return false;
2835         if (!VA.isRegLoc()) {
2836           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2837                                    MFI, MRI, TII))
2838             return false;
2839         }
2840       }
2841     }
2842
2843     // If the tailcall address may be in a register, then make sure it's
2844     // possible to register allocate for it. In 32-bit, the call address can
2845     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2846     // callee-saved registers are restored. These happen to be the same
2847     // registers used to pass 'inreg' arguments so watch out for those.
2848     if (!Subtarget->is64Bit() &&
2849         !isa<GlobalAddressSDNode>(Callee) &&
2850         !isa<ExternalSymbolSDNode>(Callee)) {
2851       unsigned NumInRegs = 0;
2852       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2853         CCValAssign &VA = ArgLocs[i];
2854         if (!VA.isRegLoc())
2855           continue;
2856         unsigned Reg = VA.getLocReg();
2857         switch (Reg) {
2858         default: break;
2859         case X86::EAX: case X86::EDX: case X86::ECX:
2860           if (++NumInRegs == 3)
2861             return false;
2862           break;
2863         }
2864       }
2865     }
2866   }
2867
2868   return true;
2869 }
2870
2871 FastISel *
2872 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2873   return X86::createFastISel(funcInfo);
2874 }
2875
2876
2877 //===----------------------------------------------------------------------===//
2878 //                           Other Lowering Hooks
2879 //===----------------------------------------------------------------------===//
2880
2881 static bool MayFoldLoad(SDValue Op) {
2882   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2883 }
2884
2885 static bool MayFoldIntoStore(SDValue Op) {
2886   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2887 }
2888
2889 static bool isTargetShuffle(unsigned Opcode) {
2890   switch(Opcode) {
2891   default: return false;
2892   case X86ISD::PSHUFD:
2893   case X86ISD::PSHUFHW:
2894   case X86ISD::PSHUFLW:
2895   case X86ISD::SHUFP:
2896   case X86ISD::PALIGN:
2897   case X86ISD::MOVLHPS:
2898   case X86ISD::MOVLHPD:
2899   case X86ISD::MOVHLPS:
2900   case X86ISD::MOVLPS:
2901   case X86ISD::MOVLPD:
2902   case X86ISD::MOVSHDUP:
2903   case X86ISD::MOVSLDUP:
2904   case X86ISD::MOVDDUP:
2905   case X86ISD::MOVSS:
2906   case X86ISD::MOVSD:
2907   case X86ISD::UNPCKL:
2908   case X86ISD::UNPCKH:
2909   case X86ISD::VPERMILP:
2910   case X86ISD::VPERM2X128:
2911     return true;
2912   }
2913 }
2914
2915 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2916                                     SDValue V1, SelectionDAG &DAG) {
2917   switch(Opc) {
2918   default: llvm_unreachable("Unknown x86 shuffle node");
2919   case X86ISD::MOVSHDUP:
2920   case X86ISD::MOVSLDUP:
2921   case X86ISD::MOVDDUP:
2922     return DAG.getNode(Opc, dl, VT, V1);
2923   }
2924 }
2925
2926 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2927                                     SDValue V1, unsigned TargetMask,
2928                                     SelectionDAG &DAG) {
2929   switch(Opc) {
2930   default: llvm_unreachable("Unknown x86 shuffle node");
2931   case X86ISD::PSHUFD:
2932   case X86ISD::PSHUFHW:
2933   case X86ISD::PSHUFLW:
2934   case X86ISD::VPERMILP:
2935   case X86ISD::VPERMI:
2936     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2937   }
2938 }
2939
2940 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2941                                     SDValue V1, SDValue V2, unsigned TargetMask,
2942                                     SelectionDAG &DAG) {
2943   switch(Opc) {
2944   default: llvm_unreachable("Unknown x86 shuffle node");
2945   case X86ISD::PALIGN:
2946   case X86ISD::SHUFP:
2947   case X86ISD::VPERM2X128:
2948     return DAG.getNode(Opc, dl, VT, V1, V2,
2949                        DAG.getConstant(TargetMask, MVT::i8));
2950   }
2951 }
2952
2953 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2954                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2955   switch(Opc) {
2956   default: llvm_unreachable("Unknown x86 shuffle node");
2957   case X86ISD::MOVLHPS:
2958   case X86ISD::MOVLHPD:
2959   case X86ISD::MOVHLPS:
2960   case X86ISD::MOVLPS:
2961   case X86ISD::MOVLPD:
2962   case X86ISD::MOVSS:
2963   case X86ISD::MOVSD:
2964   case X86ISD::UNPCKL:
2965   case X86ISD::UNPCKH:
2966     return DAG.getNode(Opc, dl, VT, V1, V2);
2967   }
2968 }
2969
2970 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2971   MachineFunction &MF = DAG.getMachineFunction();
2972   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2973   int ReturnAddrIndex = FuncInfo->getRAIndex();
2974
2975   if (ReturnAddrIndex == 0) {
2976     // Set up a frame object for the return address.
2977     uint64_t SlotSize = TD->getPointerSize();
2978     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2979                                                            false);
2980     FuncInfo->setRAIndex(ReturnAddrIndex);
2981   }
2982
2983   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2984 }
2985
2986
2987 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2988                                        bool hasSymbolicDisplacement) {
2989   // Offset should fit into 32 bit immediate field.
2990   if (!isInt<32>(Offset))
2991     return false;
2992
2993   // If we don't have a symbolic displacement - we don't have any extra
2994   // restrictions.
2995   if (!hasSymbolicDisplacement)
2996     return true;
2997
2998   // FIXME: Some tweaks might be needed for medium code model.
2999   if (M != CodeModel::Small && M != CodeModel::Kernel)
3000     return false;
3001
3002   // For small code model we assume that latest object is 16MB before end of 31
3003   // bits boundary. We may also accept pretty large negative constants knowing
3004   // that all objects are in the positive half of address space.
3005   if (M == CodeModel::Small && Offset < 16*1024*1024)
3006     return true;
3007
3008   // For kernel code model we know that all object resist in the negative half
3009   // of 32bits address space. We may not accept negative offsets, since they may
3010   // be just off and we may accept pretty large positive ones.
3011   if (M == CodeModel::Kernel && Offset > 0)
3012     return true;
3013
3014   return false;
3015 }
3016
3017 /// isCalleePop - Determines whether the callee is required to pop its
3018 /// own arguments. Callee pop is necessary to support tail calls.
3019 bool X86::isCalleePop(CallingConv::ID CallingConv,
3020                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3021   if (IsVarArg)
3022     return false;
3023
3024   switch (CallingConv) {
3025   default:
3026     return false;
3027   case CallingConv::X86_StdCall:
3028     return !is64Bit;
3029   case CallingConv::X86_FastCall:
3030     return !is64Bit;
3031   case CallingConv::X86_ThisCall:
3032     return !is64Bit;
3033   case CallingConv::Fast:
3034     return TailCallOpt;
3035   case CallingConv::GHC:
3036     return TailCallOpt;
3037   }
3038 }
3039
3040 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3041 /// specific condition code, returning the condition code and the LHS/RHS of the
3042 /// comparison to make.
3043 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3044                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3045   if (!isFP) {
3046     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3047       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3048         // X > -1   -> X == 0, jump !sign.
3049         RHS = DAG.getConstant(0, RHS.getValueType());
3050         return X86::COND_NS;
3051       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3052         // X < 0   -> X == 0, jump on sign.
3053         return X86::COND_S;
3054       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3055         // X < 1   -> X <= 0
3056         RHS = DAG.getConstant(0, RHS.getValueType());
3057         return X86::COND_LE;
3058       }
3059     }
3060
3061     switch (SetCCOpcode) {
3062     default: llvm_unreachable("Invalid integer condition!");
3063     case ISD::SETEQ:  return X86::COND_E;
3064     case ISD::SETGT:  return X86::COND_G;
3065     case ISD::SETGE:  return X86::COND_GE;
3066     case ISD::SETLT:  return X86::COND_L;
3067     case ISD::SETLE:  return X86::COND_LE;
3068     case ISD::SETNE:  return X86::COND_NE;
3069     case ISD::SETULT: return X86::COND_B;
3070     case ISD::SETUGT: return X86::COND_A;
3071     case ISD::SETULE: return X86::COND_BE;
3072     case ISD::SETUGE: return X86::COND_AE;
3073     }
3074   }
3075
3076   // First determine if it is required or is profitable to flip the operands.
3077
3078   // If LHS is a foldable load, but RHS is not, flip the condition.
3079   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3080       !ISD::isNON_EXTLoad(RHS.getNode())) {
3081     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3082     std::swap(LHS, RHS);
3083   }
3084
3085   switch (SetCCOpcode) {
3086   default: break;
3087   case ISD::SETOLT:
3088   case ISD::SETOLE:
3089   case ISD::SETUGT:
3090   case ISD::SETUGE:
3091     std::swap(LHS, RHS);
3092     break;
3093   }
3094
3095   // On a floating point condition, the flags are set as follows:
3096   // ZF  PF  CF   op
3097   //  0 | 0 | 0 | X > Y
3098   //  0 | 0 | 1 | X < Y
3099   //  1 | 0 | 0 | X == Y
3100   //  1 | 1 | 1 | unordered
3101   switch (SetCCOpcode) {
3102   default: llvm_unreachable("Condcode should be pre-legalized away");
3103   case ISD::SETUEQ:
3104   case ISD::SETEQ:   return X86::COND_E;
3105   case ISD::SETOLT:              // flipped
3106   case ISD::SETOGT:
3107   case ISD::SETGT:   return X86::COND_A;
3108   case ISD::SETOLE:              // flipped
3109   case ISD::SETOGE:
3110   case ISD::SETGE:   return X86::COND_AE;
3111   case ISD::SETUGT:              // flipped
3112   case ISD::SETULT:
3113   case ISD::SETLT:   return X86::COND_B;
3114   case ISD::SETUGE:              // flipped
3115   case ISD::SETULE:
3116   case ISD::SETLE:   return X86::COND_BE;
3117   case ISD::SETONE:
3118   case ISD::SETNE:   return X86::COND_NE;
3119   case ISD::SETUO:   return X86::COND_P;
3120   case ISD::SETO:    return X86::COND_NP;
3121   case ISD::SETOEQ:
3122   case ISD::SETUNE:  return X86::COND_INVALID;
3123   }
3124 }
3125
3126 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3127 /// code. Current x86 isa includes the following FP cmov instructions:
3128 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3129 static bool hasFPCMov(unsigned X86CC) {
3130   switch (X86CC) {
3131   default:
3132     return false;
3133   case X86::COND_B:
3134   case X86::COND_BE:
3135   case X86::COND_E:
3136   case X86::COND_P:
3137   case X86::COND_A:
3138   case X86::COND_AE:
3139   case X86::COND_NE:
3140   case X86::COND_NP:
3141     return true;
3142   }
3143 }
3144
3145 /// isFPImmLegal - Returns true if the target can instruction select the
3146 /// specified FP immediate natively. If false, the legalizer will
3147 /// materialize the FP immediate as a load from a constant pool.
3148 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3149   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3150     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3151       return true;
3152   }
3153   return false;
3154 }
3155
3156 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3157 /// the specified range (L, H].
3158 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3159   return (Val < 0) || (Val >= Low && Val < Hi);
3160 }
3161
3162 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3163 /// specified value.
3164 static bool isUndefOrEqual(int Val, int CmpVal) {
3165   if (Val < 0 || Val == CmpVal)
3166     return true;
3167   return false;
3168 }
3169
3170 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3171 /// from position Pos and ending in Pos+Size, falls within the specified
3172 /// sequential range (L, L+Pos]. or is undef.
3173 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3174                                        int Pos, int Size, int Low) {
3175   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3176     if (!isUndefOrEqual(Mask[i], Low))
3177       return false;
3178   return true;
3179 }
3180
3181 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3182 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3183 /// the second operand.
3184 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3185   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3186     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3187   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3188     return (Mask[0] < 2 && Mask[1] < 2);
3189   return false;
3190 }
3191
3192 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3193 /// is suitable for input to PSHUFHW.
3194 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT) {
3195   if (VT != MVT::v8i16)
3196     return false;
3197
3198   // Lower quadword copied in order or undef.
3199   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3200     return false;
3201
3202   // Upper quadword shuffled.
3203   for (unsigned i = 4; i != 8; ++i)
3204     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3205       return false;
3206
3207   return true;
3208 }
3209
3210 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3211 /// is suitable for input to PSHUFLW.
3212 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT) {
3213   if (VT != MVT::v8i16)
3214     return false;
3215
3216   // Upper quadword copied in order.
3217   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3218     return false;
3219
3220   // Lower quadword shuffled.
3221   for (unsigned i = 0; i != 4; ++i)
3222     if (Mask[i] >= 4)
3223       return false;
3224
3225   return true;
3226 }
3227
3228 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3229 /// is suitable for input to PALIGNR.
3230 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3231                           const X86Subtarget *Subtarget) {
3232   if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3233       (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3234     return false;
3235
3236   unsigned NumElts = VT.getVectorNumElements();
3237   unsigned NumLanes = VT.getSizeInBits()/128;
3238   unsigned NumLaneElts = NumElts/NumLanes;
3239
3240   // Do not handle 64-bit element shuffles with palignr.
3241   if (NumLaneElts == 2)
3242     return false;
3243
3244   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3245     unsigned i;
3246     for (i = 0; i != NumLaneElts; ++i) {
3247       if (Mask[i+l] >= 0)
3248         break;
3249     }
3250
3251     // Lane is all undef, go to next lane
3252     if (i == NumLaneElts)
3253       continue;
3254
3255     int Start = Mask[i+l];
3256
3257     // Make sure its in this lane in one of the sources
3258     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3259         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3260       return false;
3261
3262     // If not lane 0, then we must match lane 0
3263     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3264       return false;
3265
3266     // Correct second source to be contiguous with first source
3267     if (Start >= (int)NumElts)
3268       Start -= NumElts - NumLaneElts;
3269
3270     // Make sure we're shifting in the right direction.
3271     if (Start <= (int)(i+l))
3272       return false;
3273
3274     Start -= i;
3275
3276     // Check the rest of the elements to see if they are consecutive.
3277     for (++i; i != NumLaneElts; ++i) {
3278       int Idx = Mask[i+l];
3279
3280       // Make sure its in this lane
3281       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3282           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3283         return false;
3284
3285       // If not lane 0, then we must match lane 0
3286       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3287         return false;
3288
3289       if (Idx >= (int)NumElts)
3290         Idx -= NumElts - NumLaneElts;
3291
3292       if (!isUndefOrEqual(Idx, Start+i))
3293         return false;
3294
3295     }
3296   }
3297
3298   return true;
3299 }
3300
3301 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3302 /// the two vector operands have swapped position.
3303 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3304                                      unsigned NumElems) {
3305   for (unsigned i = 0; i != NumElems; ++i) {
3306     int idx = Mask[i];
3307     if (idx < 0)
3308       continue;
3309     else if (idx < (int)NumElems)
3310       Mask[i] = idx + NumElems;
3311     else
3312       Mask[i] = idx - NumElems;
3313   }
3314 }
3315
3316 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3317 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3318 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3319 /// reverse of what x86 shuffles want.
3320 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3321                         bool Commuted = false) {
3322   if (!HasAVX && VT.getSizeInBits() == 256)
3323     return false;
3324
3325   unsigned NumElems = VT.getVectorNumElements();
3326   unsigned NumLanes = VT.getSizeInBits()/128;
3327   unsigned NumLaneElems = NumElems/NumLanes;
3328
3329   if (NumLaneElems != 2 && NumLaneElems != 4)
3330     return false;
3331
3332   // VSHUFPSY divides the resulting vector into 4 chunks.
3333   // The sources are also splitted into 4 chunks, and each destination
3334   // chunk must come from a different source chunk.
3335   //
3336   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3337   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3338   //
3339   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3340   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3341   //
3342   // VSHUFPDY divides the resulting vector into 4 chunks.
3343   // The sources are also splitted into 4 chunks, and each destination
3344   // chunk must come from a different source chunk.
3345   //
3346   //  SRC1 =>      X3       X2       X1       X0
3347   //  SRC2 =>      Y3       Y2       Y1       Y0
3348   //
3349   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3350   //
3351   unsigned HalfLaneElems = NumLaneElems/2;
3352   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3353     for (unsigned i = 0; i != NumLaneElems; ++i) {
3354       int Idx = Mask[i+l];
3355       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3356       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3357         return false;
3358       // For VSHUFPSY, the mask of the second half must be the same as the
3359       // first but with the appropriate offsets. This works in the same way as
3360       // VPERMILPS works with masks.
3361       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3362         continue;
3363       if (!isUndefOrEqual(Idx, Mask[i]+l))
3364         return false;
3365     }
3366   }
3367
3368   return true;
3369 }
3370
3371 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3372 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3373 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3374   unsigned NumElems = VT.getVectorNumElements();
3375
3376   if (VT.getSizeInBits() != 128)
3377     return false;
3378
3379   if (NumElems != 4)
3380     return false;
3381
3382   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3383   return isUndefOrEqual(Mask[0], 6) &&
3384          isUndefOrEqual(Mask[1], 7) &&
3385          isUndefOrEqual(Mask[2], 2) &&
3386          isUndefOrEqual(Mask[3], 3);
3387 }
3388
3389 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3390 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3391 /// <2, 3, 2, 3>
3392 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3393   unsigned NumElems = VT.getVectorNumElements();
3394
3395   if (VT.getSizeInBits() != 128)
3396     return false;
3397
3398   if (NumElems != 4)
3399     return false;
3400
3401   return isUndefOrEqual(Mask[0], 2) &&
3402          isUndefOrEqual(Mask[1], 3) &&
3403          isUndefOrEqual(Mask[2], 2) &&
3404          isUndefOrEqual(Mask[3], 3);
3405 }
3406
3407 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3408 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3409 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3410   if (VT.getSizeInBits() != 128)
3411     return false;
3412
3413   unsigned NumElems = VT.getVectorNumElements();
3414
3415   if (NumElems != 2 && NumElems != 4)
3416     return false;
3417
3418   for (unsigned i = 0; i != NumElems/2; ++i)
3419     if (!isUndefOrEqual(Mask[i], i + NumElems))
3420       return false;
3421
3422   for (unsigned i = NumElems/2; i != NumElems; ++i)
3423     if (!isUndefOrEqual(Mask[i], i))
3424       return false;
3425
3426   return true;
3427 }
3428
3429 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3430 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3431 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3432   unsigned NumElems = VT.getVectorNumElements();
3433
3434   if ((NumElems != 2 && NumElems != 4)
3435       || VT.getSizeInBits() > 128)
3436     return false;
3437
3438   for (unsigned i = 0; i != NumElems/2; ++i)
3439     if (!isUndefOrEqual(Mask[i], i))
3440       return false;
3441
3442   for (unsigned i = 0; i != NumElems/2; ++i)
3443     if (!isUndefOrEqual(Mask[i + NumElems/2], i + NumElems))
3444       return false;
3445
3446   return true;
3447 }
3448
3449 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3450 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3451 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3452                          bool HasAVX2, bool V2IsSplat = false) {
3453   unsigned NumElts = VT.getVectorNumElements();
3454
3455   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3456          "Unsupported vector type for unpckh");
3457
3458   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3459       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3460     return false;
3461
3462   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3463   // independently on 128-bit lanes.
3464   unsigned NumLanes = VT.getSizeInBits()/128;
3465   unsigned NumLaneElts = NumElts/NumLanes;
3466
3467   for (unsigned l = 0; l != NumLanes; ++l) {
3468     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3469          i != (l+1)*NumLaneElts;
3470          i += 2, ++j) {
3471       int BitI  = Mask[i];
3472       int BitI1 = Mask[i+1];
3473       if (!isUndefOrEqual(BitI, j))
3474         return false;
3475       if (V2IsSplat) {
3476         if (!isUndefOrEqual(BitI1, NumElts))
3477           return false;
3478       } else {
3479         if (!isUndefOrEqual(BitI1, j + NumElts))
3480           return false;
3481       }
3482     }
3483   }
3484
3485   return true;
3486 }
3487
3488 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3490 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3491                          bool HasAVX2, bool V2IsSplat = false) {
3492   unsigned NumElts = VT.getVectorNumElements();
3493
3494   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3495          "Unsupported vector type for unpckh");
3496
3497   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3498       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3499     return false;
3500
3501   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3502   // independently on 128-bit lanes.
3503   unsigned NumLanes = VT.getSizeInBits()/128;
3504   unsigned NumLaneElts = NumElts/NumLanes;
3505
3506   for (unsigned l = 0; l != NumLanes; ++l) {
3507     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3508          i != (l+1)*NumLaneElts; i += 2, ++j) {
3509       int BitI  = Mask[i];
3510       int BitI1 = Mask[i+1];
3511       if (!isUndefOrEqual(BitI, j))
3512         return false;
3513       if (V2IsSplat) {
3514         if (isUndefOrEqual(BitI1, NumElts))
3515           return false;
3516       } else {
3517         if (!isUndefOrEqual(BitI1, j+NumElts))
3518           return false;
3519       }
3520     }
3521   }
3522   return true;
3523 }
3524
3525 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3526 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3527 /// <0, 0, 1, 1>
3528 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3529                                   bool HasAVX2) {
3530   unsigned NumElts = VT.getVectorNumElements();
3531
3532   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3533          "Unsupported vector type for unpckh");
3534
3535   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3536       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3537     return false;
3538
3539   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3540   // FIXME: Need a better way to get rid of this, there's no latency difference
3541   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3542   // the former later. We should also remove the "_undef" special mask.
3543   if (NumElts == 4 && VT.getSizeInBits() == 256)
3544     return false;
3545
3546   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3547   // independently on 128-bit lanes.
3548   unsigned NumLanes = VT.getSizeInBits()/128;
3549   unsigned NumLaneElts = NumElts/NumLanes;
3550
3551   for (unsigned l = 0; l != NumLanes; ++l) {
3552     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3553          i != (l+1)*NumLaneElts;
3554          i += 2, ++j) {
3555       int BitI  = Mask[i];
3556       int BitI1 = Mask[i+1];
3557
3558       if (!isUndefOrEqual(BitI, j))
3559         return false;
3560       if (!isUndefOrEqual(BitI1, j))
3561         return false;
3562     }
3563   }
3564
3565   return true;
3566 }
3567
3568 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3569 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3570 /// <2, 2, 3, 3>
3571 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3572   unsigned NumElts = VT.getVectorNumElements();
3573
3574   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3575          "Unsupported vector type for unpckh");
3576
3577   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3578       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3579     return false;
3580
3581   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3582   // independently on 128-bit lanes.
3583   unsigned NumLanes = VT.getSizeInBits()/128;
3584   unsigned NumLaneElts = NumElts/NumLanes;
3585
3586   for (unsigned l = 0; l != NumLanes; ++l) {
3587     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3588          i != (l+1)*NumLaneElts; i += 2, ++j) {
3589       int BitI  = Mask[i];
3590       int BitI1 = Mask[i+1];
3591       if (!isUndefOrEqual(BitI, j))
3592         return false;
3593       if (!isUndefOrEqual(BitI1, j))
3594         return false;
3595     }
3596   }
3597   return true;
3598 }
3599
3600 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3601 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3602 /// MOVSD, and MOVD, i.e. setting the lowest element.
3603 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3604   if (VT.getVectorElementType().getSizeInBits() < 32)
3605     return false;
3606   if (VT.getSizeInBits() == 256)
3607     return false;
3608
3609   unsigned NumElts = VT.getVectorNumElements();
3610
3611   if (!isUndefOrEqual(Mask[0], NumElts))
3612     return false;
3613
3614   for (unsigned i = 1; i != NumElts; ++i)
3615     if (!isUndefOrEqual(Mask[i], i))
3616       return false;
3617
3618   return true;
3619 }
3620
3621 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3622 /// as permutations between 128-bit chunks or halves. As an example: this
3623 /// shuffle bellow:
3624 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3625 /// The first half comes from the second half of V1 and the second half from the
3626 /// the second half of V2.
3627 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3628   if (!HasAVX || VT.getSizeInBits() != 256)
3629     return false;
3630
3631   // The shuffle result is divided into half A and half B. In total the two
3632   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3633   // B must come from C, D, E or F.
3634   unsigned HalfSize = VT.getVectorNumElements()/2;
3635   bool MatchA = false, MatchB = false;
3636
3637   // Check if A comes from one of C, D, E, F.
3638   for (unsigned Half = 0; Half != 4; ++Half) {
3639     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3640       MatchA = true;
3641       break;
3642     }
3643   }
3644
3645   // Check if B comes from one of C, D, E, F.
3646   for (unsigned Half = 0; Half != 4; ++Half) {
3647     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3648       MatchB = true;
3649       break;
3650     }
3651   }
3652
3653   return MatchA && MatchB;
3654 }
3655
3656 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3657 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3658 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3659   EVT VT = SVOp->getValueType(0);
3660
3661   unsigned HalfSize = VT.getVectorNumElements()/2;
3662
3663   unsigned FstHalf = 0, SndHalf = 0;
3664   for (unsigned i = 0; i < HalfSize; ++i) {
3665     if (SVOp->getMaskElt(i) > 0) {
3666       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3667       break;
3668     }
3669   }
3670   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3671     if (SVOp->getMaskElt(i) > 0) {
3672       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3673       break;
3674     }
3675   }
3676
3677   return (FstHalf | (SndHalf << 4));
3678 }
3679
3680 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3681 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3682 /// Note that VPERMIL mask matching is different depending whether theunderlying
3683 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3684 /// to the same elements of the low, but to the higher half of the source.
3685 /// In VPERMILPD the two lanes could be shuffled independently of each other
3686 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3687 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3688   if (!HasAVX)
3689     return false;
3690
3691   unsigned NumElts = VT.getVectorNumElements();
3692   // Only match 256-bit with 32/64-bit types
3693   if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3694     return false;
3695
3696   unsigned NumLanes = VT.getSizeInBits()/128;
3697   unsigned LaneSize = NumElts/NumLanes;
3698   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3699     for (unsigned i = 0; i != LaneSize; ++i) {
3700       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3701         return false;
3702       if (NumElts != 8 || l == 0)
3703         continue;
3704       // VPERMILPS handling
3705       if (Mask[i] < 0)
3706         continue;
3707       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3708         return false;
3709     }
3710   }
3711
3712   return true;
3713 }
3714
3715 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3716 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3717 /// element of vector 2 and the other elements to come from vector 1 in order.
3718 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3719                                bool V2IsSplat = false, bool V2IsUndef = false) {
3720   unsigned NumOps = VT.getVectorNumElements();
3721   if (VT.getSizeInBits() == 256)
3722     return false;
3723   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3724     return false;
3725
3726   if (!isUndefOrEqual(Mask[0], 0))
3727     return false;
3728
3729   for (unsigned i = 1; i != NumOps; ++i)
3730     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3731           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3732           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3733       return false;
3734
3735   return true;
3736 }
3737
3738 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3739 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3740 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3741 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3742                            const X86Subtarget *Subtarget) {
3743   if (!Subtarget->hasSSE3())
3744     return false;
3745
3746   unsigned NumElems = VT.getVectorNumElements();
3747
3748   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3749       (VT.getSizeInBits() == 256 && NumElems != 8))
3750     return false;
3751
3752   // "i+1" is the value the indexed mask element must have
3753   for (unsigned i = 0; i != NumElems; i += 2)
3754     if (!isUndefOrEqual(Mask[i], i+1) ||
3755         !isUndefOrEqual(Mask[i+1], i+1))
3756       return false;
3757
3758   return true;
3759 }
3760
3761 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3762 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3763 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3764 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3765                            const X86Subtarget *Subtarget) {
3766   if (!Subtarget->hasSSE3())
3767     return false;
3768
3769   unsigned NumElems = VT.getVectorNumElements();
3770
3771   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3772       (VT.getSizeInBits() == 256 && NumElems != 8))
3773     return false;
3774
3775   // "i" is the value the indexed mask element must have
3776   for (unsigned i = 0; i != NumElems; i += 2)
3777     if (!isUndefOrEqual(Mask[i], i) ||
3778         !isUndefOrEqual(Mask[i+1], i))
3779       return false;
3780
3781   return true;
3782 }
3783
3784 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3785 /// specifies a shuffle of elements that is suitable for input to 256-bit
3786 /// version of MOVDDUP.
3787 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3788   unsigned NumElts = VT.getVectorNumElements();
3789
3790   if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3791     return false;
3792
3793   for (unsigned i = 0; i != NumElts/2; ++i)
3794     if (!isUndefOrEqual(Mask[i], 0))
3795       return false;
3796   for (unsigned i = NumElts/2; i != NumElts; ++i)
3797     if (!isUndefOrEqual(Mask[i], NumElts/2))
3798       return false;
3799   return true;
3800 }
3801
3802 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3803 /// specifies a shuffle of elements that is suitable for input to 128-bit
3804 /// version of MOVDDUP.
3805 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3806   if (VT.getSizeInBits() != 128)
3807     return false;
3808
3809   unsigned e = VT.getVectorNumElements() / 2;
3810   for (unsigned i = 0; i != e; ++i)
3811     if (!isUndefOrEqual(Mask[i], i))
3812       return false;
3813   for (unsigned i = 0; i != e; ++i)
3814     if (!isUndefOrEqual(Mask[e+i], i))
3815       return false;
3816   return true;
3817 }
3818
3819 /// isVEXTRACTF128Index - Return true if the specified
3820 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3821 /// suitable for input to VEXTRACTF128.
3822 bool X86::isVEXTRACTF128Index(SDNode *N) {
3823   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3824     return false;
3825
3826   // The index should be aligned on a 128-bit boundary.
3827   uint64_t Index =
3828     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3829
3830   unsigned VL = N->getValueType(0).getVectorNumElements();
3831   unsigned VBits = N->getValueType(0).getSizeInBits();
3832   unsigned ElSize = VBits / VL;
3833   bool Result = (Index * ElSize) % 128 == 0;
3834
3835   return Result;
3836 }
3837
3838 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3839 /// operand specifies a subvector insert that is suitable for input to
3840 /// VINSERTF128.
3841 bool X86::isVINSERTF128Index(SDNode *N) {
3842   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3843     return false;
3844
3845   // The index should be aligned on a 128-bit boundary.
3846   uint64_t Index =
3847     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3848
3849   unsigned VL = N->getValueType(0).getVectorNumElements();
3850   unsigned VBits = N->getValueType(0).getSizeInBits();
3851   unsigned ElSize = VBits / VL;
3852   bool Result = (Index * ElSize) % 128 == 0;
3853
3854   return Result;
3855 }
3856
3857 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3858 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3859 /// Handles 128-bit and 256-bit.
3860 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3861   EVT VT = N->getValueType(0);
3862
3863   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3864          "Unsupported vector type for PSHUF/SHUFP");
3865
3866   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3867   // independently on 128-bit lanes.
3868   unsigned NumElts = VT.getVectorNumElements();
3869   unsigned NumLanes = VT.getSizeInBits()/128;
3870   unsigned NumLaneElts = NumElts/NumLanes;
3871
3872   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3873          "Only supports 2 or 4 elements per lane");
3874
3875   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3876   unsigned Mask = 0;
3877   for (unsigned i = 0; i != NumElts; ++i) {
3878     int Elt = N->getMaskElt(i);
3879     if (Elt < 0) continue;
3880     Elt %= NumLaneElts;
3881     unsigned ShAmt = i << Shift;
3882     if (ShAmt >= 8) ShAmt -= 8;
3883     Mask |= Elt << ShAmt;
3884   }
3885
3886   return Mask;
3887 }
3888
3889 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3890 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3891 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3892   unsigned Mask = 0;
3893   // 8 nodes, but we only care about the last 4.
3894   for (unsigned i = 7; i >= 4; --i) {
3895     int Val = N->getMaskElt(i);
3896     if (Val >= 0)
3897       Mask |= (Val - 4);
3898     if (i != 4)
3899       Mask <<= 2;
3900   }
3901   return Mask;
3902 }
3903
3904 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3905 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3906 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3907   unsigned Mask = 0;
3908   // 8 nodes, but we only care about the first 4.
3909   for (int i = 3; i >= 0; --i) {
3910     int Val = N->getMaskElt(i);
3911     if (Val >= 0)
3912       Mask |= Val;
3913     if (i != 0)
3914       Mask <<= 2;
3915   }
3916   return Mask;
3917 }
3918
3919 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3920 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3921 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3922   EVT VT = SVOp->getValueType(0);
3923   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3924
3925   unsigned NumElts = VT.getVectorNumElements();
3926   unsigned NumLanes = VT.getSizeInBits()/128;
3927   unsigned NumLaneElts = NumElts/NumLanes;
3928
3929   int Val = 0;
3930   unsigned i;
3931   for (i = 0; i != NumElts; ++i) {
3932     Val = SVOp->getMaskElt(i);
3933     if (Val >= 0)
3934       break;
3935   }
3936   if (Val >= (int)NumElts)
3937     Val -= NumElts - NumLaneElts;
3938
3939   assert(Val - i > 0 && "PALIGNR imm should be positive");
3940   return (Val - i) * EltSize;
3941 }
3942
3943 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3944 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3945 /// instructions.
3946 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
3947   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3948     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
3949
3950   uint64_t Index =
3951     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3952
3953   EVT VecVT = N->getOperand(0).getValueType();
3954   EVT ElVT = VecVT.getVectorElementType();
3955
3956   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3957   return Index / NumElemsPerChunk;
3958 }
3959
3960 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
3961 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
3962 /// instructions.
3963 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
3964   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3965     llvm_unreachable("Illegal insert subvector for VINSERTF128");
3966
3967   uint64_t Index =
3968     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3969
3970   EVT VecVT = N->getValueType(0);
3971   EVT ElVT = VecVT.getVectorElementType();
3972
3973   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
3974   return Index / NumElemsPerChunk;
3975 }
3976
3977 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
3978 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
3979 /// Handles 256-bit.
3980 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
3981   EVT VT = N->getValueType(0);
3982
3983   unsigned NumElts = VT.getVectorNumElements();
3984
3985   assert((VT.is256BitVector() && NumElts == 4) &&
3986          "Unsupported vector type for VPERMQ/VPERMPD");
3987
3988   unsigned Mask = 0;
3989   for (unsigned i = 0; i != NumElts; ++i) {
3990     int Elt = N->getMaskElt(i);
3991     if (Elt < 0)
3992       continue;
3993     Mask |= Elt << (i*2);
3994   }
3995
3996   return Mask;
3997 }
3998 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3999 /// constant +0.0.
4000 bool X86::isZeroNode(SDValue Elt) {
4001   return ((isa<ConstantSDNode>(Elt) &&
4002            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4003           (isa<ConstantFPSDNode>(Elt) &&
4004            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4005 }
4006
4007 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4008 /// their permute mask.
4009 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4010                                     SelectionDAG &DAG) {
4011   EVT VT = SVOp->getValueType(0);
4012   unsigned NumElems = VT.getVectorNumElements();
4013   SmallVector<int, 8> MaskVec;
4014
4015   for (unsigned i = 0; i != NumElems; ++i) {
4016     int idx = SVOp->getMaskElt(i);
4017     if (idx < 0)
4018       MaskVec.push_back(idx);
4019     else if (idx < (int)NumElems)
4020       MaskVec.push_back(idx + NumElems);
4021     else
4022       MaskVec.push_back(idx - NumElems);
4023   }
4024   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4025                               SVOp->getOperand(0), &MaskVec[0]);
4026 }
4027
4028 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4029 /// match movhlps. The lower half elements should come from upper half of
4030 /// V1 (and in order), and the upper half elements should come from the upper
4031 /// half of V2 (and in order).
4032 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4033   if (VT.getSizeInBits() != 128)
4034     return false;
4035   if (VT.getVectorNumElements() != 4)
4036     return false;
4037   for (unsigned i = 0, e = 2; i != e; ++i)
4038     if (!isUndefOrEqual(Mask[i], i+2))
4039       return false;
4040   for (unsigned i = 2; i != 4; ++i)
4041     if (!isUndefOrEqual(Mask[i], i+4))
4042       return false;
4043   return true;
4044 }
4045
4046 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4047 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4048 /// required.
4049 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4050   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4051     return false;
4052   N = N->getOperand(0).getNode();
4053   if (!ISD::isNON_EXTLoad(N))
4054     return false;
4055   if (LD)
4056     *LD = cast<LoadSDNode>(N);
4057   return true;
4058 }
4059
4060 // Test whether the given value is a vector value which will be legalized
4061 // into a load.
4062 static bool WillBeConstantPoolLoad(SDNode *N) {
4063   if (N->getOpcode() != ISD::BUILD_VECTOR)
4064     return false;
4065
4066   // Check for any non-constant elements.
4067   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4068     switch (N->getOperand(i).getNode()->getOpcode()) {
4069     case ISD::UNDEF:
4070     case ISD::ConstantFP:
4071     case ISD::Constant:
4072       break;
4073     default:
4074       return false;
4075     }
4076
4077   // Vectors of all-zeros and all-ones are materialized with special
4078   // instructions rather than being loaded.
4079   return !ISD::isBuildVectorAllZeros(N) &&
4080          !ISD::isBuildVectorAllOnes(N);
4081 }
4082
4083 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4084 /// match movlp{s|d}. The lower half elements should come from lower half of
4085 /// V1 (and in order), and the upper half elements should come from the upper
4086 /// half of V2 (and in order). And since V1 will become the source of the
4087 /// MOVLP, it must be either a vector load or a scalar load to vector.
4088 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4089                                ArrayRef<int> Mask, EVT VT) {
4090   if (VT.getSizeInBits() != 128)
4091     return false;
4092
4093   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4094     return false;
4095   // Is V2 is a vector load, don't do this transformation. We will try to use
4096   // load folding shufps op.
4097   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4098     return false;
4099
4100   unsigned NumElems = VT.getVectorNumElements();
4101
4102   if (NumElems != 2 && NumElems != 4)
4103     return false;
4104   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4105     if (!isUndefOrEqual(Mask[i], i))
4106       return false;
4107   for (unsigned i = NumElems/2; i != NumElems; ++i)
4108     if (!isUndefOrEqual(Mask[i], i+NumElems))
4109       return false;
4110   return true;
4111 }
4112
4113 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4114 /// all the same.
4115 static bool isSplatVector(SDNode *N) {
4116   if (N->getOpcode() != ISD::BUILD_VECTOR)
4117     return false;
4118
4119   SDValue SplatValue = N->getOperand(0);
4120   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4121     if (N->getOperand(i) != SplatValue)
4122       return false;
4123   return true;
4124 }
4125
4126 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4127 /// to an zero vector.
4128 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4129 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4130   SDValue V1 = N->getOperand(0);
4131   SDValue V2 = N->getOperand(1);
4132   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4133   for (unsigned i = 0; i != NumElems; ++i) {
4134     int Idx = N->getMaskElt(i);
4135     if (Idx >= (int)NumElems) {
4136       unsigned Opc = V2.getOpcode();
4137       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4138         continue;
4139       if (Opc != ISD::BUILD_VECTOR ||
4140           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4141         return false;
4142     } else if (Idx >= 0) {
4143       unsigned Opc = V1.getOpcode();
4144       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4145         continue;
4146       if (Opc != ISD::BUILD_VECTOR ||
4147           !X86::isZeroNode(V1.getOperand(Idx)))
4148         return false;
4149     }
4150   }
4151   return true;
4152 }
4153
4154 /// getZeroVector - Returns a vector of specified type with all zero elements.
4155 ///
4156 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4157                              SelectionDAG &DAG, DebugLoc dl) {
4158   assert(VT.isVector() && "Expected a vector type");
4159
4160   // Always build SSE zero vectors as <4 x i32> bitcasted
4161   // to their dest type. This ensures they get CSE'd.
4162   SDValue Vec;
4163   if (VT.getSizeInBits() == 128) {  // SSE
4164     if (Subtarget->hasSSE2()) {  // SSE2
4165       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4166       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4167     } else { // SSE1
4168       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4170     }
4171   } else if (VT.getSizeInBits() == 256) { // AVX
4172     if (Subtarget->hasAVX2()) { // AVX2
4173       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4174       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4175       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4176     } else {
4177       // 256-bit logic and arithmetic instructions in AVX are all
4178       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4179       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4180       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4181       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4182     }
4183   }
4184   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4185 }
4186
4187 /// getOnesVector - Returns a vector of specified type with all bits set.
4188 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4189 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4190 /// Then bitcast to their original type, ensuring they get CSE'd.
4191 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4192                              DebugLoc dl) {
4193   assert(VT.isVector() && "Expected a vector type");
4194   assert((VT.is128BitVector() || VT.is256BitVector())
4195          && "Expected a 128-bit or 256-bit vector type");
4196
4197   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4198   SDValue Vec;
4199   if (VT.getSizeInBits() == 256) {
4200     if (HasAVX2) { // AVX2
4201       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4202       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4203     } else { // AVX
4204       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4205       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4206     }
4207   } else {
4208     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4209   }
4210
4211   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4212 }
4213
4214 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4215 /// that point to V2 points to its first element.
4216 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4217   for (unsigned i = 0; i != NumElems; ++i) {
4218     if (Mask[i] > (int)NumElems) {
4219       Mask[i] = NumElems;
4220     }
4221   }
4222 }
4223
4224 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4225 /// operation of specified width.
4226 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4227                        SDValue V2) {
4228   unsigned NumElems = VT.getVectorNumElements();
4229   SmallVector<int, 8> Mask;
4230   Mask.push_back(NumElems);
4231   for (unsigned i = 1; i != NumElems; ++i)
4232     Mask.push_back(i);
4233   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4234 }
4235
4236 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4237 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4238                           SDValue V2) {
4239   unsigned NumElems = VT.getVectorNumElements();
4240   SmallVector<int, 8> Mask;
4241   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4242     Mask.push_back(i);
4243     Mask.push_back(i + NumElems);
4244   }
4245   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4246 }
4247
4248 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4249 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4250                           SDValue V2) {
4251   unsigned NumElems = VT.getVectorNumElements();
4252   unsigned Half = NumElems/2;
4253   SmallVector<int, 8> Mask;
4254   for (unsigned i = 0; i != Half; ++i) {
4255     Mask.push_back(i + Half);
4256     Mask.push_back(i + NumElems + Half);
4257   }
4258   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4259 }
4260
4261 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4262 // a generic shuffle instruction because the target has no such instructions.
4263 // Generate shuffles which repeat i16 and i8 several times until they can be
4264 // represented by v4f32 and then be manipulated by target suported shuffles.
4265 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4266   EVT VT = V.getValueType();
4267   int NumElems = VT.getVectorNumElements();
4268   DebugLoc dl = V.getDebugLoc();
4269
4270   while (NumElems > 4) {
4271     if (EltNo < NumElems/2) {
4272       V = getUnpackl(DAG, dl, VT, V, V);
4273     } else {
4274       V = getUnpackh(DAG, dl, VT, V, V);
4275       EltNo -= NumElems/2;
4276     }
4277     NumElems >>= 1;
4278   }
4279   return V;
4280 }
4281
4282 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4283 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4284   EVT VT = V.getValueType();
4285   DebugLoc dl = V.getDebugLoc();
4286   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4287          && "Vector size not supported");
4288
4289   if (VT.getSizeInBits() == 128) {
4290     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4291     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4292     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4293                              &SplatMask[0]);
4294   } else {
4295     // To use VPERMILPS to splat scalars, the second half of indicies must
4296     // refer to the higher part, which is a duplication of the lower one,
4297     // because VPERMILPS can only handle in-lane permutations.
4298     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4299                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4300
4301     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4302     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4303                              &SplatMask[0]);
4304   }
4305
4306   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4307 }
4308
4309 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4310 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4311   EVT SrcVT = SV->getValueType(0);
4312   SDValue V1 = SV->getOperand(0);
4313   DebugLoc dl = SV->getDebugLoc();
4314
4315   int EltNo = SV->getSplatIndex();
4316   int NumElems = SrcVT.getVectorNumElements();
4317   unsigned Size = SrcVT.getSizeInBits();
4318
4319   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4320           "Unknown how to promote splat for type");
4321
4322   // Extract the 128-bit part containing the splat element and update
4323   // the splat element index when it refers to the higher register.
4324   if (Size == 256) {
4325     unsigned Idx = (EltNo >= NumElems/2) ? NumElems/2 : 0;
4326     V1 = Extract128BitVector(V1, Idx, DAG, dl);
4327     if (Idx > 0)
4328       EltNo -= NumElems/2;
4329   }
4330
4331   // All i16 and i8 vector types can't be used directly by a generic shuffle
4332   // instruction because the target has no such instruction. Generate shuffles
4333   // which repeat i16 and i8 several times until they fit in i32, and then can
4334   // be manipulated by target suported shuffles.
4335   EVT EltVT = SrcVT.getVectorElementType();
4336   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4337     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4338
4339   // Recreate the 256-bit vector and place the same 128-bit vector
4340   // into the low and high part. This is necessary because we want
4341   // to use VPERM* to shuffle the vectors
4342   if (Size == 256) {
4343     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4344   }
4345
4346   return getLegalSplat(DAG, V1, EltNo);
4347 }
4348
4349 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4350 /// vector of zero or undef vector.  This produces a shuffle where the low
4351 /// element of V2 is swizzled into the zero/undef vector, landing at element
4352 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4353 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4354                                            bool IsZero,
4355                                            const X86Subtarget *Subtarget,
4356                                            SelectionDAG &DAG) {
4357   EVT VT = V2.getValueType();
4358   SDValue V1 = IsZero
4359     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 16> MaskVec;
4362   for (unsigned i = 0; i != NumElems; ++i)
4363     // If this is the insertion idx, put the low elt of V2 here.
4364     MaskVec.push_back(i == Idx ? NumElems : i);
4365   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4366 }
4367
4368 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4369 /// target specific opcode. Returns true if the Mask could be calculated.
4370 /// Sets IsUnary to true if only uses one source.
4371 static bool getTargetShuffleMask(SDNode *N, EVT VT,
4372                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4373   unsigned NumElems = VT.getVectorNumElements();
4374   SDValue ImmN;
4375
4376   IsUnary = false;
4377   switch(N->getOpcode()) {
4378   case X86ISD::SHUFP:
4379     ImmN = N->getOperand(N->getNumOperands()-1);
4380     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4381     break;
4382   case X86ISD::UNPCKH:
4383     DecodeUNPCKHMask(VT, Mask);
4384     break;
4385   case X86ISD::UNPCKL:
4386     DecodeUNPCKLMask(VT, Mask);
4387     break;
4388   case X86ISD::MOVHLPS:
4389     DecodeMOVHLPSMask(NumElems, Mask);
4390     break;
4391   case X86ISD::MOVLHPS:
4392     DecodeMOVLHPSMask(NumElems, Mask);
4393     break;
4394   case X86ISD::PSHUFD:
4395   case X86ISD::VPERMILP:
4396     ImmN = N->getOperand(N->getNumOperands()-1);
4397     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4398     IsUnary = true;
4399     break;
4400   case X86ISD::PSHUFHW:
4401     ImmN = N->getOperand(N->getNumOperands()-1);
4402     DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4403     IsUnary = true;
4404     break;
4405   case X86ISD::PSHUFLW:
4406     ImmN = N->getOperand(N->getNumOperands()-1);
4407     DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4408     IsUnary = true;
4409     break;
4410   case X86ISD::MOVSS:
4411   case X86ISD::MOVSD: {
4412     // The index 0 always comes from the first element of the second source,
4413     // this is why MOVSS and MOVSD are used in the first place. The other
4414     // elements come from the other positions of the first source vector
4415     Mask.push_back(NumElems);
4416     for (unsigned i = 1; i != NumElems; ++i) {
4417       Mask.push_back(i);
4418     }
4419     break;
4420   }
4421   case X86ISD::VPERM2X128:
4422     ImmN = N->getOperand(N->getNumOperands()-1);
4423     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4424     if (Mask.empty()) return false;
4425     break;
4426   case X86ISD::MOVDDUP:
4427   case X86ISD::MOVLHPD:
4428   case X86ISD::MOVLPD:
4429   case X86ISD::MOVLPS:
4430   case X86ISD::MOVSHDUP:
4431   case X86ISD::MOVSLDUP:
4432   case X86ISD::PALIGN:
4433     // Not yet implemented
4434     return false;
4435   default: llvm_unreachable("unknown target shuffle node");
4436   }
4437
4438   return true;
4439 }
4440
4441 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4442 /// element of the result of the vector shuffle.
4443 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4444                                    unsigned Depth) {
4445   if (Depth == 6)
4446     return SDValue();  // Limit search depth.
4447
4448   SDValue V = SDValue(N, 0);
4449   EVT VT = V.getValueType();
4450   unsigned Opcode = V.getOpcode();
4451
4452   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4453   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4454     int Elt = SV->getMaskElt(Index);
4455
4456     if (Elt < 0)
4457       return DAG.getUNDEF(VT.getVectorElementType());
4458
4459     unsigned NumElems = VT.getVectorNumElements();
4460     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4461                                          : SV->getOperand(1);
4462     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4463   }
4464
4465   // Recurse into target specific vector shuffles to find scalars.
4466   if (isTargetShuffle(Opcode)) {
4467     unsigned NumElems = VT.getVectorNumElements();
4468     SmallVector<int, 16> ShuffleMask;
4469     SDValue ImmN;
4470     bool IsUnary;
4471
4472     if (!getTargetShuffleMask(N, VT, ShuffleMask, IsUnary))
4473       return SDValue();
4474
4475     int Elt = ShuffleMask[Index];
4476     if (Elt < 0)
4477       return DAG.getUNDEF(VT.getVectorElementType());
4478
4479     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4480                                            : N->getOperand(1);
4481     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4482                                Depth+1);
4483   }
4484
4485   // Actual nodes that may contain scalar elements
4486   if (Opcode == ISD::BITCAST) {
4487     V = V.getOperand(0);
4488     EVT SrcVT = V.getValueType();
4489     unsigned NumElems = VT.getVectorNumElements();
4490
4491     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4492       return SDValue();
4493   }
4494
4495   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4496     return (Index == 0) ? V.getOperand(0)
4497                         : DAG.getUNDEF(VT.getVectorElementType());
4498
4499   if (V.getOpcode() == ISD::BUILD_VECTOR)
4500     return V.getOperand(Index);
4501
4502   return SDValue();
4503 }
4504
4505 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4506 /// shuffle operation which come from a consecutively from a zero. The
4507 /// search can start in two different directions, from left or right.
4508 static
4509 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4510                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4511   unsigned i;
4512   for (i = 0; i != NumElems; ++i) {
4513     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4514     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4515     if (!(Elt.getNode() &&
4516          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4517       break;
4518   }
4519
4520   return i;
4521 }
4522
4523 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4524 /// correspond consecutively to elements from one of the vector operands,
4525 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4526 static
4527 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4528                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4529                               unsigned NumElems, unsigned &OpNum) {
4530   bool SeenV1 = false;
4531   bool SeenV2 = false;
4532
4533   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4534     int Idx = SVOp->getMaskElt(i);
4535     // Ignore undef indicies
4536     if (Idx < 0)
4537       continue;
4538
4539     if (Idx < (int)NumElems)
4540       SeenV1 = true;
4541     else
4542       SeenV2 = true;
4543
4544     // Only accept consecutive elements from the same vector
4545     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4546       return false;
4547   }
4548
4549   OpNum = SeenV1 ? 0 : 1;
4550   return true;
4551 }
4552
4553 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4554 /// logical left shift of a vector.
4555 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4556                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4557   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4558   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4559               false /* check zeros from right */, DAG);
4560   unsigned OpSrc;
4561
4562   if (!NumZeros)
4563     return false;
4564
4565   // Considering the elements in the mask that are not consecutive zeros,
4566   // check if they consecutively come from only one of the source vectors.
4567   //
4568   //               V1 = {X, A, B, C}     0
4569   //                         \  \  \    /
4570   //   vector_shuffle V1, V2 <1, 2, 3, X>
4571   //
4572   if (!isShuffleMaskConsecutive(SVOp,
4573             0,                   // Mask Start Index
4574             NumElems-NumZeros,   // Mask End Index(exclusive)
4575             NumZeros,            // Where to start looking in the src vector
4576             NumElems,            // Number of elements in vector
4577             OpSrc))              // Which source operand ?
4578     return false;
4579
4580   isLeft = false;
4581   ShAmt = NumZeros;
4582   ShVal = SVOp->getOperand(OpSrc);
4583   return true;
4584 }
4585
4586 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4587 /// logical left shift of a vector.
4588 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4589                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4590   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4591   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4592               true /* check zeros from left */, DAG);
4593   unsigned OpSrc;
4594
4595   if (!NumZeros)
4596     return false;
4597
4598   // Considering the elements in the mask that are not consecutive zeros,
4599   // check if they consecutively come from only one of the source vectors.
4600   //
4601   //                           0    { A, B, X, X } = V2
4602   //                          / \    /  /
4603   //   vector_shuffle V1, V2 <X, X, 4, 5>
4604   //
4605   if (!isShuffleMaskConsecutive(SVOp,
4606             NumZeros,     // Mask Start Index
4607             NumElems,     // Mask End Index(exclusive)
4608             0,            // Where to start looking in the src vector
4609             NumElems,     // Number of elements in vector
4610             OpSrc))       // Which source operand ?
4611     return false;
4612
4613   isLeft = true;
4614   ShAmt = NumZeros;
4615   ShVal = SVOp->getOperand(OpSrc);
4616   return true;
4617 }
4618
4619 /// isVectorShift - Returns true if the shuffle can be implemented as a
4620 /// logical left or right shift of a vector.
4621 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4622                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4623   // Although the logic below support any bitwidth size, there are no
4624   // shift instructions which handle more than 128-bit vectors.
4625   if (SVOp->getValueType(0).getSizeInBits() > 128)
4626     return false;
4627
4628   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4629       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4630     return true;
4631
4632   return false;
4633 }
4634
4635 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4636 ///
4637 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4638                                        unsigned NumNonZero, unsigned NumZero,
4639                                        SelectionDAG &DAG,
4640                                        const X86Subtarget* Subtarget,
4641                                        const TargetLowering &TLI) {
4642   if (NumNonZero > 8)
4643     return SDValue();
4644
4645   DebugLoc dl = Op.getDebugLoc();
4646   SDValue V(0, 0);
4647   bool First = true;
4648   for (unsigned i = 0; i < 16; ++i) {
4649     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4650     if (ThisIsNonZero && First) {
4651       if (NumZero)
4652         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4653       else
4654         V = DAG.getUNDEF(MVT::v8i16);
4655       First = false;
4656     }
4657
4658     if ((i & 1) != 0) {
4659       SDValue ThisElt(0, 0), LastElt(0, 0);
4660       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4661       if (LastIsNonZero) {
4662         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4663                               MVT::i16, Op.getOperand(i-1));
4664       }
4665       if (ThisIsNonZero) {
4666         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4667         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4668                               ThisElt, DAG.getConstant(8, MVT::i8));
4669         if (LastIsNonZero)
4670           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4671       } else
4672         ThisElt = LastElt;
4673
4674       if (ThisElt.getNode())
4675         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4676                         DAG.getIntPtrConstant(i/2));
4677     }
4678   }
4679
4680   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4681 }
4682
4683 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4684 ///
4685 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4686                                      unsigned NumNonZero, unsigned NumZero,
4687                                      SelectionDAG &DAG,
4688                                      const X86Subtarget* Subtarget,
4689                                      const TargetLowering &TLI) {
4690   if (NumNonZero > 4)
4691     return SDValue();
4692
4693   DebugLoc dl = Op.getDebugLoc();
4694   SDValue V(0, 0);
4695   bool First = true;
4696   for (unsigned i = 0; i < 8; ++i) {
4697     bool isNonZero = (NonZeros & (1 << i)) != 0;
4698     if (isNonZero) {
4699       if (First) {
4700         if (NumZero)
4701           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4702         else
4703           V = DAG.getUNDEF(MVT::v8i16);
4704         First = false;
4705       }
4706       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4707                       MVT::v8i16, V, Op.getOperand(i),
4708                       DAG.getIntPtrConstant(i));
4709     }
4710   }
4711
4712   return V;
4713 }
4714
4715 /// getVShift - Return a vector logical shift node.
4716 ///
4717 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4718                          unsigned NumBits, SelectionDAG &DAG,
4719                          const TargetLowering &TLI, DebugLoc dl) {
4720   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4721   EVT ShVT = MVT::v2i64;
4722   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4723   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4724   return DAG.getNode(ISD::BITCAST, dl, VT,
4725                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4726                              DAG.getConstant(NumBits,
4727                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4728 }
4729
4730 SDValue
4731 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4732                                           SelectionDAG &DAG) const {
4733
4734   // Check if the scalar load can be widened into a vector load. And if
4735   // the address is "base + cst" see if the cst can be "absorbed" into
4736   // the shuffle mask.
4737   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4738     SDValue Ptr = LD->getBasePtr();
4739     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4740       return SDValue();
4741     EVT PVT = LD->getValueType(0);
4742     if (PVT != MVT::i32 && PVT != MVT::f32)
4743       return SDValue();
4744
4745     int FI = -1;
4746     int64_t Offset = 0;
4747     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4748       FI = FINode->getIndex();
4749       Offset = 0;
4750     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4751                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4752       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4753       Offset = Ptr.getConstantOperandVal(1);
4754       Ptr = Ptr.getOperand(0);
4755     } else {
4756       return SDValue();
4757     }
4758
4759     // FIXME: 256-bit vector instructions don't require a strict alignment,
4760     // improve this code to support it better.
4761     unsigned RequiredAlign = VT.getSizeInBits()/8;
4762     SDValue Chain = LD->getChain();
4763     // Make sure the stack object alignment is at least 16 or 32.
4764     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4765     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4766       if (MFI->isFixedObjectIndex(FI)) {
4767         // Can't change the alignment. FIXME: It's possible to compute
4768         // the exact stack offset and reference FI + adjust offset instead.
4769         // If someone *really* cares about this. That's the way to implement it.
4770         return SDValue();
4771       } else {
4772         MFI->setObjectAlignment(FI, RequiredAlign);
4773       }
4774     }
4775
4776     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4777     // Ptr + (Offset & ~15).
4778     if (Offset < 0)
4779       return SDValue();
4780     if ((Offset % RequiredAlign) & 3)
4781       return SDValue();
4782     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4783     if (StartOffset)
4784       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4785                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4786
4787     int EltNo = (Offset - StartOffset) >> 2;
4788     int NumElems = VT.getVectorNumElements();
4789
4790     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4791     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4792                              LD->getPointerInfo().getWithOffset(StartOffset),
4793                              false, false, false, 0);
4794
4795     SmallVector<int, 8> Mask;
4796     for (int i = 0; i < NumElems; ++i)
4797       Mask.push_back(EltNo);
4798
4799     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4800   }
4801
4802   return SDValue();
4803 }
4804
4805 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4806 /// vector of type 'VT', see if the elements can be replaced by a single large
4807 /// load which has the same value as a build_vector whose operands are 'elts'.
4808 ///
4809 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4810 ///
4811 /// FIXME: we'd also like to handle the case where the last elements are zero
4812 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4813 /// There's even a handy isZeroNode for that purpose.
4814 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4815                                         DebugLoc &DL, SelectionDAG &DAG) {
4816   EVT EltVT = VT.getVectorElementType();
4817   unsigned NumElems = Elts.size();
4818
4819   LoadSDNode *LDBase = NULL;
4820   unsigned LastLoadedElt = -1U;
4821
4822   // For each element in the initializer, see if we've found a load or an undef.
4823   // If we don't find an initial load element, or later load elements are
4824   // non-consecutive, bail out.
4825   for (unsigned i = 0; i < NumElems; ++i) {
4826     SDValue Elt = Elts[i];
4827
4828     if (!Elt.getNode() ||
4829         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4830       return SDValue();
4831     if (!LDBase) {
4832       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4833         return SDValue();
4834       LDBase = cast<LoadSDNode>(Elt.getNode());
4835       LastLoadedElt = i;
4836       continue;
4837     }
4838     if (Elt.getOpcode() == ISD::UNDEF)
4839       continue;
4840
4841     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4842     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4843       return SDValue();
4844     LastLoadedElt = i;
4845   }
4846
4847   // If we have found an entire vector of loads and undefs, then return a large
4848   // load of the entire vector width starting at the base pointer.  If we found
4849   // consecutive loads for the low half, generate a vzext_load node.
4850   if (LastLoadedElt == NumElems - 1) {
4851     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4852       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4853                          LDBase->getPointerInfo(),
4854                          LDBase->isVolatile(), LDBase->isNonTemporal(),
4855                          LDBase->isInvariant(), 0);
4856     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4857                        LDBase->getPointerInfo(),
4858                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4859                        LDBase->isInvariant(), LDBase->getAlignment());
4860   } else if (NumElems == 4 && LastLoadedElt == 1 &&
4861              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4862     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4863     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4864     SDValue ResNode =
4865         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4866                                 LDBase->getPointerInfo(),
4867                                 LDBase->getAlignment(),
4868                                 false/*isVolatile*/, true/*ReadMem*/,
4869                                 false/*WriteMem*/);
4870     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4871   }
4872   return SDValue();
4873 }
4874
4875 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4876 /// to generate a splat value for the following cases:
4877 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4878 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4879 /// a scalar load, or a constant.
4880 /// The VBROADCAST node is returned when a pattern is found,
4881 /// or SDValue() otherwise.
4882 SDValue
4883 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4884   if (!Subtarget->hasAVX())
4885     return SDValue();
4886
4887   EVT VT = Op.getValueType();
4888   DebugLoc dl = Op.getDebugLoc();
4889
4890   SDValue Ld;
4891   bool ConstSplatVal;
4892
4893   switch (Op.getOpcode()) {
4894     default:
4895       // Unknown pattern found.
4896       return SDValue();
4897
4898     case ISD::BUILD_VECTOR: {
4899       // The BUILD_VECTOR node must be a splat.
4900       if (!isSplatVector(Op.getNode()))
4901         return SDValue();
4902
4903       Ld = Op.getOperand(0);
4904       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4905                      Ld.getOpcode() == ISD::ConstantFP);
4906
4907       // The suspected load node has several users. Make sure that all
4908       // of its users are from the BUILD_VECTOR node.
4909       // Constants may have multiple users.
4910       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4911         return SDValue();
4912       break;
4913     }
4914
4915     case ISD::VECTOR_SHUFFLE: {
4916       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4917
4918       // Shuffles must have a splat mask where the first element is
4919       // broadcasted.
4920       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4921         return SDValue();
4922
4923       SDValue Sc = Op.getOperand(0);
4924       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
4925         return SDValue();
4926
4927       Ld = Sc.getOperand(0);
4928       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4929                        Ld.getOpcode() == ISD::ConstantFP);
4930
4931       // The scalar_to_vector node and the suspected
4932       // load node must have exactly one user.
4933       // Constants may have multiple users.
4934       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
4935         return SDValue();
4936       break;
4937     }
4938   }
4939
4940   bool Is256 = VT.getSizeInBits() == 256;
4941   bool Is128 = VT.getSizeInBits() == 128;
4942
4943   // Handle the broadcasting a single constant scalar from the constant pool
4944   // into a vector. On Sandybridge it is still better to load a constant vector
4945   // from the constant pool and not to broadcast it from a scalar.
4946   if (ConstSplatVal && Subtarget->hasAVX2()) {
4947     EVT CVT = Ld.getValueType();
4948     assert(!CVT.isVector() && "Must not broadcast a vector type");
4949     unsigned ScalarSize = CVT.getSizeInBits();
4950
4951     if ((Is256 && (ScalarSize == 32 || ScalarSize == 64)) ||
4952         (Is128 && (ScalarSize == 32))) {
4953
4954       const Constant *C = 0;
4955       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
4956         C = CI->getConstantIntValue();
4957       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
4958         C = CF->getConstantFPValue();
4959
4960       assert(C && "Invalid constant type");
4961
4962       SDValue CP = DAG.getConstantPool(C, getPointerTy());
4963       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
4964       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
4965                          MachinePointerInfo::getConstantPool(),
4966                          false, false, false, Alignment);
4967
4968       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4969     }
4970   }
4971
4972   // The scalar source must be a normal load.
4973   if (!ISD::isNormalLoad(Ld.getNode()))
4974     return SDValue();
4975
4976   // Reject loads that have uses of the chain result
4977   if (Ld->hasAnyUseOfValue(1))
4978     return SDValue();
4979
4980   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
4981
4982   // VBroadcast to YMM
4983   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
4984     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4985
4986   // VBroadcast to XMM
4987   if (Is128 && (ScalarSize == 32))
4988     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4989
4990   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
4991   // double since there is vbroadcastsd xmm
4992   if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
4993     // VBroadcast to YMM
4994     if (Is256 && (ScalarSize == 8 || ScalarSize == 16))
4995       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
4996
4997     // VBroadcast to XMM
4998     if (Is128 && (ScalarSize ==  8 || ScalarSize == 16 || ScalarSize == 64))
4999       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5000   }
5001
5002   // Unsupported broadcast.
5003   return SDValue();
5004 }
5005
5006 SDValue
5007 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5008   DebugLoc dl = Op.getDebugLoc();
5009
5010   EVT VT = Op.getValueType();
5011   EVT ExtVT = VT.getVectorElementType();
5012   unsigned NumElems = Op.getNumOperands();
5013
5014   // Vectors containing all zeros can be matched by pxor and xorps later
5015   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5016     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5017     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5018     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5019       return Op;
5020
5021     return getZeroVector(VT, Subtarget, DAG, dl);
5022   }
5023
5024   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5025   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5026   // vpcmpeqd on 256-bit vectors.
5027   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5028     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5029       return Op;
5030
5031     return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5032   }
5033
5034   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5035   if (Broadcast.getNode())
5036     return Broadcast;
5037
5038   unsigned EVTBits = ExtVT.getSizeInBits();
5039
5040   unsigned NumZero  = 0;
5041   unsigned NumNonZero = 0;
5042   unsigned NonZeros = 0;
5043   bool IsAllConstants = true;
5044   SmallSet<SDValue, 8> Values;
5045   for (unsigned i = 0; i < NumElems; ++i) {
5046     SDValue Elt = Op.getOperand(i);
5047     if (Elt.getOpcode() == ISD::UNDEF)
5048       continue;
5049     Values.insert(Elt);
5050     if (Elt.getOpcode() != ISD::Constant &&
5051         Elt.getOpcode() != ISD::ConstantFP)
5052       IsAllConstants = false;
5053     if (X86::isZeroNode(Elt))
5054       NumZero++;
5055     else {
5056       NonZeros |= (1 << i);
5057       NumNonZero++;
5058     }
5059   }
5060
5061   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5062   if (NumNonZero == 0)
5063     return DAG.getUNDEF(VT);
5064
5065   // Special case for single non-zero, non-undef, element.
5066   if (NumNonZero == 1) {
5067     unsigned Idx = CountTrailingZeros_32(NonZeros);
5068     SDValue Item = Op.getOperand(Idx);
5069
5070     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5071     // the value are obviously zero, truncate the value to i32 and do the
5072     // insertion that way.  Only do this if the value is non-constant or if the
5073     // value is a constant being inserted into element 0.  It is cheaper to do
5074     // a constant pool load than it is to do a movd + shuffle.
5075     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5076         (!IsAllConstants || Idx == 0)) {
5077       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5078         // Handle SSE only.
5079         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5080         EVT VecVT = MVT::v4i32;
5081         unsigned VecElts = 4;
5082
5083         // Truncate the value (which may itself be a constant) to i32, and
5084         // convert it to a vector with movd (S2V+shuffle to zero extend).
5085         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5086         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5087         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5088
5089         // Now we have our 32-bit value zero extended in the low element of
5090         // a vector.  If Idx != 0, swizzle it into place.
5091         if (Idx != 0) {
5092           SmallVector<int, 4> Mask;
5093           Mask.push_back(Idx);
5094           for (unsigned i = 1; i != VecElts; ++i)
5095             Mask.push_back(i);
5096           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5097                                       &Mask[0]);
5098         }
5099         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5100       }
5101     }
5102
5103     // If we have a constant or non-constant insertion into the low element of
5104     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5105     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5106     // depending on what the source datatype is.
5107     if (Idx == 0) {
5108       if (NumZero == 0)
5109         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5110
5111       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5112           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5113         if (VT.getSizeInBits() == 256) {
5114           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5115           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5116                              Item, DAG.getIntPtrConstant(0));
5117         }
5118         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5119         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5120         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5121         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5122       }
5123
5124       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5125         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5126         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5127         if (VT.getSizeInBits() == 256) {
5128           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5129           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5130         } else {
5131           assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5132           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5133         }
5134         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5135       }
5136     }
5137
5138     // Is it a vector logical left shift?
5139     if (NumElems == 2 && Idx == 1 &&
5140         X86::isZeroNode(Op.getOperand(0)) &&
5141         !X86::isZeroNode(Op.getOperand(1))) {
5142       unsigned NumBits = VT.getSizeInBits();
5143       return getVShift(true, VT,
5144                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5145                                    VT, Op.getOperand(1)),
5146                        NumBits/2, DAG, *this, dl);
5147     }
5148
5149     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5150       return SDValue();
5151
5152     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5153     // is a non-constant being inserted into an element other than the low one,
5154     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5155     // movd/movss) to move this into the low element, then shuffle it into
5156     // place.
5157     if (EVTBits == 32) {
5158       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5159
5160       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5161       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5162       SmallVector<int, 8> MaskVec;
5163       for (unsigned i = 0; i < NumElems; i++)
5164         MaskVec.push_back(i == Idx ? 0 : 1);
5165       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5166     }
5167   }
5168
5169   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5170   if (Values.size() == 1) {
5171     if (EVTBits == 32) {
5172       // Instead of a shuffle like this:
5173       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5174       // Check if it's possible to issue this instead.
5175       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5176       unsigned Idx = CountTrailingZeros_32(NonZeros);
5177       SDValue Item = Op.getOperand(Idx);
5178       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5179         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5180     }
5181     return SDValue();
5182   }
5183
5184   // A vector full of immediates; various special cases are already
5185   // handled, so this is best done with a single constant-pool load.
5186   if (IsAllConstants)
5187     return SDValue();
5188
5189   // For AVX-length vectors, build the individual 128-bit pieces and use
5190   // shuffles to put them in place.
5191   if (VT.getSizeInBits() == 256) {
5192     SmallVector<SDValue, 32> V;
5193     for (unsigned i = 0; i != NumElems; ++i)
5194       V.push_back(Op.getOperand(i));
5195
5196     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5197
5198     // Build both the lower and upper subvector.
5199     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5200     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5201                                 NumElems/2);
5202
5203     // Recreate the wider vector with the lower and upper part.
5204     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5205   }
5206
5207   // Let legalizer expand 2-wide build_vectors.
5208   if (EVTBits == 64) {
5209     if (NumNonZero == 1) {
5210       // One half is zero or undef.
5211       unsigned Idx = CountTrailingZeros_32(NonZeros);
5212       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5213                                  Op.getOperand(Idx));
5214       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5215     }
5216     return SDValue();
5217   }
5218
5219   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5220   if (EVTBits == 8 && NumElems == 16) {
5221     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5222                                         Subtarget, *this);
5223     if (V.getNode()) return V;
5224   }
5225
5226   if (EVTBits == 16 && NumElems == 8) {
5227     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5228                                       Subtarget, *this);
5229     if (V.getNode()) return V;
5230   }
5231
5232   // If element VT is == 32 bits, turn it into a number of shuffles.
5233   SmallVector<SDValue, 8> V(NumElems);
5234   if (NumElems == 4 && NumZero > 0) {
5235     for (unsigned i = 0; i < 4; ++i) {
5236       bool isZero = !(NonZeros & (1 << i));
5237       if (isZero)
5238         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5239       else
5240         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5241     }
5242
5243     for (unsigned i = 0; i < 2; ++i) {
5244       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5245         default: break;
5246         case 0:
5247           V[i] = V[i*2];  // Must be a zero vector.
5248           break;
5249         case 1:
5250           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5251           break;
5252         case 2:
5253           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5254           break;
5255         case 3:
5256           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5257           break;
5258       }
5259     }
5260
5261     bool Reverse1 = (NonZeros & 0x3) == 2;
5262     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5263     int MaskVec[] = {
5264       Reverse1 ? 1 : 0,
5265       Reverse1 ? 0 : 1,
5266       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5267       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5268     };
5269     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5270   }
5271
5272   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5273     // Check for a build vector of consecutive loads.
5274     for (unsigned i = 0; i < NumElems; ++i)
5275       V[i] = Op.getOperand(i);
5276
5277     // Check for elements which are consecutive loads.
5278     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5279     if (LD.getNode())
5280       return LD;
5281
5282     // For SSE 4.1, use insertps to put the high elements into the low element.
5283     if (getSubtarget()->hasSSE41()) {
5284       SDValue Result;
5285       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5286         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5287       else
5288         Result = DAG.getUNDEF(VT);
5289
5290       for (unsigned i = 1; i < NumElems; ++i) {
5291         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5292         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5293                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5294       }
5295       return Result;
5296     }
5297
5298     // Otherwise, expand into a number of unpckl*, start by extending each of
5299     // our (non-undef) elements to the full vector width with the element in the
5300     // bottom slot of the vector (which generates no code for SSE).
5301     for (unsigned i = 0; i < NumElems; ++i) {
5302       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5303         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5304       else
5305         V[i] = DAG.getUNDEF(VT);
5306     }
5307
5308     // Next, we iteratively mix elements, e.g. for v4f32:
5309     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5310     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5311     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5312     unsigned EltStride = NumElems >> 1;
5313     while (EltStride != 0) {
5314       for (unsigned i = 0; i < EltStride; ++i) {
5315         // If V[i+EltStride] is undef and this is the first round of mixing,
5316         // then it is safe to just drop this shuffle: V[i] is already in the
5317         // right place, the one element (since it's the first round) being
5318         // inserted as undef can be dropped.  This isn't safe for successive
5319         // rounds because they will permute elements within both vectors.
5320         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5321             EltStride == NumElems/2)
5322           continue;
5323
5324         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5325       }
5326       EltStride >>= 1;
5327     }
5328     return V[0];
5329   }
5330   return SDValue();
5331 }
5332
5333 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5334 // them in a MMX register.  This is better than doing a stack convert.
5335 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5336   DebugLoc dl = Op.getDebugLoc();
5337   EVT ResVT = Op.getValueType();
5338
5339   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5340          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5341   int Mask[2];
5342   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5343   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5344   InVec = Op.getOperand(1);
5345   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5346     unsigned NumElts = ResVT.getVectorNumElements();
5347     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5348     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5349                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5350   } else {
5351     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5352     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5353     Mask[0] = 0; Mask[1] = 2;
5354     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5355   }
5356   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5357 }
5358
5359 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5360 // to create 256-bit vectors from two other 128-bit ones.
5361 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5362   DebugLoc dl = Op.getDebugLoc();
5363   EVT ResVT = Op.getValueType();
5364
5365   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5366
5367   SDValue V1 = Op.getOperand(0);
5368   SDValue V2 = Op.getOperand(1);
5369   unsigned NumElems = ResVT.getVectorNumElements();
5370
5371   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5372 }
5373
5374 SDValue
5375 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5376   EVT ResVT = Op.getValueType();
5377
5378   assert(Op.getNumOperands() == 2);
5379   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5380          "Unsupported CONCAT_VECTORS for value type");
5381
5382   // We support concatenate two MMX registers and place them in a MMX register.
5383   // This is better than doing a stack convert.
5384   if (ResVT.is128BitVector())
5385     return LowerMMXCONCAT_VECTORS(Op, DAG);
5386
5387   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5388   // from two other 128-bit ones.
5389   return LowerAVXCONCAT_VECTORS(Op, DAG);
5390 }
5391
5392 // Try to lower a shuffle node into a simple blend instruction.
5393 static SDValue LowerVECTOR_SHUFFLEtoBlend(SDValue Op,
5394                                           const X86Subtarget *Subtarget,
5395                                           SelectionDAG &DAG) {
5396   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5397   SDValue V1 = SVOp->getOperand(0);
5398   SDValue V2 = SVOp->getOperand(1);
5399   DebugLoc dl = SVOp->getDebugLoc();
5400   EVT VT = Op.getValueType();
5401   EVT InVT = V1.getValueType();
5402   int MaskSize = VT.getVectorNumElements();
5403   int InSize = InVT.getVectorNumElements();
5404
5405   if (!Subtarget->hasSSE41())
5406     return SDValue();
5407
5408   if (MaskSize != InSize)
5409     return SDValue();
5410
5411   int ISDNo = 0;
5412   MVT OpTy;
5413
5414   switch (VT.getSimpleVT().SimpleTy) {
5415   default: return SDValue();
5416   case MVT::v8i16:
5417            ISDNo = X86ISD::BLENDPW;
5418            OpTy = MVT::v8i16;
5419            break;
5420   case MVT::v4i32:
5421   case MVT::v4f32:
5422            ISDNo = X86ISD::BLENDPS;
5423            OpTy = MVT::v4f32;
5424            break;
5425   case MVT::v2i64:
5426   case MVT::v2f64:
5427            ISDNo = X86ISD::BLENDPD;
5428            OpTy = MVT::v2f64;
5429            break;
5430   case MVT::v8i32:
5431   case MVT::v8f32:
5432            if (!Subtarget->hasAVX())
5433              return SDValue();
5434            ISDNo = X86ISD::BLENDPS;
5435            OpTy = MVT::v8f32;
5436            break;
5437   case MVT::v4i64:
5438   case MVT::v4f64:
5439            if (!Subtarget->hasAVX())
5440              return SDValue();
5441            ISDNo = X86ISD::BLENDPD;
5442            OpTy = MVT::v4f64;
5443            break;
5444   case MVT::v16i16:
5445            if (!Subtarget->hasAVX2())
5446              return SDValue();
5447            ISDNo = X86ISD::BLENDPW;
5448            OpTy = MVT::v16i16;
5449            break;
5450   }
5451   assert(ISDNo && "Invalid Op Number");
5452
5453   unsigned MaskVals = 0;
5454
5455   for (int i = 0; i < MaskSize; ++i) {
5456     int EltIdx = SVOp->getMaskElt(i);
5457     if (EltIdx == i || EltIdx == -1)
5458       MaskVals |= (1<<i);
5459     else if (EltIdx == (i + MaskSize))
5460       continue; // Bit is set to zero;
5461     else return SDValue();
5462   }
5463
5464   V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5465   V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5466   SDValue Ret =  DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5467                              DAG.getConstant(MaskVals, MVT::i32));
5468   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5469 }
5470
5471 // v8i16 shuffles - Prefer shuffles in the following order:
5472 // 1. [all]   pshuflw, pshufhw, optional move
5473 // 2. [ssse3] 1 x pshufb
5474 // 3. [ssse3] 2 x pshufb + 1 x por
5475 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5476 SDValue
5477 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5478                                             SelectionDAG &DAG) const {
5479   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5480   SDValue V1 = SVOp->getOperand(0);
5481   SDValue V2 = SVOp->getOperand(1);
5482   DebugLoc dl = SVOp->getDebugLoc();
5483   SmallVector<int, 8> MaskVals;
5484
5485   // Determine if more than 1 of the words in each of the low and high quadwords
5486   // of the result come from the same quadword of one of the two inputs.  Undef
5487   // mask values count as coming from any quadword, for better codegen.
5488   unsigned LoQuad[] = { 0, 0, 0, 0 };
5489   unsigned HiQuad[] = { 0, 0, 0, 0 };
5490   std::bitset<4> InputQuads;
5491   for (unsigned i = 0; i < 8; ++i) {
5492     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5493     int EltIdx = SVOp->getMaskElt(i);
5494     MaskVals.push_back(EltIdx);
5495     if (EltIdx < 0) {
5496       ++Quad[0];
5497       ++Quad[1];
5498       ++Quad[2];
5499       ++Quad[3];
5500       continue;
5501     }
5502     ++Quad[EltIdx / 4];
5503     InputQuads.set(EltIdx / 4);
5504   }
5505
5506   int BestLoQuad = -1;
5507   unsigned MaxQuad = 1;
5508   for (unsigned i = 0; i < 4; ++i) {
5509     if (LoQuad[i] > MaxQuad) {
5510       BestLoQuad = i;
5511       MaxQuad = LoQuad[i];
5512     }
5513   }
5514
5515   int BestHiQuad = -1;
5516   MaxQuad = 1;
5517   for (unsigned i = 0; i < 4; ++i) {
5518     if (HiQuad[i] > MaxQuad) {
5519       BestHiQuad = i;
5520       MaxQuad = HiQuad[i];
5521     }
5522   }
5523
5524   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5525   // of the two input vectors, shuffle them into one input vector so only a
5526   // single pshufb instruction is necessary. If There are more than 2 input
5527   // quads, disable the next transformation since it does not help SSSE3.
5528   bool V1Used = InputQuads[0] || InputQuads[1];
5529   bool V2Used = InputQuads[2] || InputQuads[3];
5530   if (Subtarget->hasSSSE3()) {
5531     if (InputQuads.count() == 2 && V1Used && V2Used) {
5532       BestLoQuad = InputQuads[0] ? 0 : 1;
5533       BestHiQuad = InputQuads[2] ? 2 : 3;
5534     }
5535     if (InputQuads.count() > 2) {
5536       BestLoQuad = -1;
5537       BestHiQuad = -1;
5538     }
5539   }
5540
5541   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5542   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5543   // words from all 4 input quadwords.
5544   SDValue NewV;
5545   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5546     int MaskV[] = {
5547       BestLoQuad < 0 ? 0 : BestLoQuad,
5548       BestHiQuad < 0 ? 1 : BestHiQuad
5549     };
5550     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5551                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5552                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5553     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5554
5555     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5556     // source words for the shuffle, to aid later transformations.
5557     bool AllWordsInNewV = true;
5558     bool InOrder[2] = { true, true };
5559     for (unsigned i = 0; i != 8; ++i) {
5560       int idx = MaskVals[i];
5561       if (idx != (int)i)
5562         InOrder[i/4] = false;
5563       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5564         continue;
5565       AllWordsInNewV = false;
5566       break;
5567     }
5568
5569     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5570     if (AllWordsInNewV) {
5571       for (int i = 0; i != 8; ++i) {
5572         int idx = MaskVals[i];
5573         if (idx < 0)
5574           continue;
5575         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5576         if ((idx != i) && idx < 4)
5577           pshufhw = false;
5578         if ((idx != i) && idx > 3)
5579           pshuflw = false;
5580       }
5581       V1 = NewV;
5582       V2Used = false;
5583       BestLoQuad = 0;
5584       BestHiQuad = 1;
5585     }
5586
5587     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5588     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5589     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5590       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5591       unsigned TargetMask = 0;
5592       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5593                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5594       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5595       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5596                              getShufflePSHUFLWImmediate(SVOp);
5597       V1 = NewV.getOperand(0);
5598       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5599     }
5600   }
5601
5602   // If we have SSSE3, and all words of the result are from 1 input vector,
5603   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5604   // is present, fall back to case 4.
5605   if (Subtarget->hasSSSE3()) {
5606     SmallVector<SDValue,16> pshufbMask;
5607
5608     // If we have elements from both input vectors, set the high bit of the
5609     // shuffle mask element to zero out elements that come from V2 in the V1
5610     // mask, and elements that come from V1 in the V2 mask, so that the two
5611     // results can be OR'd together.
5612     bool TwoInputs = V1Used && V2Used;
5613     for (unsigned i = 0; i != 8; ++i) {
5614       int EltIdx = MaskVals[i] * 2;
5615       if (TwoInputs && (EltIdx >= 16)) {
5616         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5617         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5618         continue;
5619       }
5620       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5621       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5622     }
5623     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5624     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5625                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5626                                  MVT::v16i8, &pshufbMask[0], 16));
5627     if (!TwoInputs)
5628       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5629
5630     // Calculate the shuffle mask for the second input, shuffle it, and
5631     // OR it with the first shuffled input.
5632     pshufbMask.clear();
5633     for (unsigned i = 0; i != 8; ++i) {
5634       int EltIdx = MaskVals[i] * 2;
5635       if (EltIdx < 16) {
5636         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5637         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5638         continue;
5639       }
5640       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5641       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5642     }
5643     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5644     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5645                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5646                                  MVT::v16i8, &pshufbMask[0], 16));
5647     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5648     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5649   }
5650
5651   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5652   // and update MaskVals with new element order.
5653   std::bitset<8> InOrder;
5654   if (BestLoQuad >= 0) {
5655     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5656     for (int i = 0; i != 4; ++i) {
5657       int idx = MaskVals[i];
5658       if (idx < 0) {
5659         InOrder.set(i);
5660       } else if ((idx / 4) == BestLoQuad) {
5661         MaskV[i] = idx & 3;
5662         InOrder.set(i);
5663       }
5664     }
5665     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5666                                 &MaskV[0]);
5667
5668     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5669       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5670       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5671                                   NewV.getOperand(0),
5672                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5673     }
5674   }
5675
5676   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5677   // and update MaskVals with the new element order.
5678   if (BestHiQuad >= 0) {
5679     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5680     for (unsigned i = 4; i != 8; ++i) {
5681       int idx = MaskVals[i];
5682       if (idx < 0) {
5683         InOrder.set(i);
5684       } else if ((idx / 4) == BestHiQuad) {
5685         MaskV[i] = (idx & 3) + 4;
5686         InOrder.set(i);
5687       }
5688     }
5689     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5690                                 &MaskV[0]);
5691
5692     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5693       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5694       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5695                                   NewV.getOperand(0),
5696                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5697     }
5698   }
5699
5700   // In case BestHi & BestLo were both -1, which means each quadword has a word
5701   // from each of the four input quadwords, calculate the InOrder bitvector now
5702   // before falling through to the insert/extract cleanup.
5703   if (BestLoQuad == -1 && BestHiQuad == -1) {
5704     NewV = V1;
5705     for (int i = 0; i != 8; ++i)
5706       if (MaskVals[i] < 0 || MaskVals[i] == i)
5707         InOrder.set(i);
5708   }
5709
5710   // The other elements are put in the right place using pextrw and pinsrw.
5711   for (unsigned i = 0; i != 8; ++i) {
5712     if (InOrder[i])
5713       continue;
5714     int EltIdx = MaskVals[i];
5715     if (EltIdx < 0)
5716       continue;
5717     SDValue ExtOp = (EltIdx < 8)
5718     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5719                   DAG.getIntPtrConstant(EltIdx))
5720     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5721                   DAG.getIntPtrConstant(EltIdx - 8));
5722     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5723                        DAG.getIntPtrConstant(i));
5724   }
5725   return NewV;
5726 }
5727
5728 // v16i8 shuffles - Prefer shuffles in the following order:
5729 // 1. [ssse3] 1 x pshufb
5730 // 2. [ssse3] 2 x pshufb + 1 x por
5731 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5732 static
5733 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5734                                  SelectionDAG &DAG,
5735                                  const X86TargetLowering &TLI) {
5736   SDValue V1 = SVOp->getOperand(0);
5737   SDValue V2 = SVOp->getOperand(1);
5738   DebugLoc dl = SVOp->getDebugLoc();
5739   ArrayRef<int> MaskVals = SVOp->getMask();
5740
5741   // If we have SSSE3, case 1 is generated when all result bytes come from
5742   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5743   // present, fall back to case 3.
5744   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5745   bool V1Only = true;
5746   bool V2Only = true;
5747   for (unsigned i = 0; i < 16; ++i) {
5748     int EltIdx = MaskVals[i];
5749     if (EltIdx < 0)
5750       continue;
5751     if (EltIdx < 16)
5752       V2Only = false;
5753     else
5754       V1Only = false;
5755   }
5756
5757   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5758   if (TLI.getSubtarget()->hasSSSE3()) {
5759     SmallVector<SDValue,16> pshufbMask;
5760
5761     // If all result elements are from one input vector, then only translate
5762     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5763     //
5764     // Otherwise, we have elements from both input vectors, and must zero out
5765     // elements that come from V2 in the first mask, and V1 in the second mask
5766     // so that we can OR them together.
5767     bool TwoInputs = !(V1Only || V2Only);
5768     for (unsigned i = 0; i != 16; ++i) {
5769       int EltIdx = MaskVals[i];
5770       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5771         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5772         continue;
5773       }
5774       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5775     }
5776     // If all the elements are from V2, assign it to V1 and return after
5777     // building the first pshufb.
5778     if (V2Only)
5779       V1 = V2;
5780     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5781                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5782                                  MVT::v16i8, &pshufbMask[0], 16));
5783     if (!TwoInputs)
5784       return V1;
5785
5786     // Calculate the shuffle mask for the second input, shuffle it, and
5787     // OR it with the first shuffled input.
5788     pshufbMask.clear();
5789     for (unsigned i = 0; i != 16; ++i) {
5790       int EltIdx = MaskVals[i];
5791       if (EltIdx < 16) {
5792         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5793         continue;
5794       }
5795       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5796     }
5797     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5798                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5799                                  MVT::v16i8, &pshufbMask[0], 16));
5800     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5801   }
5802
5803   // No SSSE3 - Calculate in place words and then fix all out of place words
5804   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5805   // the 16 different words that comprise the two doublequadword input vectors.
5806   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5807   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5808   SDValue NewV = V2Only ? V2 : V1;
5809   for (int i = 0; i != 8; ++i) {
5810     int Elt0 = MaskVals[i*2];
5811     int Elt1 = MaskVals[i*2+1];
5812
5813     // This word of the result is all undef, skip it.
5814     if (Elt0 < 0 && Elt1 < 0)
5815       continue;
5816
5817     // This word of the result is already in the correct place, skip it.
5818     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5819       continue;
5820     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5821       continue;
5822
5823     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5824     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5825     SDValue InsElt;
5826
5827     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5828     // using a single extract together, load it and store it.
5829     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5830       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5831                            DAG.getIntPtrConstant(Elt1 / 2));
5832       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5833                         DAG.getIntPtrConstant(i));
5834       continue;
5835     }
5836
5837     // If Elt1 is defined, extract it from the appropriate source.  If the
5838     // source byte is not also odd, shift the extracted word left 8 bits
5839     // otherwise clear the bottom 8 bits if we need to do an or.
5840     if (Elt1 >= 0) {
5841       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5842                            DAG.getIntPtrConstant(Elt1 / 2));
5843       if ((Elt1 & 1) == 0)
5844         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5845                              DAG.getConstant(8,
5846                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5847       else if (Elt0 >= 0)
5848         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5849                              DAG.getConstant(0xFF00, MVT::i16));
5850     }
5851     // If Elt0 is defined, extract it from the appropriate source.  If the
5852     // source byte is not also even, shift the extracted word right 8 bits. If
5853     // Elt1 was also defined, OR the extracted values together before
5854     // inserting them in the result.
5855     if (Elt0 >= 0) {
5856       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5857                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5858       if ((Elt0 & 1) != 0)
5859         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5860                               DAG.getConstant(8,
5861                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5862       else if (Elt1 >= 0)
5863         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5864                              DAG.getConstant(0x00FF, MVT::i16));
5865       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5866                          : InsElt0;
5867     }
5868     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5869                        DAG.getIntPtrConstant(i));
5870   }
5871   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5872 }
5873
5874 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5875 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5876 /// done when every pair / quad of shuffle mask elements point to elements in
5877 /// the right sequence. e.g.
5878 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5879 static
5880 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5881                                  SelectionDAG &DAG, DebugLoc dl) {
5882   EVT VT = SVOp->getValueType(0);
5883   SDValue V1 = SVOp->getOperand(0);
5884   SDValue V2 = SVOp->getOperand(1);
5885   unsigned NumElems = VT.getVectorNumElements();
5886   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5887   EVT NewVT;
5888   switch (VT.getSimpleVT().SimpleTy) {
5889   default: llvm_unreachable("Unexpected!");
5890   case MVT::v4f32: NewVT = MVT::v2f64; break;
5891   case MVT::v4i32: NewVT = MVT::v2i64; break;
5892   case MVT::v8i16: NewVT = MVT::v4i32; break;
5893   case MVT::v16i8: NewVT = MVT::v4i32; break;
5894   }
5895
5896   int Scale = NumElems / NewWidth;
5897   SmallVector<int, 8> MaskVec;
5898   for (unsigned i = 0; i < NumElems; i += Scale) {
5899     int StartIdx = -1;
5900     for (int j = 0; j < Scale; ++j) {
5901       int EltIdx = SVOp->getMaskElt(i+j);
5902       if (EltIdx < 0)
5903         continue;
5904       if (StartIdx == -1)
5905         StartIdx = EltIdx - (EltIdx % Scale);
5906       if (EltIdx != StartIdx + j)
5907         return SDValue();
5908     }
5909     if (StartIdx == -1)
5910       MaskVec.push_back(-1);
5911     else
5912       MaskVec.push_back(StartIdx / Scale);
5913   }
5914
5915   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5916   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5917   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5918 }
5919
5920 /// getVZextMovL - Return a zero-extending vector move low node.
5921 ///
5922 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5923                             SDValue SrcOp, SelectionDAG &DAG,
5924                             const X86Subtarget *Subtarget, DebugLoc dl) {
5925   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5926     LoadSDNode *LD = NULL;
5927     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5928       LD = dyn_cast<LoadSDNode>(SrcOp);
5929     if (!LD) {
5930       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5931       // instead.
5932       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5933       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5934           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5935           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5936           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5937         // PR2108
5938         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5939         return DAG.getNode(ISD::BITCAST, dl, VT,
5940                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5941                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5942                                                    OpVT,
5943                                                    SrcOp.getOperand(0)
5944                                                           .getOperand(0))));
5945       }
5946     }
5947   }
5948
5949   return DAG.getNode(ISD::BITCAST, dl, VT,
5950                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5951                                  DAG.getNode(ISD::BITCAST, dl,
5952                                              OpVT, SrcOp)));
5953 }
5954
5955 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5956 /// which could not be matched by any known target speficic shuffle
5957 static SDValue
5958 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5959   EVT VT = SVOp->getValueType(0);
5960
5961   unsigned NumElems = VT.getVectorNumElements();
5962   unsigned NumLaneElems = NumElems / 2;
5963
5964   DebugLoc dl = SVOp->getDebugLoc();
5965   MVT EltVT = VT.getVectorElementType().getSimpleVT();
5966   EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
5967   SDValue Shufs[2];
5968
5969   SmallVector<int, 16> Mask;
5970   for (unsigned l = 0; l < 2; ++l) {
5971     // Build a shuffle mask for the output, discovering on the fly which
5972     // input vectors to use as shuffle operands (recorded in InputUsed).
5973     // If building a suitable shuffle vector proves too hard, then bail
5974     // out with useBuildVector set.
5975     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
5976     unsigned LaneStart = l * NumLaneElems;
5977     for (unsigned i = 0; i != NumLaneElems; ++i) {
5978       // The mask element.  This indexes into the input.
5979       int Idx = SVOp->getMaskElt(i+LaneStart);
5980       if (Idx < 0) {
5981         // the mask element does not index into any input vector.
5982         Mask.push_back(-1);
5983         continue;
5984       }
5985
5986       // The input vector this mask element indexes into.
5987       int Input = Idx / NumLaneElems;
5988
5989       // Turn the index into an offset from the start of the input vector.
5990       Idx -= Input * NumLaneElems;
5991
5992       // Find or create a shuffle vector operand to hold this input.
5993       unsigned OpNo;
5994       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
5995         if (InputUsed[OpNo] == Input)
5996           // This input vector is already an operand.
5997           break;
5998         if (InputUsed[OpNo] < 0) {
5999           // Create a new operand for this input vector.
6000           InputUsed[OpNo] = Input;
6001           break;
6002         }
6003       }
6004
6005       if (OpNo >= array_lengthof(InputUsed)) {
6006         // More than two input vectors used! Give up.
6007         return SDValue();
6008       }
6009
6010       // Add the mask index for the new shuffle vector.
6011       Mask.push_back(Idx + OpNo * NumLaneElems);
6012     }
6013
6014     if (InputUsed[0] < 0) {
6015       // No input vectors were used! The result is undefined.
6016       Shufs[l] = DAG.getUNDEF(NVT);
6017     } else {
6018       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6019                                         (InputUsed[0] % 2) * NumLaneElems,
6020                                         DAG, dl);
6021       // If only one input was used, use an undefined vector for the other.
6022       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6023         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6024                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6025       // At least one input vector was used. Create a new shuffle vector.
6026       Shufs[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6027     }
6028
6029     Mask.clear();
6030   }
6031
6032   // Concatenate the result back
6033   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Shufs[0], Shufs[1]);
6034 }
6035
6036 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6037 /// 4 elements, and match them with several different shuffle types.
6038 static SDValue
6039 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6040   SDValue V1 = SVOp->getOperand(0);
6041   SDValue V2 = SVOp->getOperand(1);
6042   DebugLoc dl = SVOp->getDebugLoc();
6043   EVT VT = SVOp->getValueType(0);
6044
6045   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6046
6047   std::pair<int, int> Locs[4];
6048   int Mask1[] = { -1, -1, -1, -1 };
6049   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6050
6051   unsigned NumHi = 0;
6052   unsigned NumLo = 0;
6053   for (unsigned i = 0; i != 4; ++i) {
6054     int Idx = PermMask[i];
6055     if (Idx < 0) {
6056       Locs[i] = std::make_pair(-1, -1);
6057     } else {
6058       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6059       if (Idx < 4) {
6060         Locs[i] = std::make_pair(0, NumLo);
6061         Mask1[NumLo] = Idx;
6062         NumLo++;
6063       } else {
6064         Locs[i] = std::make_pair(1, NumHi);
6065         if (2+NumHi < 4)
6066           Mask1[2+NumHi] = Idx;
6067         NumHi++;
6068       }
6069     }
6070   }
6071
6072   if (NumLo <= 2 && NumHi <= 2) {
6073     // If no more than two elements come from either vector. This can be
6074     // implemented with two shuffles. First shuffle gather the elements.
6075     // The second shuffle, which takes the first shuffle as both of its
6076     // vector operands, put the elements into the right order.
6077     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6078
6079     int Mask2[] = { -1, -1, -1, -1 };
6080
6081     for (unsigned i = 0; i != 4; ++i)
6082       if (Locs[i].first != -1) {
6083         unsigned Idx = (i < 2) ? 0 : 4;
6084         Idx += Locs[i].first * 2 + Locs[i].second;
6085         Mask2[i] = Idx;
6086       }
6087
6088     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6089   } else if (NumLo == 3 || NumHi == 3) {
6090     // Otherwise, we must have three elements from one vector, call it X, and
6091     // one element from the other, call it Y.  First, use a shufps to build an
6092     // intermediate vector with the one element from Y and the element from X
6093     // that will be in the same half in the final destination (the indexes don't
6094     // matter). Then, use a shufps to build the final vector, taking the half
6095     // containing the element from Y from the intermediate, and the other half
6096     // from X.
6097     if (NumHi == 3) {
6098       // Normalize it so the 3 elements come from V1.
6099       CommuteVectorShuffleMask(PermMask, 4);
6100       std::swap(V1, V2);
6101     }
6102
6103     // Find the element from V2.
6104     unsigned HiIndex;
6105     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6106       int Val = PermMask[HiIndex];
6107       if (Val < 0)
6108         continue;
6109       if (Val >= 4)
6110         break;
6111     }
6112
6113     Mask1[0] = PermMask[HiIndex];
6114     Mask1[1] = -1;
6115     Mask1[2] = PermMask[HiIndex^1];
6116     Mask1[3] = -1;
6117     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6118
6119     if (HiIndex >= 2) {
6120       Mask1[0] = PermMask[0];
6121       Mask1[1] = PermMask[1];
6122       Mask1[2] = HiIndex & 1 ? 6 : 4;
6123       Mask1[3] = HiIndex & 1 ? 4 : 6;
6124       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6125     } else {
6126       Mask1[0] = HiIndex & 1 ? 2 : 0;
6127       Mask1[1] = HiIndex & 1 ? 0 : 2;
6128       Mask1[2] = PermMask[2];
6129       Mask1[3] = PermMask[3];
6130       if (Mask1[2] >= 0)
6131         Mask1[2] += 4;
6132       if (Mask1[3] >= 0)
6133         Mask1[3] += 4;
6134       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6135     }
6136   }
6137
6138   // Break it into (shuffle shuffle_hi, shuffle_lo).
6139   int LoMask[] = { -1, -1, -1, -1 };
6140   int HiMask[] = { -1, -1, -1, -1 };
6141
6142   int *MaskPtr = LoMask;
6143   unsigned MaskIdx = 0;
6144   unsigned LoIdx = 0;
6145   unsigned HiIdx = 2;
6146   for (unsigned i = 0; i != 4; ++i) {
6147     if (i == 2) {
6148       MaskPtr = HiMask;
6149       MaskIdx = 1;
6150       LoIdx = 0;
6151       HiIdx = 2;
6152     }
6153     int Idx = PermMask[i];
6154     if (Idx < 0) {
6155       Locs[i] = std::make_pair(-1, -1);
6156     } else if (Idx < 4) {
6157       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6158       MaskPtr[LoIdx] = Idx;
6159       LoIdx++;
6160     } else {
6161       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6162       MaskPtr[HiIdx] = Idx;
6163       HiIdx++;
6164     }
6165   }
6166
6167   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6168   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6169   int MaskOps[] = { -1, -1, -1, -1 };
6170   for (unsigned i = 0; i != 4; ++i)
6171     if (Locs[i].first != -1)
6172       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6173   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6174 }
6175
6176 static bool MayFoldVectorLoad(SDValue V) {
6177   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6178     V = V.getOperand(0);
6179   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6180     V = V.getOperand(0);
6181   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6182       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6183     // BUILD_VECTOR (load), undef
6184     V = V.getOperand(0);
6185   if (MayFoldLoad(V))
6186     return true;
6187   return false;
6188 }
6189
6190 // FIXME: the version above should always be used. Since there's
6191 // a bug where several vector shuffles can't be folded because the
6192 // DAG is not updated during lowering and a node claims to have two
6193 // uses while it only has one, use this version, and let isel match
6194 // another instruction if the load really happens to have more than
6195 // one use. Remove this version after this bug get fixed.
6196 // rdar://8434668, PR8156
6197 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6198   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6199     V = V.getOperand(0);
6200   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6201     V = V.getOperand(0);
6202   if (ISD::isNormalLoad(V.getNode()))
6203     return true;
6204   return false;
6205 }
6206
6207 static
6208 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6209   EVT VT = Op.getValueType();
6210
6211   // Canonizalize to v2f64.
6212   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6213   return DAG.getNode(ISD::BITCAST, dl, VT,
6214                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6215                                           V1, DAG));
6216 }
6217
6218 static
6219 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6220                         bool HasSSE2) {
6221   SDValue V1 = Op.getOperand(0);
6222   SDValue V2 = Op.getOperand(1);
6223   EVT VT = Op.getValueType();
6224
6225   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6226
6227   if (HasSSE2 && VT == MVT::v2f64)
6228     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6229
6230   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6231   return DAG.getNode(ISD::BITCAST, dl, VT,
6232                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6233                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6234                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6235 }
6236
6237 static
6238 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6239   SDValue V1 = Op.getOperand(0);
6240   SDValue V2 = Op.getOperand(1);
6241   EVT VT = Op.getValueType();
6242
6243   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6244          "unsupported shuffle type");
6245
6246   if (V2.getOpcode() == ISD::UNDEF)
6247     V2 = V1;
6248
6249   // v4i32 or v4f32
6250   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6251 }
6252
6253 static
6254 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6255   SDValue V1 = Op.getOperand(0);
6256   SDValue V2 = Op.getOperand(1);
6257   EVT VT = Op.getValueType();
6258   unsigned NumElems = VT.getVectorNumElements();
6259
6260   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6261   // operand of these instructions is only memory, so check if there's a
6262   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6263   // same masks.
6264   bool CanFoldLoad = false;
6265
6266   // Trivial case, when V2 comes from a load.
6267   if (MayFoldVectorLoad(V2))
6268     CanFoldLoad = true;
6269
6270   // When V1 is a load, it can be folded later into a store in isel, example:
6271   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6272   //    turns into:
6273   //  (MOVLPSmr addr:$src1, VR128:$src2)
6274   // So, recognize this potential and also use MOVLPS or MOVLPD
6275   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6276     CanFoldLoad = true;
6277
6278   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6279   if (CanFoldLoad) {
6280     if (HasSSE2 && NumElems == 2)
6281       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6282
6283     if (NumElems == 4)
6284       // If we don't care about the second element, procede to use movss.
6285       if (SVOp->getMaskElt(1) != -1)
6286         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6287   }
6288
6289   // movl and movlp will both match v2i64, but v2i64 is never matched by
6290   // movl earlier because we make it strict to avoid messing with the movlp load
6291   // folding logic (see the code above getMOVLP call). Match it here then,
6292   // this is horrible, but will stay like this until we move all shuffle
6293   // matching to x86 specific nodes. Note that for the 1st condition all
6294   // types are matched with movsd.
6295   if (HasSSE2) {
6296     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6297     // as to remove this logic from here, as much as possible
6298     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6299       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6300     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6301   }
6302
6303   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6304
6305   // Invert the operand order and use SHUFPS to match it.
6306   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6307                               getShuffleSHUFImmediate(SVOp), DAG);
6308 }
6309
6310 SDValue
6311 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6312   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6313   EVT VT = Op.getValueType();
6314   DebugLoc dl = Op.getDebugLoc();
6315   SDValue V1 = Op.getOperand(0);
6316   SDValue V2 = Op.getOperand(1);
6317
6318   if (isZeroShuffle(SVOp))
6319     return getZeroVector(VT, Subtarget, DAG, dl);
6320
6321   // Handle splat operations
6322   if (SVOp->isSplat()) {
6323     unsigned NumElem = VT.getVectorNumElements();
6324     int Size = VT.getSizeInBits();
6325
6326     // Use vbroadcast whenever the splat comes from a foldable load
6327     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6328     if (Broadcast.getNode())
6329       return Broadcast;
6330
6331     // Handle splats by matching through known shuffle masks
6332     if ((Size == 128 && NumElem <= 4) ||
6333         (Size == 256 && NumElem < 8))
6334       return SDValue();
6335
6336     // All remaning splats are promoted to target supported vector shuffles.
6337     return PromoteSplat(SVOp, DAG);
6338   }
6339
6340   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6341   // do it!
6342   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6343     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6344     if (NewOp.getNode())
6345       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6346   } else if ((VT == MVT::v4i32 ||
6347              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6348     // FIXME: Figure out a cleaner way to do this.
6349     // Try to make use of movq to zero out the top part.
6350     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6351       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6352       if (NewOp.getNode()) {
6353         EVT NewVT = NewOp.getValueType();
6354         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6355                                NewVT, true, false))
6356           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6357                               DAG, Subtarget, dl);
6358       }
6359     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6360       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6361       if (NewOp.getNode()) {
6362         EVT NewVT = NewOp.getValueType();
6363         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6364           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6365                               DAG, Subtarget, dl);
6366       }
6367     }
6368   }
6369   return SDValue();
6370 }
6371
6372 SDValue
6373 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6374   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6375   SDValue V1 = Op.getOperand(0);
6376   SDValue V2 = Op.getOperand(1);
6377   EVT VT = Op.getValueType();
6378   DebugLoc dl = Op.getDebugLoc();
6379   unsigned NumElems = VT.getVectorNumElements();
6380   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6381   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6382   bool V1IsSplat = false;
6383   bool V2IsSplat = false;
6384   bool HasSSE2 = Subtarget->hasSSE2();
6385   bool HasAVX    = Subtarget->hasAVX();
6386   bool HasAVX2   = Subtarget->hasAVX2();
6387   MachineFunction &MF = DAG.getMachineFunction();
6388   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6389
6390   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6391
6392   if (V1IsUndef && V2IsUndef)
6393     return DAG.getUNDEF(VT);
6394
6395   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6396
6397   // Vector shuffle lowering takes 3 steps:
6398   //
6399   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6400   //    narrowing and commutation of operands should be handled.
6401   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6402   //    shuffle nodes.
6403   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6404   //    so the shuffle can be broken into other shuffles and the legalizer can
6405   //    try the lowering again.
6406   //
6407   // The general idea is that no vector_shuffle operation should be left to
6408   // be matched during isel, all of them must be converted to a target specific
6409   // node here.
6410
6411   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6412   // narrowing and commutation of operands should be handled. The actual code
6413   // doesn't include all of those, work in progress...
6414   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6415   if (NewOp.getNode())
6416     return NewOp;
6417
6418   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6419
6420   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6421   // unpckh_undef). Only use pshufd if speed is more important than size.
6422   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6423     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6424   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6425     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6426
6427   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6428       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6429     return getMOVDDup(Op, dl, V1, DAG);
6430
6431   if (isMOVHLPS_v_undef_Mask(M, VT))
6432     return getMOVHighToLow(Op, dl, DAG);
6433
6434   // Use to match splats
6435   if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6436       (VT == MVT::v2f64 || VT == MVT::v2i64))
6437     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6438
6439   if (isPSHUFDMask(M, VT)) {
6440     // The actual implementation will match the mask in the if above and then
6441     // during isel it can match several different instructions, not only pshufd
6442     // as its name says, sad but true, emulate the behavior for now...
6443     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6444       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6445
6446     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6447
6448     if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6449       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6450
6451     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6452       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6453
6454     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6455                                 TargetMask, DAG);
6456   }
6457
6458   // Check if this can be converted into a logical shift.
6459   bool isLeft = false;
6460   unsigned ShAmt = 0;
6461   SDValue ShVal;
6462   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6463   if (isShift && ShVal.hasOneUse()) {
6464     // If the shifted value has multiple uses, it may be cheaper to use
6465     // v_set0 + movlhps or movhlps, etc.
6466     EVT EltVT = VT.getVectorElementType();
6467     ShAmt *= EltVT.getSizeInBits();
6468     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6469   }
6470
6471   if (isMOVLMask(M, VT)) {
6472     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6473       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6474     if (!isMOVLPMask(M, VT)) {
6475       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6476         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6477
6478       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6479         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6480     }
6481   }
6482
6483   // FIXME: fold these into legal mask.
6484   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6485     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6486
6487   if (isMOVHLPSMask(M, VT))
6488     return getMOVHighToLow(Op, dl, DAG);
6489
6490   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6491     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6492
6493   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6494     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6495
6496   if (isMOVLPMask(M, VT))
6497     return getMOVLP(Op, dl, DAG, HasSSE2);
6498
6499   if (ShouldXformToMOVHLPS(M, VT) ||
6500       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6501     return CommuteVectorShuffle(SVOp, DAG);
6502
6503   if (isShift) {
6504     // No better options. Use a vshldq / vsrldq.
6505     EVT EltVT = VT.getVectorElementType();
6506     ShAmt *= EltVT.getSizeInBits();
6507     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6508   }
6509
6510   bool Commuted = false;
6511   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6512   // 1,1,1,1 -> v8i16 though.
6513   V1IsSplat = isSplatVector(V1.getNode());
6514   V2IsSplat = isSplatVector(V2.getNode());
6515
6516   // Canonicalize the splat or undef, if present, to be on the RHS.
6517   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6518     CommuteVectorShuffleMask(M, NumElems);
6519     std::swap(V1, V2);
6520     std::swap(V1IsSplat, V2IsSplat);
6521     Commuted = true;
6522   }
6523
6524   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6525     // Shuffling low element of v1 into undef, just return v1.
6526     if (V2IsUndef)
6527       return V1;
6528     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6529     // the instruction selector will not match, so get a canonical MOVL with
6530     // swapped operands to undo the commute.
6531     return getMOVL(DAG, dl, VT, V2, V1);
6532   }
6533
6534   if (isUNPCKLMask(M, VT, HasAVX2))
6535     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6536
6537   if (isUNPCKHMask(M, VT, HasAVX2))
6538     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6539
6540   if (V2IsSplat) {
6541     // Normalize mask so all entries that point to V2 points to its first
6542     // element then try to match unpck{h|l} again. If match, return a
6543     // new vector_shuffle with the corrected mask.p
6544     SmallVector<int, 8> NewMask(M.begin(), M.end());
6545     NormalizeMask(NewMask, NumElems);
6546     if (isUNPCKLMask(NewMask, VT, HasAVX2, true)) {
6547       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6548     } else if (isUNPCKHMask(NewMask, VT, HasAVX2, true)) {
6549       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6550     }
6551   }
6552
6553   if (Commuted) {
6554     // Commute is back and try unpck* again.
6555     // FIXME: this seems wrong.
6556     CommuteVectorShuffleMask(M, NumElems);
6557     std::swap(V1, V2);
6558     std::swap(V1IsSplat, V2IsSplat);
6559     Commuted = false;
6560
6561     if (isUNPCKLMask(M, VT, HasAVX2))
6562       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6563
6564     if (isUNPCKHMask(M, VT, HasAVX2))
6565       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6566   }
6567
6568   // Normalize the node to match x86 shuffle ops if needed
6569   if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6570     return CommuteVectorShuffle(SVOp, DAG);
6571
6572   // The checks below are all present in isShuffleMaskLegal, but they are
6573   // inlined here right now to enable us to directly emit target specific
6574   // nodes, and remove one by one until they don't return Op anymore.
6575
6576   if (isPALIGNRMask(M, VT, Subtarget))
6577     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6578                                 getShufflePALIGNRImmediate(SVOp),
6579                                 DAG);
6580
6581   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6582       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6583     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6584       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6585   }
6586
6587   if (isPSHUFHWMask(M, VT))
6588     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6589                                 getShufflePSHUFHWImmediate(SVOp),
6590                                 DAG);
6591
6592   if (isPSHUFLWMask(M, VT))
6593     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6594                                 getShufflePSHUFLWImmediate(SVOp),
6595                                 DAG);
6596
6597   if (isSHUFPMask(M, VT, HasAVX))
6598     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6599                                 getShuffleSHUFImmediate(SVOp), DAG);
6600
6601   if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6602     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6603   if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6604     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6605
6606   //===--------------------------------------------------------------------===//
6607   // Generate target specific nodes for 128 or 256-bit shuffles only
6608   // supported in the AVX instruction set.
6609   //
6610
6611   // Handle VMOVDDUPY permutations
6612   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6613     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6614
6615   // Handle VPERMILPS/D* permutations
6616   if (isVPERMILPMask(M, VT, HasAVX)) {
6617     if (HasAVX2 && VT == MVT::v8i32)
6618       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6619                                   getShuffleSHUFImmediate(SVOp), DAG);
6620     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6621                                 getShuffleSHUFImmediate(SVOp), DAG);
6622   }
6623
6624   // Handle VPERM2F128/VPERM2I128 permutations
6625   if (isVPERM2X128Mask(M, VT, HasAVX))
6626     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6627                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6628
6629   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(Op, Subtarget, DAG);
6630   if (BlendOp.getNode())
6631     return BlendOp;
6632
6633   if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6634     SmallVector<SDValue, 8> permclMask;
6635     for (unsigned i = 0; i != 8; ++i) {
6636       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6637     }
6638     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6639                                &permclMask[0], 8);
6640     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6641     return DAG.getNode(X86ISD::VPERMV, dl, VT,
6642                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6643   }
6644
6645   if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6646     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6647                                 getShuffleCLImmediate(SVOp), DAG);
6648
6649
6650   //===--------------------------------------------------------------------===//
6651   // Since no target specific shuffle was selected for this generic one,
6652   // lower it into other known shuffles. FIXME: this isn't true yet, but
6653   // this is the plan.
6654   //
6655
6656   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6657   if (VT == MVT::v8i16) {
6658     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6659     if (NewOp.getNode())
6660       return NewOp;
6661   }
6662
6663   if (VT == MVT::v16i8) {
6664     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6665     if (NewOp.getNode())
6666       return NewOp;
6667   }
6668
6669   // Handle all 128-bit wide vectors with 4 elements, and match them with
6670   // several different shuffle types.
6671   if (NumElems == 4 && VT.getSizeInBits() == 128)
6672     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6673
6674   // Handle general 256-bit shuffles
6675   if (VT.is256BitVector())
6676     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6677
6678   return SDValue();
6679 }
6680
6681 SDValue
6682 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6683                                                 SelectionDAG &DAG) const {
6684   EVT VT = Op.getValueType();
6685   DebugLoc dl = Op.getDebugLoc();
6686
6687   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6688     return SDValue();
6689
6690   if (VT.getSizeInBits() == 8) {
6691     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6692                                     Op.getOperand(0), Op.getOperand(1));
6693     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6694                                     DAG.getValueType(VT));
6695     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6696   } else if (VT.getSizeInBits() == 16) {
6697     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6698     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6699     if (Idx == 0)
6700       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6701                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6702                                      DAG.getNode(ISD::BITCAST, dl,
6703                                                  MVT::v4i32,
6704                                                  Op.getOperand(0)),
6705                                      Op.getOperand(1)));
6706     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6707                                     Op.getOperand(0), Op.getOperand(1));
6708     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6709                                     DAG.getValueType(VT));
6710     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6711   } else if (VT == MVT::f32) {
6712     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6713     // the result back to FR32 register. It's only worth matching if the
6714     // result has a single use which is a store or a bitcast to i32.  And in
6715     // the case of a store, it's not worth it if the index is a constant 0,
6716     // because a MOVSSmr can be used instead, which is smaller and faster.
6717     if (!Op.hasOneUse())
6718       return SDValue();
6719     SDNode *User = *Op.getNode()->use_begin();
6720     if ((User->getOpcode() != ISD::STORE ||
6721          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6722           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6723         (User->getOpcode() != ISD::BITCAST ||
6724          User->getValueType(0) != MVT::i32))
6725       return SDValue();
6726     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6727                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6728                                               Op.getOperand(0)),
6729                                               Op.getOperand(1));
6730     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6731   } else if (VT == MVT::i32 || VT == MVT::i64) {
6732     // ExtractPS/pextrq works with constant index.
6733     if (isa<ConstantSDNode>(Op.getOperand(1)))
6734       return Op;
6735   }
6736   return SDValue();
6737 }
6738
6739
6740 SDValue
6741 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6742                                            SelectionDAG &DAG) const {
6743   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6744     return SDValue();
6745
6746   SDValue Vec = Op.getOperand(0);
6747   EVT VecVT = Vec.getValueType();
6748
6749   // If this is a 256-bit vector result, first extract the 128-bit vector and
6750   // then extract the element from the 128-bit vector.
6751   if (VecVT.getSizeInBits() == 256) {
6752     DebugLoc dl = Op.getNode()->getDebugLoc();
6753     unsigned NumElems = VecVT.getVectorNumElements();
6754     SDValue Idx = Op.getOperand(1);
6755     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6756
6757     // Get the 128-bit vector.
6758     bool Upper = IdxVal >= NumElems/2;
6759     Vec = Extract128BitVector(Vec, Upper ? NumElems/2 : 0, DAG, dl);
6760
6761     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6762                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6763   }
6764
6765   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6766
6767   if (Subtarget->hasSSE41()) {
6768     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6769     if (Res.getNode())
6770       return Res;
6771   }
6772
6773   EVT VT = Op.getValueType();
6774   DebugLoc dl = Op.getDebugLoc();
6775   // TODO: handle v16i8.
6776   if (VT.getSizeInBits() == 16) {
6777     SDValue Vec = Op.getOperand(0);
6778     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6779     if (Idx == 0)
6780       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6781                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6782                                      DAG.getNode(ISD::BITCAST, dl,
6783                                                  MVT::v4i32, Vec),
6784                                      Op.getOperand(1)));
6785     // Transform it so it match pextrw which produces a 32-bit result.
6786     EVT EltVT = MVT::i32;
6787     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6788                                     Op.getOperand(0), Op.getOperand(1));
6789     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6790                                     DAG.getValueType(VT));
6791     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6792   } else if (VT.getSizeInBits() == 32) {
6793     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6794     if (Idx == 0)
6795       return Op;
6796
6797     // SHUFPS the element to the lowest double word, then movss.
6798     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6799     EVT VVT = Op.getOperand(0).getValueType();
6800     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6801                                        DAG.getUNDEF(VVT), Mask);
6802     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6803                        DAG.getIntPtrConstant(0));
6804   } else if (VT.getSizeInBits() == 64) {
6805     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6806     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6807     //        to match extract_elt for f64.
6808     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6809     if (Idx == 0)
6810       return Op;
6811
6812     // UNPCKHPD the element to the lowest double word, then movsd.
6813     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6814     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6815     int Mask[2] = { 1, -1 };
6816     EVT VVT = Op.getOperand(0).getValueType();
6817     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6818                                        DAG.getUNDEF(VVT), Mask);
6819     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6820                        DAG.getIntPtrConstant(0));
6821   }
6822
6823   return SDValue();
6824 }
6825
6826 SDValue
6827 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6828                                                SelectionDAG &DAG) const {
6829   EVT VT = Op.getValueType();
6830   EVT EltVT = VT.getVectorElementType();
6831   DebugLoc dl = Op.getDebugLoc();
6832
6833   SDValue N0 = Op.getOperand(0);
6834   SDValue N1 = Op.getOperand(1);
6835   SDValue N2 = Op.getOperand(2);
6836
6837   if (VT.getSizeInBits() == 256)
6838     return SDValue();
6839
6840   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6841       isa<ConstantSDNode>(N2)) {
6842     unsigned Opc;
6843     if (VT == MVT::v8i16)
6844       Opc = X86ISD::PINSRW;
6845     else if (VT == MVT::v16i8)
6846       Opc = X86ISD::PINSRB;
6847     else
6848       Opc = X86ISD::PINSRB;
6849
6850     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6851     // argument.
6852     if (N1.getValueType() != MVT::i32)
6853       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6854     if (N2.getValueType() != MVT::i32)
6855       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6856     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6857   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6858     // Bits [7:6] of the constant are the source select.  This will always be
6859     //  zero here.  The DAG Combiner may combine an extract_elt index into these
6860     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
6861     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
6862     // Bits [5:4] of the constant are the destination select.  This is the
6863     //  value of the incoming immediate.
6864     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
6865     //   combine either bitwise AND or insert of float 0.0 to set these bits.
6866     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6867     // Create this as a scalar to vector..
6868     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6869     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6870   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
6871              isa<ConstantSDNode>(N2)) {
6872     // PINSR* works with constant index.
6873     return Op;
6874   }
6875   return SDValue();
6876 }
6877
6878 SDValue
6879 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6880   EVT VT = Op.getValueType();
6881   EVT EltVT = VT.getVectorElementType();
6882
6883   DebugLoc dl = Op.getDebugLoc();
6884   SDValue N0 = Op.getOperand(0);
6885   SDValue N1 = Op.getOperand(1);
6886   SDValue N2 = Op.getOperand(2);
6887
6888   // If this is a 256-bit vector result, first extract the 128-bit vector,
6889   // insert the element into the extracted half and then place it back.
6890   if (VT.getSizeInBits() == 256) {
6891     if (!isa<ConstantSDNode>(N2))
6892       return SDValue();
6893
6894     // Get the desired 128-bit vector half.
6895     unsigned NumElems = VT.getVectorNumElements();
6896     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6897     bool Upper = IdxVal >= NumElems/2;
6898     unsigned Ins128Idx = Upper ? NumElems/2 : 0;
6899     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
6900
6901     // Insert the element into the desired half.
6902     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
6903                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
6904
6905     // Insert the changed part back to the 256-bit vector
6906     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
6907   }
6908
6909   if (Subtarget->hasSSE41())
6910     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6911
6912   if (EltVT == MVT::i8)
6913     return SDValue();
6914
6915   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6916     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6917     // as its second argument.
6918     if (N1.getValueType() != MVT::i32)
6919       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6920     if (N2.getValueType() != MVT::i32)
6921       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6922     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6923   }
6924   return SDValue();
6925 }
6926
6927 SDValue
6928 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6929   LLVMContext *Context = DAG.getContext();
6930   DebugLoc dl = Op.getDebugLoc();
6931   EVT OpVT = Op.getValueType();
6932
6933   // If this is a 256-bit vector result, first insert into a 128-bit
6934   // vector and then insert into the 256-bit vector.
6935   if (OpVT.getSizeInBits() > 128) {
6936     // Insert into a 128-bit vector.
6937     EVT VT128 = EVT::getVectorVT(*Context,
6938                                  OpVT.getVectorElementType(),
6939                                  OpVT.getVectorNumElements() / 2);
6940
6941     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6942
6943     // Insert the 128-bit vector.
6944     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
6945   }
6946
6947   if (Op.getValueType() == MVT::v1i64 &&
6948       Op.getOperand(0).getValueType() == MVT::i64)
6949     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
6950
6951   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
6952   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
6953          "Expected an SSE type!");
6954   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
6955                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
6956 }
6957
6958 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
6959 // a simple subregister reference or explicit instructions to grab
6960 // upper bits of a vector.
6961 SDValue
6962 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6963   if (Subtarget->hasAVX()) {
6964     DebugLoc dl = Op.getNode()->getDebugLoc();
6965     SDValue Vec = Op.getNode()->getOperand(0);
6966     SDValue Idx = Op.getNode()->getOperand(1);
6967
6968     if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
6969         Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
6970         isa<ConstantSDNode>(Idx)) {
6971       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6972       return Extract128BitVector(Vec, IdxVal, DAG, dl);
6973     }
6974   }
6975   return SDValue();
6976 }
6977
6978 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
6979 // simple superregister reference or explicit instructions to insert
6980 // the upper bits of a vector.
6981 SDValue
6982 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
6983   if (Subtarget->hasAVX()) {
6984     DebugLoc dl = Op.getNode()->getDebugLoc();
6985     SDValue Vec = Op.getNode()->getOperand(0);
6986     SDValue SubVec = Op.getNode()->getOperand(1);
6987     SDValue Idx = Op.getNode()->getOperand(2);
6988
6989     if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
6990         SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
6991         isa<ConstantSDNode>(Idx)) {
6992       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6993       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
6994     }
6995   }
6996   return SDValue();
6997 }
6998
6999 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7000 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7001 // one of the above mentioned nodes. It has to be wrapped because otherwise
7002 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7003 // be used to form addressing mode. These wrapped nodes will be selected
7004 // into MOV32ri.
7005 SDValue
7006 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7007   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7008
7009   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7010   // global base reg.
7011   unsigned char OpFlag = 0;
7012   unsigned WrapperKind = X86ISD::Wrapper;
7013   CodeModel::Model M = getTargetMachine().getCodeModel();
7014
7015   if (Subtarget->isPICStyleRIPRel() &&
7016       (M == CodeModel::Small || M == CodeModel::Kernel))
7017     WrapperKind = X86ISD::WrapperRIP;
7018   else if (Subtarget->isPICStyleGOT())
7019     OpFlag = X86II::MO_GOTOFF;
7020   else if (Subtarget->isPICStyleStubPIC())
7021     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7022
7023   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7024                                              CP->getAlignment(),
7025                                              CP->getOffset(), OpFlag);
7026   DebugLoc DL = CP->getDebugLoc();
7027   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7028   // With PIC, the address is actually $g + Offset.
7029   if (OpFlag) {
7030     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7031                          DAG.getNode(X86ISD::GlobalBaseReg,
7032                                      DebugLoc(), getPointerTy()),
7033                          Result);
7034   }
7035
7036   return Result;
7037 }
7038
7039 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7040   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7041
7042   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7043   // global base reg.
7044   unsigned char OpFlag = 0;
7045   unsigned WrapperKind = X86ISD::Wrapper;
7046   CodeModel::Model M = getTargetMachine().getCodeModel();
7047
7048   if (Subtarget->isPICStyleRIPRel() &&
7049       (M == CodeModel::Small || M == CodeModel::Kernel))
7050     WrapperKind = X86ISD::WrapperRIP;
7051   else if (Subtarget->isPICStyleGOT())
7052     OpFlag = X86II::MO_GOTOFF;
7053   else if (Subtarget->isPICStyleStubPIC())
7054     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7055
7056   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7057                                           OpFlag);
7058   DebugLoc DL = JT->getDebugLoc();
7059   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7060
7061   // With PIC, the address is actually $g + Offset.
7062   if (OpFlag)
7063     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7064                          DAG.getNode(X86ISD::GlobalBaseReg,
7065                                      DebugLoc(), getPointerTy()),
7066                          Result);
7067
7068   return Result;
7069 }
7070
7071 SDValue
7072 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7073   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7074
7075   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7076   // global base reg.
7077   unsigned char OpFlag = 0;
7078   unsigned WrapperKind = X86ISD::Wrapper;
7079   CodeModel::Model M = getTargetMachine().getCodeModel();
7080
7081   if (Subtarget->isPICStyleRIPRel() &&
7082       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7083     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7084       OpFlag = X86II::MO_GOTPCREL;
7085     WrapperKind = X86ISD::WrapperRIP;
7086   } else if (Subtarget->isPICStyleGOT()) {
7087     OpFlag = X86II::MO_GOT;
7088   } else if (Subtarget->isPICStyleStubPIC()) {
7089     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7090   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7091     OpFlag = X86II::MO_DARWIN_NONLAZY;
7092   }
7093
7094   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7095
7096   DebugLoc DL = Op.getDebugLoc();
7097   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7098
7099
7100   // With PIC, the address is actually $g + Offset.
7101   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7102       !Subtarget->is64Bit()) {
7103     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7104                          DAG.getNode(X86ISD::GlobalBaseReg,
7105                                      DebugLoc(), getPointerTy()),
7106                          Result);
7107   }
7108
7109   // For symbols that require a load from a stub to get the address, emit the
7110   // load.
7111   if (isGlobalStubReference(OpFlag))
7112     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7113                          MachinePointerInfo::getGOT(), false, false, false, 0);
7114
7115   return Result;
7116 }
7117
7118 SDValue
7119 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7120   // Create the TargetBlockAddressAddress node.
7121   unsigned char OpFlags =
7122     Subtarget->ClassifyBlockAddressReference();
7123   CodeModel::Model M = getTargetMachine().getCodeModel();
7124   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7125   DebugLoc dl = Op.getDebugLoc();
7126   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7127                                        /*isTarget=*/true, OpFlags);
7128
7129   if (Subtarget->isPICStyleRIPRel() &&
7130       (M == CodeModel::Small || M == CodeModel::Kernel))
7131     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7132   else
7133     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7134
7135   // With PIC, the address is actually $g + Offset.
7136   if (isGlobalRelativeToPICBase(OpFlags)) {
7137     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7138                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7139                          Result);
7140   }
7141
7142   return Result;
7143 }
7144
7145 SDValue
7146 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7147                                       int64_t Offset,
7148                                       SelectionDAG &DAG) const {
7149   // Create the TargetGlobalAddress node, folding in the constant
7150   // offset if it is legal.
7151   unsigned char OpFlags =
7152     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7153   CodeModel::Model M = getTargetMachine().getCodeModel();
7154   SDValue Result;
7155   if (OpFlags == X86II::MO_NO_FLAG &&
7156       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7157     // A direct static reference to a global.
7158     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7159     Offset = 0;
7160   } else {
7161     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7162   }
7163
7164   if (Subtarget->isPICStyleRIPRel() &&
7165       (M == CodeModel::Small || M == CodeModel::Kernel))
7166     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7167   else
7168     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7169
7170   // With PIC, the address is actually $g + Offset.
7171   if (isGlobalRelativeToPICBase(OpFlags)) {
7172     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7173                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7174                          Result);
7175   }
7176
7177   // For globals that require a load from a stub to get the address, emit the
7178   // load.
7179   if (isGlobalStubReference(OpFlags))
7180     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7181                          MachinePointerInfo::getGOT(), false, false, false, 0);
7182
7183   // If there was a non-zero offset that we didn't fold, create an explicit
7184   // addition for it.
7185   if (Offset != 0)
7186     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7187                          DAG.getConstant(Offset, getPointerTy()));
7188
7189   return Result;
7190 }
7191
7192 SDValue
7193 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7194   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7195   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7196   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7197 }
7198
7199 static SDValue
7200 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7201            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7202            unsigned char OperandFlags) {
7203   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7204   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7205   DebugLoc dl = GA->getDebugLoc();
7206   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7207                                            GA->getValueType(0),
7208                                            GA->getOffset(),
7209                                            OperandFlags);
7210   if (InFlag) {
7211     SDValue Ops[] = { Chain,  TGA, *InFlag };
7212     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7213   } else {
7214     SDValue Ops[]  = { Chain, TGA };
7215     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7216   }
7217
7218   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7219   MFI->setAdjustsStack(true);
7220
7221   SDValue Flag = Chain.getValue(1);
7222   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7223 }
7224
7225 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7226 static SDValue
7227 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7228                                 const EVT PtrVT) {
7229   SDValue InFlag;
7230   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7231   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7232                                      DAG.getNode(X86ISD::GlobalBaseReg,
7233                                                  DebugLoc(), PtrVT), InFlag);
7234   InFlag = Chain.getValue(1);
7235
7236   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7237 }
7238
7239 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7240 static SDValue
7241 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7242                                 const EVT PtrVT) {
7243   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7244                     X86::RAX, X86II::MO_TLSGD);
7245 }
7246
7247 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7248 // "local exec" model.
7249 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7250                                    const EVT PtrVT, TLSModel::Model model,
7251                                    bool is64Bit) {
7252   DebugLoc dl = GA->getDebugLoc();
7253
7254   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7255   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7256                                                          is64Bit ? 257 : 256));
7257
7258   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7259                                       DAG.getIntPtrConstant(0),
7260                                       MachinePointerInfo(Ptr),
7261                                       false, false, false, 0);
7262
7263   unsigned char OperandFlags = 0;
7264   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7265   // initialexec.
7266   unsigned WrapperKind = X86ISD::Wrapper;
7267   if (model == TLSModel::LocalExec) {
7268     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7269   } else if (is64Bit) {
7270     assert(model == TLSModel::InitialExec);
7271     OperandFlags = X86II::MO_GOTTPOFF;
7272     WrapperKind = X86ISD::WrapperRIP;
7273   } else {
7274     assert(model == TLSModel::InitialExec);
7275     OperandFlags = X86II::MO_INDNTPOFF;
7276   }
7277
7278   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7279   // exec)
7280   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7281                                            GA->getValueType(0),
7282                                            GA->getOffset(), OperandFlags);
7283   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7284
7285   if (model == TLSModel::InitialExec)
7286     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7287                          MachinePointerInfo::getGOT(), false, false, false, 0);
7288
7289   // The address of the thread local variable is the add of the thread
7290   // pointer with the offset of the variable.
7291   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7292 }
7293
7294 SDValue
7295 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7296
7297   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7298   const GlobalValue *GV = GA->getGlobal();
7299
7300   if (Subtarget->isTargetELF()) {
7301     // TODO: implement the "local dynamic" model
7302     // TODO: implement the "initial exec"model for pic executables
7303
7304     // If GV is an alias then use the aliasee for determining
7305     // thread-localness.
7306     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7307       GV = GA->resolveAliasedGlobal(false);
7308
7309     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7310
7311     switch (model) {
7312       case TLSModel::GeneralDynamic:
7313       case TLSModel::LocalDynamic: // not implemented
7314         if (Subtarget->is64Bit())
7315           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7316         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7317
7318       case TLSModel::InitialExec:
7319       case TLSModel::LocalExec:
7320         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7321                                    Subtarget->is64Bit());
7322     }
7323     llvm_unreachable("Unknown TLS model.");
7324   }
7325
7326   if (Subtarget->isTargetDarwin()) {
7327     // Darwin only has one model of TLS.  Lower to that.
7328     unsigned char OpFlag = 0;
7329     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7330                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7331
7332     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7333     // global base reg.
7334     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7335                   !Subtarget->is64Bit();
7336     if (PIC32)
7337       OpFlag = X86II::MO_TLVP_PIC_BASE;
7338     else
7339       OpFlag = X86II::MO_TLVP;
7340     DebugLoc DL = Op.getDebugLoc();
7341     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7342                                                 GA->getValueType(0),
7343                                                 GA->getOffset(), OpFlag);
7344     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7345
7346     // With PIC32, the address is actually $g + Offset.
7347     if (PIC32)
7348       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7349                            DAG.getNode(X86ISD::GlobalBaseReg,
7350                                        DebugLoc(), getPointerTy()),
7351                            Offset);
7352
7353     // Lowering the machine isd will make sure everything is in the right
7354     // location.
7355     SDValue Chain = DAG.getEntryNode();
7356     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7357     SDValue Args[] = { Chain, Offset };
7358     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7359
7360     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7361     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7362     MFI->setAdjustsStack(true);
7363
7364     // And our return value (tls address) is in the standard call return value
7365     // location.
7366     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7367     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7368                               Chain.getValue(1));
7369   }
7370
7371   if (Subtarget->isTargetWindows()) {
7372     // Just use the implicit TLS architecture
7373     // Need to generate someting similar to:
7374     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7375     //                                  ; from TEB
7376     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7377     //   mov     rcx, qword [rdx+rcx*8]
7378     //   mov     eax, .tls$:tlsvar
7379     //   [rax+rcx] contains the address
7380     // Windows 64bit: gs:0x58
7381     // Windows 32bit: fs:__tls_array
7382
7383     // If GV is an alias then use the aliasee for determining
7384     // thread-localness.
7385     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7386       GV = GA->resolveAliasedGlobal(false);
7387     DebugLoc dl = GA->getDebugLoc();
7388     SDValue Chain = DAG.getEntryNode();
7389
7390     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7391     // %gs:0x58 (64-bit).
7392     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7393                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7394                                                              256)
7395                                         : Type::getInt32PtrTy(*DAG.getContext(),
7396                                                               257));
7397
7398     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7399                                         Subtarget->is64Bit()
7400                                         ? DAG.getIntPtrConstant(0x58)
7401                                         : DAG.getExternalSymbol("_tls_array",
7402                                                                 getPointerTy()),
7403                                         MachinePointerInfo(Ptr),
7404                                         false, false, false, 0);
7405
7406     // Load the _tls_index variable
7407     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7408     if (Subtarget->is64Bit())
7409       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7410                            IDX, MachinePointerInfo(), MVT::i32,
7411                            false, false, 0);
7412     else
7413       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7414                         false, false, false, 0);
7415
7416     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7417                                     getPointerTy());
7418     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7419
7420     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7421     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7422                       false, false, false, 0);
7423
7424     // Get the offset of start of .tls section
7425     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7426                                              GA->getValueType(0),
7427                                              GA->getOffset(), X86II::MO_SECREL);
7428     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7429
7430     // The address of the thread local variable is the add of the thread
7431     // pointer with the offset of the variable.
7432     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7433   }
7434
7435   llvm_unreachable("TLS not implemented for this target.");
7436 }
7437
7438
7439 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7440 /// and take a 2 x i32 value to shift plus a shift amount.
7441 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7442   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7443   EVT VT = Op.getValueType();
7444   unsigned VTBits = VT.getSizeInBits();
7445   DebugLoc dl = Op.getDebugLoc();
7446   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7447   SDValue ShOpLo = Op.getOperand(0);
7448   SDValue ShOpHi = Op.getOperand(1);
7449   SDValue ShAmt  = Op.getOperand(2);
7450   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7451                                      DAG.getConstant(VTBits - 1, MVT::i8))
7452                        : DAG.getConstant(0, VT);
7453
7454   SDValue Tmp2, Tmp3;
7455   if (Op.getOpcode() == ISD::SHL_PARTS) {
7456     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7457     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7458   } else {
7459     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7460     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7461   }
7462
7463   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7464                                 DAG.getConstant(VTBits, MVT::i8));
7465   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7466                              AndNode, DAG.getConstant(0, MVT::i8));
7467
7468   SDValue Hi, Lo;
7469   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7470   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7471   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7472
7473   if (Op.getOpcode() == ISD::SHL_PARTS) {
7474     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7475     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7476   } else {
7477     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7478     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7479   }
7480
7481   SDValue Ops[2] = { Lo, Hi };
7482   return DAG.getMergeValues(Ops, 2, dl);
7483 }
7484
7485 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7486                                            SelectionDAG &DAG) const {
7487   EVT SrcVT = Op.getOperand(0).getValueType();
7488
7489   if (SrcVT.isVector())
7490     return SDValue();
7491
7492   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7493          "Unknown SINT_TO_FP to lower!");
7494
7495   // These are really Legal; return the operand so the caller accepts it as
7496   // Legal.
7497   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7498     return Op;
7499   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7500       Subtarget->is64Bit()) {
7501     return Op;
7502   }
7503
7504   DebugLoc dl = Op.getDebugLoc();
7505   unsigned Size = SrcVT.getSizeInBits()/8;
7506   MachineFunction &MF = DAG.getMachineFunction();
7507   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7508   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7509   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7510                                StackSlot,
7511                                MachinePointerInfo::getFixedStack(SSFI),
7512                                false, false, 0);
7513   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7514 }
7515
7516 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7517                                      SDValue StackSlot,
7518                                      SelectionDAG &DAG) const {
7519   // Build the FILD
7520   DebugLoc DL = Op.getDebugLoc();
7521   SDVTList Tys;
7522   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7523   if (useSSE)
7524     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7525   else
7526     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7527
7528   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7529
7530   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7531   MachineMemOperand *MMO;
7532   if (FI) {
7533     int SSFI = FI->getIndex();
7534     MMO =
7535       DAG.getMachineFunction()
7536       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7537                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7538   } else {
7539     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7540     StackSlot = StackSlot.getOperand(1);
7541   }
7542   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7543   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7544                                            X86ISD::FILD, DL,
7545                                            Tys, Ops, array_lengthof(Ops),
7546                                            SrcVT, MMO);
7547
7548   if (useSSE) {
7549     Chain = Result.getValue(1);
7550     SDValue InFlag = Result.getValue(2);
7551
7552     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7553     // shouldn't be necessary except that RFP cannot be live across
7554     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7555     MachineFunction &MF = DAG.getMachineFunction();
7556     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7557     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7558     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7559     Tys = DAG.getVTList(MVT::Other);
7560     SDValue Ops[] = {
7561       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7562     };
7563     MachineMemOperand *MMO =
7564       DAG.getMachineFunction()
7565       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7566                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7567
7568     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7569                                     Ops, array_lengthof(Ops),
7570                                     Op.getValueType(), MMO);
7571     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7572                          MachinePointerInfo::getFixedStack(SSFI),
7573                          false, false, false, 0);
7574   }
7575
7576   return Result;
7577 }
7578
7579 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7580 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7581                                                SelectionDAG &DAG) const {
7582   // This algorithm is not obvious. Here it is what we're trying to output:
7583   /*
7584      movq       %rax,  %xmm0
7585      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7586      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7587      #ifdef __SSE3__
7588        haddpd   %xmm0, %xmm0          
7589      #else
7590        pshufd   $0x4e, %xmm0, %xmm1 
7591        addpd    %xmm1, %xmm0
7592      #endif
7593   */
7594
7595   DebugLoc dl = Op.getDebugLoc();
7596   LLVMContext *Context = DAG.getContext();
7597
7598   // Build some magic constants.
7599   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7600   Constant *C0 = ConstantDataVector::get(*Context, CV0);
7601   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7602
7603   SmallVector<Constant*,2> CV1;
7604   CV1.push_back(
7605         ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7606   CV1.push_back(
7607         ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7608   Constant *C1 = ConstantVector::get(CV1);
7609   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7610
7611   // Load the 64-bit value into an XMM register.
7612   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7613                             Op.getOperand(0));
7614   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7615                               MachinePointerInfo::getConstantPool(),
7616                               false, false, false, 16);
7617   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7618                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7619                               CLod0);
7620
7621   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7622                               MachinePointerInfo::getConstantPool(),
7623                               false, false, false, 16);
7624   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7625   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7626   SDValue Result;
7627
7628   if (Subtarget->hasSSE3()) {
7629     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7630     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7631   } else {
7632     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7633     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7634                                            S2F, 0x4E, DAG);
7635     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7636                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7637                          Sub);
7638   }
7639
7640   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7641                      DAG.getIntPtrConstant(0));
7642 }
7643
7644 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7645 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7646                                                SelectionDAG &DAG) const {
7647   DebugLoc dl = Op.getDebugLoc();
7648   // FP constant to bias correct the final result.
7649   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7650                                    MVT::f64);
7651
7652   // Load the 32-bit value into an XMM register.
7653   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7654                              Op.getOperand(0));
7655
7656   // Zero out the upper parts of the register.
7657   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7658
7659   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7660                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7661                      DAG.getIntPtrConstant(0));
7662
7663   // Or the load with the bias.
7664   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7665                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7666                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7667                                                    MVT::v2f64, Load)),
7668                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7669                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7670                                                    MVT::v2f64, Bias)));
7671   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7672                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7673                    DAG.getIntPtrConstant(0));
7674
7675   // Subtract the bias.
7676   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7677
7678   // Handle final rounding.
7679   EVT DestVT = Op.getValueType();
7680
7681   if (DestVT.bitsLT(MVT::f64)) {
7682     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7683                        DAG.getIntPtrConstant(0));
7684   } else if (DestVT.bitsGT(MVT::f64)) {
7685     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7686   }
7687
7688   // Handle final rounding.
7689   return Sub;
7690 }
7691
7692 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7693                                            SelectionDAG &DAG) const {
7694   SDValue N0 = Op.getOperand(0);
7695   DebugLoc dl = Op.getDebugLoc();
7696
7697   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7698   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7699   // the optimization here.
7700   if (DAG.SignBitIsZero(N0))
7701     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7702
7703   EVT SrcVT = N0.getValueType();
7704   EVT DstVT = Op.getValueType();
7705   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7706     return LowerUINT_TO_FP_i64(Op, DAG);
7707   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7708     return LowerUINT_TO_FP_i32(Op, DAG);
7709   else if (Subtarget->is64Bit() &&
7710            SrcVT == MVT::i64 && DstVT == MVT::f32)
7711     return SDValue();
7712
7713   // Make a 64-bit buffer, and use it to build an FILD.
7714   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7715   if (SrcVT == MVT::i32) {
7716     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7717     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7718                                      getPointerTy(), StackSlot, WordOff);
7719     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7720                                   StackSlot, MachinePointerInfo(),
7721                                   false, false, 0);
7722     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7723                                   OffsetSlot, MachinePointerInfo(),
7724                                   false, false, 0);
7725     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7726     return Fild;
7727   }
7728
7729   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7730   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7731                                StackSlot, MachinePointerInfo(),
7732                                false, false, 0);
7733   // For i64 source, we need to add the appropriate power of 2 if the input
7734   // was negative.  This is the same as the optimization in
7735   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7736   // we must be careful to do the computation in x87 extended precision, not
7737   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7738   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7739   MachineMemOperand *MMO =
7740     DAG.getMachineFunction()
7741     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7742                           MachineMemOperand::MOLoad, 8, 8);
7743
7744   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7745   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7746   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7747                                          MVT::i64, MMO);
7748
7749   APInt FF(32, 0x5F800000ULL);
7750
7751   // Check whether the sign bit is set.
7752   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7753                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7754                                  ISD::SETLT);
7755
7756   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7757   SDValue FudgePtr = DAG.getConstantPool(
7758                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7759                                          getPointerTy());
7760
7761   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7762   SDValue Zero = DAG.getIntPtrConstant(0);
7763   SDValue Four = DAG.getIntPtrConstant(4);
7764   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7765                                Zero, Four);
7766   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7767
7768   // Load the value out, extending it from f32 to f80.
7769   // FIXME: Avoid the extend by constructing the right constant pool?
7770   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7771                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7772                                  MVT::f32, false, false, 4);
7773   // Extend everything to 80 bits to force it to be done on x87.
7774   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7775   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7776 }
7777
7778 std::pair<SDValue,SDValue> X86TargetLowering::
7779 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7780   DebugLoc DL = Op.getDebugLoc();
7781
7782   EVT DstTy = Op.getValueType();
7783
7784   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7785     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7786     DstTy = MVT::i64;
7787   }
7788
7789   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7790          DstTy.getSimpleVT() >= MVT::i16 &&
7791          "Unknown FP_TO_INT to lower!");
7792
7793   // These are really Legal.
7794   if (DstTy == MVT::i32 &&
7795       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7796     return std::make_pair(SDValue(), SDValue());
7797   if (Subtarget->is64Bit() &&
7798       DstTy == MVT::i64 &&
7799       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7800     return std::make_pair(SDValue(), SDValue());
7801
7802   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7803   // stack slot, or into the FTOL runtime function.
7804   MachineFunction &MF = DAG.getMachineFunction();
7805   unsigned MemSize = DstTy.getSizeInBits()/8;
7806   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7807   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7808
7809   unsigned Opc;
7810   if (!IsSigned && isIntegerTypeFTOL(DstTy))
7811     Opc = X86ISD::WIN_FTOL;
7812   else
7813     switch (DstTy.getSimpleVT().SimpleTy) {
7814     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7815     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7816     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7817     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7818     }
7819
7820   SDValue Chain = DAG.getEntryNode();
7821   SDValue Value = Op.getOperand(0);
7822   EVT TheVT = Op.getOperand(0).getValueType();
7823   // FIXME This causes a redundant load/store if the SSE-class value is already
7824   // in memory, such as if it is on the callstack.
7825   if (isScalarFPTypeInSSEReg(TheVT)) {
7826     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7827     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7828                          MachinePointerInfo::getFixedStack(SSFI),
7829                          false, false, 0);
7830     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7831     SDValue Ops[] = {
7832       Chain, StackSlot, DAG.getValueType(TheVT)
7833     };
7834
7835     MachineMemOperand *MMO =
7836       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7837                               MachineMemOperand::MOLoad, MemSize, MemSize);
7838     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7839                                     DstTy, MMO);
7840     Chain = Value.getValue(1);
7841     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7842     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7843   }
7844
7845   MachineMemOperand *MMO =
7846     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7847                             MachineMemOperand::MOStore, MemSize, MemSize);
7848
7849   if (Opc != X86ISD::WIN_FTOL) {
7850     // Build the FP_TO_INT*_IN_MEM
7851     SDValue Ops[] = { Chain, Value, StackSlot };
7852     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7853                                            Ops, 3, DstTy, MMO);
7854     return std::make_pair(FIST, StackSlot);
7855   } else {
7856     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7857       DAG.getVTList(MVT::Other, MVT::Glue),
7858       Chain, Value);
7859     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7860       MVT::i32, ftol.getValue(1));
7861     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7862       MVT::i32, eax.getValue(2));
7863     SDValue Ops[] = { eax, edx };
7864     SDValue pair = IsReplace
7865       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7866       : DAG.getMergeValues(Ops, 2, DL);
7867     return std::make_pair(pair, SDValue());
7868   }
7869 }
7870
7871 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7872                                            SelectionDAG &DAG) const {
7873   if (Op.getValueType().isVector())
7874     return SDValue();
7875
7876   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7877     /*IsSigned=*/ true, /*IsReplace=*/ false);
7878   SDValue FIST = Vals.first, StackSlot = Vals.second;
7879   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7880   if (FIST.getNode() == 0) return Op;
7881
7882   if (StackSlot.getNode())
7883     // Load the result.
7884     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7885                        FIST, StackSlot, MachinePointerInfo(),
7886                        false, false, false, 0);
7887   else
7888     // The node is the result.
7889     return FIST;
7890 }
7891
7892 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7893                                            SelectionDAG &DAG) const {
7894   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7895     /*IsSigned=*/ false, /*IsReplace=*/ false);
7896   SDValue FIST = Vals.first, StackSlot = Vals.second;
7897   assert(FIST.getNode() && "Unexpected failure");
7898
7899   if (StackSlot.getNode())
7900     // Load the result.
7901     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7902                        FIST, StackSlot, MachinePointerInfo(),
7903                        false, false, false, 0);
7904   else
7905     // The node is the result.
7906     return FIST;
7907 }
7908
7909 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7910                                      SelectionDAG &DAG) const {
7911   LLVMContext *Context = DAG.getContext();
7912   DebugLoc dl = Op.getDebugLoc();
7913   EVT VT = Op.getValueType();
7914   EVT EltVT = VT;
7915   if (VT.isVector())
7916     EltVT = VT.getVectorElementType();
7917   Constant *C;
7918   if (EltVT == MVT::f64) {
7919     C = ConstantVector::getSplat(2, 
7920                 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7921   } else {
7922     C = ConstantVector::getSplat(4,
7923                ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7924   }
7925   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7926   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7927                              MachinePointerInfo::getConstantPool(),
7928                              false, false, false, 16);
7929   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7930 }
7931
7932 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7933   LLVMContext *Context = DAG.getContext();
7934   DebugLoc dl = Op.getDebugLoc();
7935   EVT VT = Op.getValueType();
7936   EVT EltVT = VT;
7937   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
7938   if (VT.isVector()) {
7939     EltVT = VT.getVectorElementType();
7940     NumElts = VT.getVectorNumElements();
7941   }
7942   Constant *C;
7943   if (EltVT == MVT::f64)
7944     C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
7945   else
7946     C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
7947   C = ConstantVector::getSplat(NumElts, C);
7948   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7949   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7950                              MachinePointerInfo::getConstantPool(),
7951                              false, false, false, 16);
7952   if (VT.isVector()) {
7953     MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
7954     return DAG.getNode(ISD::BITCAST, dl, VT,
7955                        DAG.getNode(ISD::XOR, dl, XORVT,
7956                     DAG.getNode(ISD::BITCAST, dl, XORVT,
7957                                 Op.getOperand(0)),
7958                     DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
7959   } else {
7960     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
7961   }
7962 }
7963
7964 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
7965   LLVMContext *Context = DAG.getContext();
7966   SDValue Op0 = Op.getOperand(0);
7967   SDValue Op1 = Op.getOperand(1);
7968   DebugLoc dl = Op.getDebugLoc();
7969   EVT VT = Op.getValueType();
7970   EVT SrcVT = Op1.getValueType();
7971
7972   // If second operand is smaller, extend it first.
7973   if (SrcVT.bitsLT(VT)) {
7974     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
7975     SrcVT = VT;
7976   }
7977   // And if it is bigger, shrink it first.
7978   if (SrcVT.bitsGT(VT)) {
7979     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
7980     SrcVT = VT;
7981   }
7982
7983   // At this point the operands and the result should have the same
7984   // type, and that won't be f80 since that is not custom lowered.
7985
7986   // First get the sign bit of second operand.
7987   SmallVector<Constant*,4> CV;
7988   if (SrcVT == MVT::f64) {
7989     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
7990     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
7991   } else {
7992     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
7993     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7994     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7995     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
7996   }
7997   Constant *C = ConstantVector::get(CV);
7998   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7999   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8000                               MachinePointerInfo::getConstantPool(),
8001                               false, false, false, 16);
8002   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8003
8004   // Shift sign bit right or left if the two operands have different types.
8005   if (SrcVT.bitsGT(VT)) {
8006     // Op0 is MVT::f32, Op1 is MVT::f64.
8007     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8008     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8009                           DAG.getConstant(32, MVT::i32));
8010     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8011     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8012                           DAG.getIntPtrConstant(0));
8013   }
8014
8015   // Clear first operand sign bit.
8016   CV.clear();
8017   if (VT == MVT::f64) {
8018     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8019     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8020   } else {
8021     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8022     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8023     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8024     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8025   }
8026   C = ConstantVector::get(CV);
8027   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8028   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8029                               MachinePointerInfo::getConstantPool(),
8030                               false, false, false, 16);
8031   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8032
8033   // Or the value with the sign bit.
8034   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8035 }
8036
8037 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8038   SDValue N0 = Op.getOperand(0);
8039   DebugLoc dl = Op.getDebugLoc();
8040   EVT VT = Op.getValueType();
8041
8042   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8043   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8044                                   DAG.getConstant(1, VT));
8045   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8046 }
8047
8048 /// Emit nodes that will be selected as "test Op0,Op0", or something
8049 /// equivalent.
8050 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8051                                     SelectionDAG &DAG) const {
8052   DebugLoc dl = Op.getDebugLoc();
8053
8054   // CF and OF aren't always set the way we want. Determine which
8055   // of these we need.
8056   bool NeedCF = false;
8057   bool NeedOF = false;
8058   switch (X86CC) {
8059   default: break;
8060   case X86::COND_A: case X86::COND_AE:
8061   case X86::COND_B: case X86::COND_BE:
8062     NeedCF = true;
8063     break;
8064   case X86::COND_G: case X86::COND_GE:
8065   case X86::COND_L: case X86::COND_LE:
8066   case X86::COND_O: case X86::COND_NO:
8067     NeedOF = true;
8068     break;
8069   }
8070
8071   // See if we can use the EFLAGS value from the operand instead of
8072   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8073   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8074   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8075     // Emit a CMP with 0, which is the TEST pattern.
8076     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8077                        DAG.getConstant(0, Op.getValueType()));
8078
8079   unsigned Opcode = 0;
8080   unsigned NumOperands = 0;
8081   switch (Op.getNode()->getOpcode()) {
8082   case ISD::ADD:
8083     // Due to an isel shortcoming, be conservative if this add is likely to be
8084     // selected as part of a load-modify-store instruction. When the root node
8085     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8086     // uses of other nodes in the match, such as the ADD in this case. This
8087     // leads to the ADD being left around and reselected, with the result being
8088     // two adds in the output.  Alas, even if none our users are stores, that
8089     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8090     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8091     // climbing the DAG back to the root, and it doesn't seem to be worth the
8092     // effort.
8093     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8094          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8095       if (UI->getOpcode() != ISD::CopyToReg &&
8096           UI->getOpcode() != ISD::SETCC &&
8097           UI->getOpcode() != ISD::STORE)
8098         goto default_case;
8099
8100     if (ConstantSDNode *C =
8101         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8102       // An add of one will be selected as an INC.
8103       if (C->getAPIntValue() == 1) {
8104         Opcode = X86ISD::INC;
8105         NumOperands = 1;
8106         break;
8107       }
8108
8109       // An add of negative one (subtract of one) will be selected as a DEC.
8110       if (C->getAPIntValue().isAllOnesValue()) {
8111         Opcode = X86ISD::DEC;
8112         NumOperands = 1;
8113         break;
8114       }
8115     }
8116
8117     // Otherwise use a regular EFLAGS-setting add.
8118     Opcode = X86ISD::ADD;
8119     NumOperands = 2;
8120     break;
8121   case ISD::AND: {
8122     // If the primary and result isn't used, don't bother using X86ISD::AND,
8123     // because a TEST instruction will be better.
8124     bool NonFlagUse = false;
8125     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8126            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8127       SDNode *User = *UI;
8128       unsigned UOpNo = UI.getOperandNo();
8129       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8130         // Look pass truncate.
8131         UOpNo = User->use_begin().getOperandNo();
8132         User = *User->use_begin();
8133       }
8134
8135       if (User->getOpcode() != ISD::BRCOND &&
8136           User->getOpcode() != ISD::SETCC &&
8137           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8138         NonFlagUse = true;
8139         break;
8140       }
8141     }
8142
8143     if (!NonFlagUse)
8144       break;
8145   }
8146     // FALL THROUGH
8147   case ISD::SUB:
8148   case ISD::OR:
8149   case ISD::XOR:
8150     // Due to the ISEL shortcoming noted above, be conservative if this op is
8151     // likely to be selected as part of a load-modify-store instruction.
8152     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8153            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8154       if (UI->getOpcode() == ISD::STORE)
8155         goto default_case;
8156
8157     // Otherwise use a regular EFLAGS-setting instruction.
8158     switch (Op.getNode()->getOpcode()) {
8159     default: llvm_unreachable("unexpected operator!");
8160     case ISD::SUB: Opcode = X86ISD::SUB; break;
8161     case ISD::OR:  Opcode = X86ISD::OR;  break;
8162     case ISD::XOR: Opcode = X86ISD::XOR; break;
8163     case ISD::AND: Opcode = X86ISD::AND; break;
8164     }
8165
8166     NumOperands = 2;
8167     break;
8168   case X86ISD::ADD:
8169   case X86ISD::SUB:
8170   case X86ISD::INC:
8171   case X86ISD::DEC:
8172   case X86ISD::OR:
8173   case X86ISD::XOR:
8174   case X86ISD::AND:
8175     return SDValue(Op.getNode(), 1);
8176   default:
8177   default_case:
8178     break;
8179   }
8180
8181   if (Opcode == 0)
8182     // Emit a CMP with 0, which is the TEST pattern.
8183     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8184                        DAG.getConstant(0, Op.getValueType()));
8185
8186   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8187   SmallVector<SDValue, 4> Ops;
8188   for (unsigned i = 0; i != NumOperands; ++i)
8189     Ops.push_back(Op.getOperand(i));
8190
8191   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8192   DAG.ReplaceAllUsesWith(Op, New);
8193   return SDValue(New.getNode(), 1);
8194 }
8195
8196 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8197 /// equivalent.
8198 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8199                                    SelectionDAG &DAG) const {
8200   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8201     if (C->getAPIntValue() == 0)
8202       return EmitTest(Op0, X86CC, DAG);
8203
8204   DebugLoc dl = Op0.getDebugLoc();
8205   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8206 }
8207
8208 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8209 /// if it's possible.
8210 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8211                                      DebugLoc dl, SelectionDAG &DAG) const {
8212   SDValue Op0 = And.getOperand(0);
8213   SDValue Op1 = And.getOperand(1);
8214   if (Op0.getOpcode() == ISD::TRUNCATE)
8215     Op0 = Op0.getOperand(0);
8216   if (Op1.getOpcode() == ISD::TRUNCATE)
8217     Op1 = Op1.getOperand(0);
8218
8219   SDValue LHS, RHS;
8220   if (Op1.getOpcode() == ISD::SHL)
8221     std::swap(Op0, Op1);
8222   if (Op0.getOpcode() == ISD::SHL) {
8223     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8224       if (And00C->getZExtValue() == 1) {
8225         // If we looked past a truncate, check that it's only truncating away
8226         // known zeros.
8227         unsigned BitWidth = Op0.getValueSizeInBits();
8228         unsigned AndBitWidth = And.getValueSizeInBits();
8229         if (BitWidth > AndBitWidth) {
8230           APInt Zeros, Ones;
8231           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8232           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8233             return SDValue();
8234         }
8235         LHS = Op1;
8236         RHS = Op0.getOperand(1);
8237       }
8238   } else if (Op1.getOpcode() == ISD::Constant) {
8239     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8240     uint64_t AndRHSVal = AndRHS->getZExtValue();
8241     SDValue AndLHS = Op0;
8242
8243     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8244       LHS = AndLHS.getOperand(0);
8245       RHS = AndLHS.getOperand(1);
8246     }
8247
8248     // Use BT if the immediate can't be encoded in a TEST instruction.
8249     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8250       LHS = AndLHS;
8251       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8252     }
8253   }
8254
8255   if (LHS.getNode()) {
8256     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8257     // instruction.  Since the shift amount is in-range-or-undefined, we know
8258     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8259     // the encoding for the i16 version is larger than the i32 version.
8260     // Also promote i16 to i32 for performance / code size reason.
8261     if (LHS.getValueType() == MVT::i8 ||
8262         LHS.getValueType() == MVT::i16)
8263       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8264
8265     // If the operand types disagree, extend the shift amount to match.  Since
8266     // BT ignores high bits (like shifts) we can use anyextend.
8267     if (LHS.getValueType() != RHS.getValueType())
8268       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8269
8270     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8271     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8272     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8273                        DAG.getConstant(Cond, MVT::i8), BT);
8274   }
8275
8276   return SDValue();
8277 }
8278
8279 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8280
8281   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8282
8283   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8284   SDValue Op0 = Op.getOperand(0);
8285   SDValue Op1 = Op.getOperand(1);
8286   DebugLoc dl = Op.getDebugLoc();
8287   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8288
8289   // Optimize to BT if possible.
8290   // Lower (X & (1 << N)) == 0 to BT(X, N).
8291   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8292   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8293   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8294       Op1.getOpcode() == ISD::Constant &&
8295       cast<ConstantSDNode>(Op1)->isNullValue() &&
8296       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8297     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8298     if (NewSetCC.getNode())
8299       return NewSetCC;
8300   }
8301
8302   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8303   // these.
8304   if (Op1.getOpcode() == ISD::Constant &&
8305       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8306        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8307       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8308
8309     // If the input is a setcc, then reuse the input setcc or use a new one with
8310     // the inverted condition.
8311     if (Op0.getOpcode() == X86ISD::SETCC) {
8312       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8313       bool Invert = (CC == ISD::SETNE) ^
8314         cast<ConstantSDNode>(Op1)->isNullValue();
8315       if (!Invert) return Op0;
8316
8317       CCode = X86::GetOppositeBranchCondition(CCode);
8318       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8319                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8320     }
8321   }
8322
8323   bool isFP = Op1.getValueType().isFloatingPoint();
8324   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8325   if (X86CC == X86::COND_INVALID)
8326     return SDValue();
8327
8328   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8329   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8330                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8331 }
8332
8333 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8334 // ones, and then concatenate the result back.
8335 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8336   EVT VT = Op.getValueType();
8337
8338   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8339          "Unsupported value type for operation");
8340
8341   int NumElems = VT.getVectorNumElements();
8342   DebugLoc dl = Op.getDebugLoc();
8343   SDValue CC = Op.getOperand(2);
8344
8345   // Extract the LHS vectors
8346   SDValue LHS = Op.getOperand(0);
8347   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8348   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8349
8350   // Extract the RHS vectors
8351   SDValue RHS = Op.getOperand(1);
8352   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8353   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8354
8355   // Issue the operation on the smaller types and concatenate the result back
8356   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8357   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8358   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8359                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8360                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8361 }
8362
8363
8364 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8365   SDValue Cond;
8366   SDValue Op0 = Op.getOperand(0);
8367   SDValue Op1 = Op.getOperand(1);
8368   SDValue CC = Op.getOperand(2);
8369   EVT VT = Op.getValueType();
8370   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8371   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8372   DebugLoc dl = Op.getDebugLoc();
8373
8374   if (isFP) {
8375     unsigned SSECC = 8;
8376     EVT EltVT = Op0.getValueType().getVectorElementType();
8377     assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8378
8379     bool Swap = false;
8380
8381     // SSE Condition code mapping:
8382     //  0 - EQ
8383     //  1 - LT
8384     //  2 - LE
8385     //  3 - UNORD
8386     //  4 - NEQ
8387     //  5 - NLT
8388     //  6 - NLE
8389     //  7 - ORD
8390     switch (SetCCOpcode) {
8391     default: break;
8392     case ISD::SETOEQ:
8393     case ISD::SETEQ:  SSECC = 0; break;
8394     case ISD::SETOGT:
8395     case ISD::SETGT: Swap = true; // Fallthrough
8396     case ISD::SETLT:
8397     case ISD::SETOLT: SSECC = 1; break;
8398     case ISD::SETOGE:
8399     case ISD::SETGE: Swap = true; // Fallthrough
8400     case ISD::SETLE:
8401     case ISD::SETOLE: SSECC = 2; break;
8402     case ISD::SETUO:  SSECC = 3; break;
8403     case ISD::SETUNE:
8404     case ISD::SETNE:  SSECC = 4; break;
8405     case ISD::SETULE: Swap = true;
8406     case ISD::SETUGE: SSECC = 5; break;
8407     case ISD::SETULT: Swap = true;
8408     case ISD::SETUGT: SSECC = 6; break;
8409     case ISD::SETO:   SSECC = 7; break;
8410     }
8411     if (Swap)
8412       std::swap(Op0, Op1);
8413
8414     // In the two special cases we can't handle, emit two comparisons.
8415     if (SSECC == 8) {
8416       if (SetCCOpcode == ISD::SETUEQ) {
8417         SDValue UNORD, EQ;
8418         UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8419                             DAG.getConstant(3, MVT::i8));
8420         EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8421                          DAG.getConstant(0, MVT::i8));
8422         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8423       } else if (SetCCOpcode == ISD::SETONE) {
8424         SDValue ORD, NEQ;
8425         ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8426                           DAG.getConstant(7, MVT::i8));
8427         NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8428                           DAG.getConstant(4, MVT::i8));
8429         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8430       }
8431       llvm_unreachable("Illegal FP comparison");
8432     }
8433     // Handle all other FP comparisons here.
8434     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8435                        DAG.getConstant(SSECC, MVT::i8));
8436   }
8437
8438   // Break 256-bit integer vector compare into smaller ones.
8439   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8440     return Lower256IntVSETCC(Op, DAG);
8441
8442   // We are handling one of the integer comparisons here.  Since SSE only has
8443   // GT and EQ comparisons for integer, swapping operands and multiple
8444   // operations may be required for some comparisons.
8445   unsigned Opc = 0;
8446   bool Swap = false, Invert = false, FlipSigns = false;
8447
8448   switch (SetCCOpcode) {
8449   default: break;
8450   case ISD::SETNE:  Invert = true;
8451   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
8452   case ISD::SETLT:  Swap = true;
8453   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
8454   case ISD::SETGE:  Swap = true;
8455   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
8456   case ISD::SETULT: Swap = true;
8457   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8458   case ISD::SETUGE: Swap = true;
8459   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8460   }
8461   if (Swap)
8462     std::swap(Op0, Op1);
8463
8464   // Check that the operation in question is available (most are plain SSE2,
8465   // but PCMPGTQ and PCMPEQQ have different requirements).
8466   if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8467     return SDValue();
8468   if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8469     return SDValue();
8470
8471   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8472   // bits of the inputs before performing those operations.
8473   if (FlipSigns) {
8474     EVT EltVT = VT.getVectorElementType();
8475     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8476                                       EltVT);
8477     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8478     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8479                                     SignBits.size());
8480     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8481     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8482   }
8483
8484   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8485
8486   // If the logical-not of the result is required, perform that now.
8487   if (Invert)
8488     Result = DAG.getNOT(dl, Result, VT);
8489
8490   return Result;
8491 }
8492
8493 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8494 static bool isX86LogicalCmp(SDValue Op) {
8495   unsigned Opc = Op.getNode()->getOpcode();
8496   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8497     return true;
8498   if (Op.getResNo() == 1 &&
8499       (Opc == X86ISD::ADD ||
8500        Opc == X86ISD::SUB ||
8501        Opc == X86ISD::ADC ||
8502        Opc == X86ISD::SBB ||
8503        Opc == X86ISD::SMUL ||
8504        Opc == X86ISD::UMUL ||
8505        Opc == X86ISD::INC ||
8506        Opc == X86ISD::DEC ||
8507        Opc == X86ISD::OR ||
8508        Opc == X86ISD::XOR ||
8509        Opc == X86ISD::AND))
8510     return true;
8511
8512   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8513     return true;
8514
8515   return false;
8516 }
8517
8518 static bool isZero(SDValue V) {
8519   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8520   return C && C->isNullValue();
8521 }
8522
8523 static bool isAllOnes(SDValue V) {
8524   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8525   return C && C->isAllOnesValue();
8526 }
8527
8528 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8529   bool addTest = true;
8530   SDValue Cond  = Op.getOperand(0);
8531   SDValue Op1 = Op.getOperand(1);
8532   SDValue Op2 = Op.getOperand(2);
8533   DebugLoc DL = Op.getDebugLoc();
8534   SDValue CC;
8535
8536   if (Cond.getOpcode() == ISD::SETCC) {
8537     SDValue NewCond = LowerSETCC(Cond, DAG);
8538     if (NewCond.getNode())
8539       Cond = NewCond;
8540   }
8541
8542   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8543   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8544   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8545   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8546   if (Cond.getOpcode() == X86ISD::SETCC &&
8547       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8548       isZero(Cond.getOperand(1).getOperand(1))) {
8549     SDValue Cmp = Cond.getOperand(1);
8550
8551     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8552
8553     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8554         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8555       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8556
8557       SDValue CmpOp0 = Cmp.getOperand(0);
8558       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8559                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8560
8561       SDValue Res =   // Res = 0 or -1.
8562         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8563                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8564
8565       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8566         Res = DAG.getNOT(DL, Res, Res.getValueType());
8567
8568       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8569       if (N2C == 0 || !N2C->isNullValue())
8570         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8571       return Res;
8572     }
8573   }
8574
8575   // Look past (and (setcc_carry (cmp ...)), 1).
8576   if (Cond.getOpcode() == ISD::AND &&
8577       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8578     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8579     if (C && C->getAPIntValue() == 1)
8580       Cond = Cond.getOperand(0);
8581   }
8582
8583   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8584   // setting operand in place of the X86ISD::SETCC.
8585   unsigned CondOpcode = Cond.getOpcode();
8586   if (CondOpcode == X86ISD::SETCC ||
8587       CondOpcode == X86ISD::SETCC_CARRY) {
8588     CC = Cond.getOperand(0);
8589
8590     SDValue Cmp = Cond.getOperand(1);
8591     unsigned Opc = Cmp.getOpcode();
8592     EVT VT = Op.getValueType();
8593
8594     bool IllegalFPCMov = false;
8595     if (VT.isFloatingPoint() && !VT.isVector() &&
8596         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8597       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8598
8599     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8600         Opc == X86ISD::BT) { // FIXME
8601       Cond = Cmp;
8602       addTest = false;
8603     }
8604   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8605              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8606              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8607               Cond.getOperand(0).getValueType() != MVT::i8)) {
8608     SDValue LHS = Cond.getOperand(0);
8609     SDValue RHS = Cond.getOperand(1);
8610     unsigned X86Opcode;
8611     unsigned X86Cond;
8612     SDVTList VTs;
8613     switch (CondOpcode) {
8614     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8615     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8616     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8617     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8618     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8619     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8620     default: llvm_unreachable("unexpected overflowing operator");
8621     }
8622     if (CondOpcode == ISD::UMULO)
8623       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8624                           MVT::i32);
8625     else
8626       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8627
8628     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8629
8630     if (CondOpcode == ISD::UMULO)
8631       Cond = X86Op.getValue(2);
8632     else
8633       Cond = X86Op.getValue(1);
8634
8635     CC = DAG.getConstant(X86Cond, MVT::i8);
8636     addTest = false;
8637   }
8638
8639   if (addTest) {
8640     // Look pass the truncate.
8641     if (Cond.getOpcode() == ISD::TRUNCATE)
8642       Cond = Cond.getOperand(0);
8643
8644     // We know the result of AND is compared against zero. Try to match
8645     // it to BT.
8646     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8647       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8648       if (NewSetCC.getNode()) {
8649         CC = NewSetCC.getOperand(0);
8650         Cond = NewSetCC.getOperand(1);
8651         addTest = false;
8652       }
8653     }
8654   }
8655
8656   if (addTest) {
8657     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8658     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8659   }
8660
8661   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8662   // a <  b ?  0 : -1 -> RES = setcc_carry
8663   // a >= b ? -1 :  0 -> RES = setcc_carry
8664   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8665   if (Cond.getOpcode() == X86ISD::CMP) {
8666     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8667
8668     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8669         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8670       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8671                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8672       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8673         return DAG.getNOT(DL, Res, Res.getValueType());
8674       return Res;
8675     }
8676   }
8677
8678   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8679   // condition is true.
8680   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8681   SDValue Ops[] = { Op2, Op1, CC, Cond };
8682   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8683 }
8684
8685 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8686 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8687 // from the AND / OR.
8688 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8689   Opc = Op.getOpcode();
8690   if (Opc != ISD::OR && Opc != ISD::AND)
8691     return false;
8692   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8693           Op.getOperand(0).hasOneUse() &&
8694           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8695           Op.getOperand(1).hasOneUse());
8696 }
8697
8698 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8699 // 1 and that the SETCC node has a single use.
8700 static bool isXor1OfSetCC(SDValue Op) {
8701   if (Op.getOpcode() != ISD::XOR)
8702     return false;
8703   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8704   if (N1C && N1C->getAPIntValue() == 1) {
8705     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8706       Op.getOperand(0).hasOneUse();
8707   }
8708   return false;
8709 }
8710
8711 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8712   bool addTest = true;
8713   SDValue Chain = Op.getOperand(0);
8714   SDValue Cond  = Op.getOperand(1);
8715   SDValue Dest  = Op.getOperand(2);
8716   DebugLoc dl = Op.getDebugLoc();
8717   SDValue CC;
8718   bool Inverted = false;
8719
8720   if (Cond.getOpcode() == ISD::SETCC) {
8721     // Check for setcc([su]{add,sub,mul}o == 0).
8722     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8723         isa<ConstantSDNode>(Cond.getOperand(1)) &&
8724         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8725         Cond.getOperand(0).getResNo() == 1 &&
8726         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8727          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8728          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8729          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8730          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8731          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8732       Inverted = true;
8733       Cond = Cond.getOperand(0);
8734     } else {
8735       SDValue NewCond = LowerSETCC(Cond, DAG);
8736       if (NewCond.getNode())
8737         Cond = NewCond;
8738     }
8739   }
8740 #if 0
8741   // FIXME: LowerXALUO doesn't handle these!!
8742   else if (Cond.getOpcode() == X86ISD::ADD  ||
8743            Cond.getOpcode() == X86ISD::SUB  ||
8744            Cond.getOpcode() == X86ISD::SMUL ||
8745            Cond.getOpcode() == X86ISD::UMUL)
8746     Cond = LowerXALUO(Cond, DAG);
8747 #endif
8748
8749   // Look pass (and (setcc_carry (cmp ...)), 1).
8750   if (Cond.getOpcode() == ISD::AND &&
8751       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8752     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8753     if (C && C->getAPIntValue() == 1)
8754       Cond = Cond.getOperand(0);
8755   }
8756
8757   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8758   // setting operand in place of the X86ISD::SETCC.
8759   unsigned CondOpcode = Cond.getOpcode();
8760   if (CondOpcode == X86ISD::SETCC ||
8761       CondOpcode == X86ISD::SETCC_CARRY) {
8762     CC = Cond.getOperand(0);
8763
8764     SDValue Cmp = Cond.getOperand(1);
8765     unsigned Opc = Cmp.getOpcode();
8766     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8767     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8768       Cond = Cmp;
8769       addTest = false;
8770     } else {
8771       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8772       default: break;
8773       case X86::COND_O:
8774       case X86::COND_B:
8775         // These can only come from an arithmetic instruction with overflow,
8776         // e.g. SADDO, UADDO.
8777         Cond = Cond.getNode()->getOperand(1);
8778         addTest = false;
8779         break;
8780       }
8781     }
8782   }
8783   CondOpcode = Cond.getOpcode();
8784   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8785       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8786       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8787        Cond.getOperand(0).getValueType() != MVT::i8)) {
8788     SDValue LHS = Cond.getOperand(0);
8789     SDValue RHS = Cond.getOperand(1);
8790     unsigned X86Opcode;
8791     unsigned X86Cond;
8792     SDVTList VTs;
8793     switch (CondOpcode) {
8794     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8795     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8796     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8797     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8798     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8799     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8800     default: llvm_unreachable("unexpected overflowing operator");
8801     }
8802     if (Inverted)
8803       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8804     if (CondOpcode == ISD::UMULO)
8805       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8806                           MVT::i32);
8807     else
8808       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8809
8810     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8811
8812     if (CondOpcode == ISD::UMULO)
8813       Cond = X86Op.getValue(2);
8814     else
8815       Cond = X86Op.getValue(1);
8816
8817     CC = DAG.getConstant(X86Cond, MVT::i8);
8818     addTest = false;
8819   } else {
8820     unsigned CondOpc;
8821     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8822       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8823       if (CondOpc == ISD::OR) {
8824         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8825         // two branches instead of an explicit OR instruction with a
8826         // separate test.
8827         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8828             isX86LogicalCmp(Cmp)) {
8829           CC = Cond.getOperand(0).getOperand(0);
8830           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8831                               Chain, Dest, CC, Cmp);
8832           CC = Cond.getOperand(1).getOperand(0);
8833           Cond = Cmp;
8834           addTest = false;
8835         }
8836       } else { // ISD::AND
8837         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8838         // two branches instead of an explicit AND instruction with a
8839         // separate test. However, we only do this if this block doesn't
8840         // have a fall-through edge, because this requires an explicit
8841         // jmp when the condition is false.
8842         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8843             isX86LogicalCmp(Cmp) &&
8844             Op.getNode()->hasOneUse()) {
8845           X86::CondCode CCode =
8846             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8847           CCode = X86::GetOppositeBranchCondition(CCode);
8848           CC = DAG.getConstant(CCode, MVT::i8);
8849           SDNode *User = *Op.getNode()->use_begin();
8850           // Look for an unconditional branch following this conditional branch.
8851           // We need this because we need to reverse the successors in order
8852           // to implement FCMP_OEQ.
8853           if (User->getOpcode() == ISD::BR) {
8854             SDValue FalseBB = User->getOperand(1);
8855             SDNode *NewBR =
8856               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8857             assert(NewBR == User);
8858             (void)NewBR;
8859             Dest = FalseBB;
8860
8861             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8862                                 Chain, Dest, CC, Cmp);
8863             X86::CondCode CCode =
8864               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8865             CCode = X86::GetOppositeBranchCondition(CCode);
8866             CC = DAG.getConstant(CCode, MVT::i8);
8867             Cond = Cmp;
8868             addTest = false;
8869           }
8870         }
8871       }
8872     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8873       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8874       // It should be transformed during dag combiner except when the condition
8875       // is set by a arithmetics with overflow node.
8876       X86::CondCode CCode =
8877         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8878       CCode = X86::GetOppositeBranchCondition(CCode);
8879       CC = DAG.getConstant(CCode, MVT::i8);
8880       Cond = Cond.getOperand(0).getOperand(1);
8881       addTest = false;
8882     } else if (Cond.getOpcode() == ISD::SETCC &&
8883                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
8884       // For FCMP_OEQ, we can emit
8885       // two branches instead of an explicit AND instruction with a
8886       // separate test. However, we only do this if this block doesn't
8887       // have a fall-through edge, because this requires an explicit
8888       // jmp when the condition is false.
8889       if (Op.getNode()->hasOneUse()) {
8890         SDNode *User = *Op.getNode()->use_begin();
8891         // Look for an unconditional branch following this conditional branch.
8892         // We need this because we need to reverse the successors in order
8893         // to implement FCMP_OEQ.
8894         if (User->getOpcode() == ISD::BR) {
8895           SDValue FalseBB = User->getOperand(1);
8896           SDNode *NewBR =
8897             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8898           assert(NewBR == User);
8899           (void)NewBR;
8900           Dest = FalseBB;
8901
8902           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8903                                     Cond.getOperand(0), Cond.getOperand(1));
8904           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8905           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8906                               Chain, Dest, CC, Cmp);
8907           CC = DAG.getConstant(X86::COND_P, MVT::i8);
8908           Cond = Cmp;
8909           addTest = false;
8910         }
8911       }
8912     } else if (Cond.getOpcode() == ISD::SETCC &&
8913                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
8914       // For FCMP_UNE, we can emit
8915       // two branches instead of an explicit AND instruction with a
8916       // separate test. However, we only do this if this block doesn't
8917       // have a fall-through edge, because this requires an explicit
8918       // jmp when the condition is false.
8919       if (Op.getNode()->hasOneUse()) {
8920         SDNode *User = *Op.getNode()->use_begin();
8921         // Look for an unconditional branch following this conditional branch.
8922         // We need this because we need to reverse the successors in order
8923         // to implement FCMP_UNE.
8924         if (User->getOpcode() == ISD::BR) {
8925           SDValue FalseBB = User->getOperand(1);
8926           SDNode *NewBR =
8927             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8928           assert(NewBR == User);
8929           (void)NewBR;
8930
8931           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
8932                                     Cond.getOperand(0), Cond.getOperand(1));
8933           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8934           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8935                               Chain, Dest, CC, Cmp);
8936           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
8937           Cond = Cmp;
8938           addTest = false;
8939           Dest = FalseBB;
8940         }
8941       }
8942     }
8943   }
8944
8945   if (addTest) {
8946     // Look pass the truncate.
8947     if (Cond.getOpcode() == ISD::TRUNCATE)
8948       Cond = Cond.getOperand(0);
8949
8950     // We know the result of AND is compared against zero. Try to match
8951     // it to BT.
8952     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8953       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8954       if (NewSetCC.getNode()) {
8955         CC = NewSetCC.getOperand(0);
8956         Cond = NewSetCC.getOperand(1);
8957         addTest = false;
8958       }
8959     }
8960   }
8961
8962   if (addTest) {
8963     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8964     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8965   }
8966   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8967                      Chain, Dest, CC, Cond);
8968 }
8969
8970
8971 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8972 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8973 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8974 // that the guard pages used by the OS virtual memory manager are allocated in
8975 // correct sequence.
8976 SDValue
8977 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8978                                            SelectionDAG &DAG) const {
8979   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8980           getTargetMachine().Options.EnableSegmentedStacks) &&
8981          "This should be used only on Windows targets or when segmented stacks "
8982          "are being used");
8983   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8984   DebugLoc dl = Op.getDebugLoc();
8985
8986   // Get the inputs.
8987   SDValue Chain = Op.getOperand(0);
8988   SDValue Size  = Op.getOperand(1);
8989   // FIXME: Ensure alignment here
8990
8991   bool Is64Bit = Subtarget->is64Bit();
8992   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8993
8994   if (getTargetMachine().Options.EnableSegmentedStacks) {
8995     MachineFunction &MF = DAG.getMachineFunction();
8996     MachineRegisterInfo &MRI = MF.getRegInfo();
8997
8998     if (Is64Bit) {
8999       // The 64 bit implementation of segmented stacks needs to clobber both r10
9000       // r11. This makes it impossible to use it along with nested parameters.
9001       const Function *F = MF.getFunction();
9002
9003       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9004            I != E; I++)
9005         if (I->hasNestAttr())
9006           report_fatal_error("Cannot use segmented stacks with functions that "
9007                              "have nested arguments.");
9008     }
9009
9010     const TargetRegisterClass *AddrRegClass =
9011       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9012     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9013     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9014     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9015                                 DAG.getRegister(Vreg, SPTy));
9016     SDValue Ops1[2] = { Value, Chain };
9017     return DAG.getMergeValues(Ops1, 2, dl);
9018   } else {
9019     SDValue Flag;
9020     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9021
9022     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9023     Flag = Chain.getValue(1);
9024     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9025
9026     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9027     Flag = Chain.getValue(1);
9028
9029     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9030
9031     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9032     return DAG.getMergeValues(Ops1, 2, dl);
9033   }
9034 }
9035
9036 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9037   MachineFunction &MF = DAG.getMachineFunction();
9038   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9039
9040   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9041   DebugLoc DL = Op.getDebugLoc();
9042
9043   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9044     // vastart just stores the address of the VarArgsFrameIndex slot into the
9045     // memory location argument.
9046     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9047                                    getPointerTy());
9048     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9049                         MachinePointerInfo(SV), false, false, 0);
9050   }
9051
9052   // __va_list_tag:
9053   //   gp_offset         (0 - 6 * 8)
9054   //   fp_offset         (48 - 48 + 8 * 16)
9055   //   overflow_arg_area (point to parameters coming in memory).
9056   //   reg_save_area
9057   SmallVector<SDValue, 8> MemOps;
9058   SDValue FIN = Op.getOperand(1);
9059   // Store gp_offset
9060   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9061                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9062                                                MVT::i32),
9063                                FIN, MachinePointerInfo(SV), false, false, 0);
9064   MemOps.push_back(Store);
9065
9066   // Store fp_offset
9067   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9068                     FIN, DAG.getIntPtrConstant(4));
9069   Store = DAG.getStore(Op.getOperand(0), DL,
9070                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9071                                        MVT::i32),
9072                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9073   MemOps.push_back(Store);
9074
9075   // Store ptr to overflow_arg_area
9076   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9077                     FIN, DAG.getIntPtrConstant(4));
9078   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9079                                     getPointerTy());
9080   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9081                        MachinePointerInfo(SV, 8),
9082                        false, false, 0);
9083   MemOps.push_back(Store);
9084
9085   // Store ptr to reg_save_area.
9086   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9087                     FIN, DAG.getIntPtrConstant(8));
9088   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9089                                     getPointerTy());
9090   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9091                        MachinePointerInfo(SV, 16), false, false, 0);
9092   MemOps.push_back(Store);
9093   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9094                      &MemOps[0], MemOps.size());
9095 }
9096
9097 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9098   assert(Subtarget->is64Bit() &&
9099          "LowerVAARG only handles 64-bit va_arg!");
9100   assert((Subtarget->isTargetLinux() ||
9101           Subtarget->isTargetDarwin()) &&
9102           "Unhandled target in LowerVAARG");
9103   assert(Op.getNode()->getNumOperands() == 4);
9104   SDValue Chain = Op.getOperand(0);
9105   SDValue SrcPtr = Op.getOperand(1);
9106   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9107   unsigned Align = Op.getConstantOperandVal(3);
9108   DebugLoc dl = Op.getDebugLoc();
9109
9110   EVT ArgVT = Op.getNode()->getValueType(0);
9111   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9112   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9113   uint8_t ArgMode;
9114
9115   // Decide which area this value should be read from.
9116   // TODO: Implement the AMD64 ABI in its entirety. This simple
9117   // selection mechanism works only for the basic types.
9118   if (ArgVT == MVT::f80) {
9119     llvm_unreachable("va_arg for f80 not yet implemented");
9120   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9121     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9122   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9123     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9124   } else {
9125     llvm_unreachable("Unhandled argument type in LowerVAARG");
9126   }
9127
9128   if (ArgMode == 2) {
9129     // Sanity Check: Make sure using fp_offset makes sense.
9130     assert(!getTargetMachine().Options.UseSoftFloat &&
9131            !(DAG.getMachineFunction()
9132                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9133            Subtarget->hasSSE1());
9134   }
9135
9136   // Insert VAARG_64 node into the DAG
9137   // VAARG_64 returns two values: Variable Argument Address, Chain
9138   SmallVector<SDValue, 11> InstOps;
9139   InstOps.push_back(Chain);
9140   InstOps.push_back(SrcPtr);
9141   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9142   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9143   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9144   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9145   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9146                                           VTs, &InstOps[0], InstOps.size(),
9147                                           MVT::i64,
9148                                           MachinePointerInfo(SV),
9149                                           /*Align=*/0,
9150                                           /*Volatile=*/false,
9151                                           /*ReadMem=*/true,
9152                                           /*WriteMem=*/true);
9153   Chain = VAARG.getValue(1);
9154
9155   // Load the next argument and return it
9156   return DAG.getLoad(ArgVT, dl,
9157                      Chain,
9158                      VAARG,
9159                      MachinePointerInfo(),
9160                      false, false, false, 0);
9161 }
9162
9163 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9164   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9165   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9166   SDValue Chain = Op.getOperand(0);
9167   SDValue DstPtr = Op.getOperand(1);
9168   SDValue SrcPtr = Op.getOperand(2);
9169   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9170   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9171   DebugLoc DL = Op.getDebugLoc();
9172
9173   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9174                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9175                        false,
9176                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9177 }
9178
9179 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9180 // may or may not be a constant. Takes immediate version of shift as input.
9181 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9182                                    SDValue SrcOp, SDValue ShAmt,
9183                                    SelectionDAG &DAG) {
9184   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9185
9186   if (isa<ConstantSDNode>(ShAmt)) {
9187     switch (Opc) {
9188       default: llvm_unreachable("Unknown target vector shift node");
9189       case X86ISD::VSHLI:
9190       case X86ISD::VSRLI:
9191       case X86ISD::VSRAI:
9192         return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9193     }
9194   }
9195
9196   // Change opcode to non-immediate version
9197   switch (Opc) {
9198     default: llvm_unreachable("Unknown target vector shift node");
9199     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9200     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9201     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9202   }
9203
9204   // Need to build a vector containing shift amount
9205   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9206   SDValue ShOps[4];
9207   ShOps[0] = ShAmt;
9208   ShOps[1] = DAG.getConstant(0, MVT::i32);
9209   ShOps[2] = DAG.getUNDEF(MVT::i32);
9210   ShOps[3] = DAG.getUNDEF(MVT::i32);
9211   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9212   ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9213   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9214 }
9215
9216 SDValue
9217 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9218   DebugLoc dl = Op.getDebugLoc();
9219   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9220   switch (IntNo) {
9221   default: return SDValue();    // Don't custom lower most intrinsics.
9222   // Comparison intrinsics.
9223   case Intrinsic::x86_sse_comieq_ss:
9224   case Intrinsic::x86_sse_comilt_ss:
9225   case Intrinsic::x86_sse_comile_ss:
9226   case Intrinsic::x86_sse_comigt_ss:
9227   case Intrinsic::x86_sse_comige_ss:
9228   case Intrinsic::x86_sse_comineq_ss:
9229   case Intrinsic::x86_sse_ucomieq_ss:
9230   case Intrinsic::x86_sse_ucomilt_ss:
9231   case Intrinsic::x86_sse_ucomile_ss:
9232   case Intrinsic::x86_sse_ucomigt_ss:
9233   case Intrinsic::x86_sse_ucomige_ss:
9234   case Intrinsic::x86_sse_ucomineq_ss:
9235   case Intrinsic::x86_sse2_comieq_sd:
9236   case Intrinsic::x86_sse2_comilt_sd:
9237   case Intrinsic::x86_sse2_comile_sd:
9238   case Intrinsic::x86_sse2_comigt_sd:
9239   case Intrinsic::x86_sse2_comige_sd:
9240   case Intrinsic::x86_sse2_comineq_sd:
9241   case Intrinsic::x86_sse2_ucomieq_sd:
9242   case Intrinsic::x86_sse2_ucomilt_sd:
9243   case Intrinsic::x86_sse2_ucomile_sd:
9244   case Intrinsic::x86_sse2_ucomigt_sd:
9245   case Intrinsic::x86_sse2_ucomige_sd:
9246   case Intrinsic::x86_sse2_ucomineq_sd: {
9247     unsigned Opc = 0;
9248     ISD::CondCode CC = ISD::SETCC_INVALID;
9249     switch (IntNo) {
9250     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9251     case Intrinsic::x86_sse_comieq_ss:
9252     case Intrinsic::x86_sse2_comieq_sd:
9253       Opc = X86ISD::COMI;
9254       CC = ISD::SETEQ;
9255       break;
9256     case Intrinsic::x86_sse_comilt_ss:
9257     case Intrinsic::x86_sse2_comilt_sd:
9258       Opc = X86ISD::COMI;
9259       CC = ISD::SETLT;
9260       break;
9261     case Intrinsic::x86_sse_comile_ss:
9262     case Intrinsic::x86_sse2_comile_sd:
9263       Opc = X86ISD::COMI;
9264       CC = ISD::SETLE;
9265       break;
9266     case Intrinsic::x86_sse_comigt_ss:
9267     case Intrinsic::x86_sse2_comigt_sd:
9268       Opc = X86ISD::COMI;
9269       CC = ISD::SETGT;
9270       break;
9271     case Intrinsic::x86_sse_comige_ss:
9272     case Intrinsic::x86_sse2_comige_sd:
9273       Opc = X86ISD::COMI;
9274       CC = ISD::SETGE;
9275       break;
9276     case Intrinsic::x86_sse_comineq_ss:
9277     case Intrinsic::x86_sse2_comineq_sd:
9278       Opc = X86ISD::COMI;
9279       CC = ISD::SETNE;
9280       break;
9281     case Intrinsic::x86_sse_ucomieq_ss:
9282     case Intrinsic::x86_sse2_ucomieq_sd:
9283       Opc = X86ISD::UCOMI;
9284       CC = ISD::SETEQ;
9285       break;
9286     case Intrinsic::x86_sse_ucomilt_ss:
9287     case Intrinsic::x86_sse2_ucomilt_sd:
9288       Opc = X86ISD::UCOMI;
9289       CC = ISD::SETLT;
9290       break;
9291     case Intrinsic::x86_sse_ucomile_ss:
9292     case Intrinsic::x86_sse2_ucomile_sd:
9293       Opc = X86ISD::UCOMI;
9294       CC = ISD::SETLE;
9295       break;
9296     case Intrinsic::x86_sse_ucomigt_ss:
9297     case Intrinsic::x86_sse2_ucomigt_sd:
9298       Opc = X86ISD::UCOMI;
9299       CC = ISD::SETGT;
9300       break;
9301     case Intrinsic::x86_sse_ucomige_ss:
9302     case Intrinsic::x86_sse2_ucomige_sd:
9303       Opc = X86ISD::UCOMI;
9304       CC = ISD::SETGE;
9305       break;
9306     case Intrinsic::x86_sse_ucomineq_ss:
9307     case Intrinsic::x86_sse2_ucomineq_sd:
9308       Opc = X86ISD::UCOMI;
9309       CC = ISD::SETNE;
9310       break;
9311     }
9312
9313     SDValue LHS = Op.getOperand(1);
9314     SDValue RHS = Op.getOperand(2);
9315     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9316     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9317     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9318     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9319                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9320     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9321   }
9322   // XOP comparison intrinsics
9323   case Intrinsic::x86_xop_vpcomltb:
9324   case Intrinsic::x86_xop_vpcomltw:
9325   case Intrinsic::x86_xop_vpcomltd:
9326   case Intrinsic::x86_xop_vpcomltq:
9327   case Intrinsic::x86_xop_vpcomltub:
9328   case Intrinsic::x86_xop_vpcomltuw:
9329   case Intrinsic::x86_xop_vpcomltud:
9330   case Intrinsic::x86_xop_vpcomltuq:
9331   case Intrinsic::x86_xop_vpcomleb:
9332   case Intrinsic::x86_xop_vpcomlew:
9333   case Intrinsic::x86_xop_vpcomled:
9334   case Intrinsic::x86_xop_vpcomleq:
9335   case Intrinsic::x86_xop_vpcomleub:
9336   case Intrinsic::x86_xop_vpcomleuw:
9337   case Intrinsic::x86_xop_vpcomleud:
9338   case Intrinsic::x86_xop_vpcomleuq:
9339   case Intrinsic::x86_xop_vpcomgtb:
9340   case Intrinsic::x86_xop_vpcomgtw:
9341   case Intrinsic::x86_xop_vpcomgtd:
9342   case Intrinsic::x86_xop_vpcomgtq:
9343   case Intrinsic::x86_xop_vpcomgtub:
9344   case Intrinsic::x86_xop_vpcomgtuw:
9345   case Intrinsic::x86_xop_vpcomgtud:
9346   case Intrinsic::x86_xop_vpcomgtuq:
9347   case Intrinsic::x86_xop_vpcomgeb:
9348   case Intrinsic::x86_xop_vpcomgew:
9349   case Intrinsic::x86_xop_vpcomged:
9350   case Intrinsic::x86_xop_vpcomgeq:
9351   case Intrinsic::x86_xop_vpcomgeub:
9352   case Intrinsic::x86_xop_vpcomgeuw:
9353   case Intrinsic::x86_xop_vpcomgeud:
9354   case Intrinsic::x86_xop_vpcomgeuq:
9355   case Intrinsic::x86_xop_vpcomeqb:
9356   case Intrinsic::x86_xop_vpcomeqw:
9357   case Intrinsic::x86_xop_vpcomeqd:
9358   case Intrinsic::x86_xop_vpcomeqq:
9359   case Intrinsic::x86_xop_vpcomequb:
9360   case Intrinsic::x86_xop_vpcomequw:
9361   case Intrinsic::x86_xop_vpcomequd:
9362   case Intrinsic::x86_xop_vpcomequq:
9363   case Intrinsic::x86_xop_vpcomneb:
9364   case Intrinsic::x86_xop_vpcomnew:
9365   case Intrinsic::x86_xop_vpcomned:
9366   case Intrinsic::x86_xop_vpcomneq:
9367   case Intrinsic::x86_xop_vpcomneub:
9368   case Intrinsic::x86_xop_vpcomneuw:
9369   case Intrinsic::x86_xop_vpcomneud:
9370   case Intrinsic::x86_xop_vpcomneuq:
9371   case Intrinsic::x86_xop_vpcomfalseb:
9372   case Intrinsic::x86_xop_vpcomfalsew:
9373   case Intrinsic::x86_xop_vpcomfalsed:
9374   case Intrinsic::x86_xop_vpcomfalseq:
9375   case Intrinsic::x86_xop_vpcomfalseub:
9376   case Intrinsic::x86_xop_vpcomfalseuw:
9377   case Intrinsic::x86_xop_vpcomfalseud:
9378   case Intrinsic::x86_xop_vpcomfalseuq:
9379   case Intrinsic::x86_xop_vpcomtrueb:
9380   case Intrinsic::x86_xop_vpcomtruew:
9381   case Intrinsic::x86_xop_vpcomtrued:
9382   case Intrinsic::x86_xop_vpcomtrueq:
9383   case Intrinsic::x86_xop_vpcomtrueub:
9384   case Intrinsic::x86_xop_vpcomtrueuw:
9385   case Intrinsic::x86_xop_vpcomtrueud:
9386   case Intrinsic::x86_xop_vpcomtrueuq: {
9387     unsigned CC = 0;
9388     unsigned Opc = 0;
9389
9390     switch (IntNo) {
9391     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9392     case Intrinsic::x86_xop_vpcomltb:
9393     case Intrinsic::x86_xop_vpcomltw:
9394     case Intrinsic::x86_xop_vpcomltd:
9395     case Intrinsic::x86_xop_vpcomltq:
9396       CC = 0;
9397       Opc = X86ISD::VPCOM;
9398       break;
9399     case Intrinsic::x86_xop_vpcomltub:
9400     case Intrinsic::x86_xop_vpcomltuw:
9401     case Intrinsic::x86_xop_vpcomltud:
9402     case Intrinsic::x86_xop_vpcomltuq:
9403       CC = 0;
9404       Opc = X86ISD::VPCOMU;
9405       break;
9406     case Intrinsic::x86_xop_vpcomleb:
9407     case Intrinsic::x86_xop_vpcomlew:
9408     case Intrinsic::x86_xop_vpcomled:
9409     case Intrinsic::x86_xop_vpcomleq:
9410       CC = 1;
9411       Opc = X86ISD::VPCOM;
9412       break;
9413     case Intrinsic::x86_xop_vpcomleub:
9414     case Intrinsic::x86_xop_vpcomleuw:
9415     case Intrinsic::x86_xop_vpcomleud:
9416     case Intrinsic::x86_xop_vpcomleuq:
9417       CC = 1;
9418       Opc = X86ISD::VPCOMU;
9419       break;
9420     case Intrinsic::x86_xop_vpcomgtb:
9421     case Intrinsic::x86_xop_vpcomgtw:
9422     case Intrinsic::x86_xop_vpcomgtd:
9423     case Intrinsic::x86_xop_vpcomgtq:
9424       CC = 2;
9425       Opc = X86ISD::VPCOM;
9426       break;
9427     case Intrinsic::x86_xop_vpcomgtub:
9428     case Intrinsic::x86_xop_vpcomgtuw:
9429     case Intrinsic::x86_xop_vpcomgtud:
9430     case Intrinsic::x86_xop_vpcomgtuq:
9431       CC = 2;
9432       Opc = X86ISD::VPCOMU;
9433       break;
9434     case Intrinsic::x86_xop_vpcomgeb:
9435     case Intrinsic::x86_xop_vpcomgew:
9436     case Intrinsic::x86_xop_vpcomged:
9437     case Intrinsic::x86_xop_vpcomgeq:
9438       CC = 3;
9439       Opc = X86ISD::VPCOM;
9440       break;
9441     case Intrinsic::x86_xop_vpcomgeub:
9442     case Intrinsic::x86_xop_vpcomgeuw:
9443     case Intrinsic::x86_xop_vpcomgeud:
9444     case Intrinsic::x86_xop_vpcomgeuq:
9445       CC = 3;
9446       Opc = X86ISD::VPCOMU;
9447       break;
9448     case Intrinsic::x86_xop_vpcomeqb:
9449     case Intrinsic::x86_xop_vpcomeqw:
9450     case Intrinsic::x86_xop_vpcomeqd:
9451     case Intrinsic::x86_xop_vpcomeqq:
9452       CC = 4;
9453       Opc = X86ISD::VPCOM;
9454       break;
9455     case Intrinsic::x86_xop_vpcomequb:
9456     case Intrinsic::x86_xop_vpcomequw:
9457     case Intrinsic::x86_xop_vpcomequd:
9458     case Intrinsic::x86_xop_vpcomequq:
9459       CC = 4;
9460       Opc = X86ISD::VPCOMU;
9461       break;
9462     case Intrinsic::x86_xop_vpcomneb:
9463     case Intrinsic::x86_xop_vpcomnew:
9464     case Intrinsic::x86_xop_vpcomned:
9465     case Intrinsic::x86_xop_vpcomneq:
9466       CC = 5;
9467       Opc = X86ISD::VPCOM;
9468       break;
9469     case Intrinsic::x86_xop_vpcomneub:
9470     case Intrinsic::x86_xop_vpcomneuw:
9471     case Intrinsic::x86_xop_vpcomneud:
9472     case Intrinsic::x86_xop_vpcomneuq:
9473       CC = 5;
9474       Opc = X86ISD::VPCOMU;
9475       break;
9476     case Intrinsic::x86_xop_vpcomfalseb:
9477     case Intrinsic::x86_xop_vpcomfalsew:
9478     case Intrinsic::x86_xop_vpcomfalsed:
9479     case Intrinsic::x86_xop_vpcomfalseq:
9480       CC = 6;
9481       Opc = X86ISD::VPCOM;
9482       break;
9483     case Intrinsic::x86_xop_vpcomfalseub:
9484     case Intrinsic::x86_xop_vpcomfalseuw:
9485     case Intrinsic::x86_xop_vpcomfalseud:
9486     case Intrinsic::x86_xop_vpcomfalseuq:
9487       CC = 6;
9488       Opc = X86ISD::VPCOMU;
9489       break;
9490     case Intrinsic::x86_xop_vpcomtrueb:
9491     case Intrinsic::x86_xop_vpcomtruew:
9492     case Intrinsic::x86_xop_vpcomtrued:
9493     case Intrinsic::x86_xop_vpcomtrueq:
9494       CC = 7;
9495       Opc = X86ISD::VPCOM;
9496       break;
9497     case Intrinsic::x86_xop_vpcomtrueub:
9498     case Intrinsic::x86_xop_vpcomtrueuw:
9499     case Intrinsic::x86_xop_vpcomtrueud:
9500     case Intrinsic::x86_xop_vpcomtrueuq:
9501       CC = 7;
9502       Opc = X86ISD::VPCOMU;
9503       break;
9504     }
9505
9506     SDValue LHS = Op.getOperand(1);
9507     SDValue RHS = Op.getOperand(2);
9508     return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9509                        DAG.getConstant(CC, MVT::i8));
9510   }
9511
9512   // Arithmetic intrinsics.
9513   case Intrinsic::x86_sse2_pmulu_dq:
9514   case Intrinsic::x86_avx2_pmulu_dq:
9515     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9516                        Op.getOperand(1), Op.getOperand(2));
9517   case Intrinsic::x86_sse3_hadd_ps:
9518   case Intrinsic::x86_sse3_hadd_pd:
9519   case Intrinsic::x86_avx_hadd_ps_256:
9520   case Intrinsic::x86_avx_hadd_pd_256:
9521     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9522                        Op.getOperand(1), Op.getOperand(2));
9523   case Intrinsic::x86_sse3_hsub_ps:
9524   case Intrinsic::x86_sse3_hsub_pd:
9525   case Intrinsic::x86_avx_hsub_ps_256:
9526   case Intrinsic::x86_avx_hsub_pd_256:
9527     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9528                        Op.getOperand(1), Op.getOperand(2));
9529   case Intrinsic::x86_ssse3_phadd_w_128:
9530   case Intrinsic::x86_ssse3_phadd_d_128:
9531   case Intrinsic::x86_avx2_phadd_w:
9532   case Intrinsic::x86_avx2_phadd_d:
9533     return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9534                        Op.getOperand(1), Op.getOperand(2));
9535   case Intrinsic::x86_ssse3_phsub_w_128:
9536   case Intrinsic::x86_ssse3_phsub_d_128:
9537   case Intrinsic::x86_avx2_phsub_w:
9538   case Intrinsic::x86_avx2_phsub_d:
9539     return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9540                        Op.getOperand(1), Op.getOperand(2));
9541   case Intrinsic::x86_avx2_psllv_d:
9542   case Intrinsic::x86_avx2_psllv_q:
9543   case Intrinsic::x86_avx2_psllv_d_256:
9544   case Intrinsic::x86_avx2_psllv_q_256:
9545     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9546                       Op.getOperand(1), Op.getOperand(2));
9547   case Intrinsic::x86_avx2_psrlv_d:
9548   case Intrinsic::x86_avx2_psrlv_q:
9549   case Intrinsic::x86_avx2_psrlv_d_256:
9550   case Intrinsic::x86_avx2_psrlv_q_256:
9551     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9552                       Op.getOperand(1), Op.getOperand(2));
9553   case Intrinsic::x86_avx2_psrav_d:
9554   case Intrinsic::x86_avx2_psrav_d_256:
9555     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9556                       Op.getOperand(1), Op.getOperand(2));
9557   case Intrinsic::x86_ssse3_pshuf_b_128:
9558   case Intrinsic::x86_avx2_pshuf_b:
9559     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9560                        Op.getOperand(1), Op.getOperand(2));
9561   case Intrinsic::x86_ssse3_psign_b_128:
9562   case Intrinsic::x86_ssse3_psign_w_128:
9563   case Intrinsic::x86_ssse3_psign_d_128:
9564   case Intrinsic::x86_avx2_psign_b:
9565   case Intrinsic::x86_avx2_psign_w:
9566   case Intrinsic::x86_avx2_psign_d:
9567     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9568                        Op.getOperand(1), Op.getOperand(2));
9569   case Intrinsic::x86_sse41_insertps:
9570     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9571                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9572   case Intrinsic::x86_avx_vperm2f128_ps_256:
9573   case Intrinsic::x86_avx_vperm2f128_pd_256:
9574   case Intrinsic::x86_avx_vperm2f128_si_256:
9575   case Intrinsic::x86_avx2_vperm2i128:
9576     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9577                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9578   case Intrinsic::x86_avx2_permd:
9579   case Intrinsic::x86_avx2_permps:
9580     // Operands intentionally swapped. Mask is last operand to intrinsic,
9581     // but second operand for node/intruction.
9582     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9583                        Op.getOperand(2), Op.getOperand(1));
9584
9585   // ptest and testp intrinsics. The intrinsic these come from are designed to
9586   // return an integer value, not just an instruction so lower it to the ptest
9587   // or testp pattern and a setcc for the result.
9588   case Intrinsic::x86_sse41_ptestz:
9589   case Intrinsic::x86_sse41_ptestc:
9590   case Intrinsic::x86_sse41_ptestnzc:
9591   case Intrinsic::x86_avx_ptestz_256:
9592   case Intrinsic::x86_avx_ptestc_256:
9593   case Intrinsic::x86_avx_ptestnzc_256:
9594   case Intrinsic::x86_avx_vtestz_ps:
9595   case Intrinsic::x86_avx_vtestc_ps:
9596   case Intrinsic::x86_avx_vtestnzc_ps:
9597   case Intrinsic::x86_avx_vtestz_pd:
9598   case Intrinsic::x86_avx_vtestc_pd:
9599   case Intrinsic::x86_avx_vtestnzc_pd:
9600   case Intrinsic::x86_avx_vtestz_ps_256:
9601   case Intrinsic::x86_avx_vtestc_ps_256:
9602   case Intrinsic::x86_avx_vtestnzc_ps_256:
9603   case Intrinsic::x86_avx_vtestz_pd_256:
9604   case Intrinsic::x86_avx_vtestc_pd_256:
9605   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9606     bool IsTestPacked = false;
9607     unsigned X86CC = 0;
9608     switch (IntNo) {
9609     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9610     case Intrinsic::x86_avx_vtestz_ps:
9611     case Intrinsic::x86_avx_vtestz_pd:
9612     case Intrinsic::x86_avx_vtestz_ps_256:
9613     case Intrinsic::x86_avx_vtestz_pd_256:
9614       IsTestPacked = true; // Fallthrough
9615     case Intrinsic::x86_sse41_ptestz:
9616     case Intrinsic::x86_avx_ptestz_256:
9617       // ZF = 1
9618       X86CC = X86::COND_E;
9619       break;
9620     case Intrinsic::x86_avx_vtestc_ps:
9621     case Intrinsic::x86_avx_vtestc_pd:
9622     case Intrinsic::x86_avx_vtestc_ps_256:
9623     case Intrinsic::x86_avx_vtestc_pd_256:
9624       IsTestPacked = true; // Fallthrough
9625     case Intrinsic::x86_sse41_ptestc:
9626     case Intrinsic::x86_avx_ptestc_256:
9627       // CF = 1
9628       X86CC = X86::COND_B;
9629       break;
9630     case Intrinsic::x86_avx_vtestnzc_ps:
9631     case Intrinsic::x86_avx_vtestnzc_pd:
9632     case Intrinsic::x86_avx_vtestnzc_ps_256:
9633     case Intrinsic::x86_avx_vtestnzc_pd_256:
9634       IsTestPacked = true; // Fallthrough
9635     case Intrinsic::x86_sse41_ptestnzc:
9636     case Intrinsic::x86_avx_ptestnzc_256:
9637       // ZF and CF = 0
9638       X86CC = X86::COND_A;
9639       break;
9640     }
9641
9642     SDValue LHS = Op.getOperand(1);
9643     SDValue RHS = Op.getOperand(2);
9644     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9645     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9646     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9647     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9648     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9649   }
9650
9651   // SSE/AVX shift intrinsics
9652   case Intrinsic::x86_sse2_psll_w:
9653   case Intrinsic::x86_sse2_psll_d:
9654   case Intrinsic::x86_sse2_psll_q:
9655   case Intrinsic::x86_avx2_psll_w:
9656   case Intrinsic::x86_avx2_psll_d:
9657   case Intrinsic::x86_avx2_psll_q:
9658     return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9659                        Op.getOperand(1), Op.getOperand(2));
9660   case Intrinsic::x86_sse2_psrl_w:
9661   case Intrinsic::x86_sse2_psrl_d:
9662   case Intrinsic::x86_sse2_psrl_q:
9663   case Intrinsic::x86_avx2_psrl_w:
9664   case Intrinsic::x86_avx2_psrl_d:
9665   case Intrinsic::x86_avx2_psrl_q:
9666     return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9667                        Op.getOperand(1), Op.getOperand(2));
9668   case Intrinsic::x86_sse2_psra_w:
9669   case Intrinsic::x86_sse2_psra_d:
9670   case Intrinsic::x86_avx2_psra_w:
9671   case Intrinsic::x86_avx2_psra_d:
9672     return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9673                        Op.getOperand(1), Op.getOperand(2));
9674   case Intrinsic::x86_sse2_pslli_w:
9675   case Intrinsic::x86_sse2_pslli_d:
9676   case Intrinsic::x86_sse2_pslli_q:
9677   case Intrinsic::x86_avx2_pslli_w:
9678   case Intrinsic::x86_avx2_pslli_d:
9679   case Intrinsic::x86_avx2_pslli_q:
9680     return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9681                                Op.getOperand(1), Op.getOperand(2), DAG);
9682   case Intrinsic::x86_sse2_psrli_w:
9683   case Intrinsic::x86_sse2_psrli_d:
9684   case Intrinsic::x86_sse2_psrli_q:
9685   case Intrinsic::x86_avx2_psrli_w:
9686   case Intrinsic::x86_avx2_psrli_d:
9687   case Intrinsic::x86_avx2_psrli_q:
9688     return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9689                                Op.getOperand(1), Op.getOperand(2), DAG);
9690   case Intrinsic::x86_sse2_psrai_w:
9691   case Intrinsic::x86_sse2_psrai_d:
9692   case Intrinsic::x86_avx2_psrai_w:
9693   case Intrinsic::x86_avx2_psrai_d:
9694     return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9695                                Op.getOperand(1), Op.getOperand(2), DAG);
9696   // Fix vector shift instructions where the last operand is a non-immediate
9697   // i32 value.
9698   case Intrinsic::x86_mmx_pslli_w:
9699   case Intrinsic::x86_mmx_pslli_d:
9700   case Intrinsic::x86_mmx_pslli_q:
9701   case Intrinsic::x86_mmx_psrli_w:
9702   case Intrinsic::x86_mmx_psrli_d:
9703   case Intrinsic::x86_mmx_psrli_q:
9704   case Intrinsic::x86_mmx_psrai_w:
9705   case Intrinsic::x86_mmx_psrai_d: {
9706     SDValue ShAmt = Op.getOperand(2);
9707     if (isa<ConstantSDNode>(ShAmt))
9708       return SDValue();
9709
9710     unsigned NewIntNo = 0;
9711     switch (IntNo) {
9712     case Intrinsic::x86_mmx_pslli_w:
9713       NewIntNo = Intrinsic::x86_mmx_psll_w;
9714       break;
9715     case Intrinsic::x86_mmx_pslli_d:
9716       NewIntNo = Intrinsic::x86_mmx_psll_d;
9717       break;
9718     case Intrinsic::x86_mmx_pslli_q:
9719       NewIntNo = Intrinsic::x86_mmx_psll_q;
9720       break;
9721     case Intrinsic::x86_mmx_psrli_w:
9722       NewIntNo = Intrinsic::x86_mmx_psrl_w;
9723       break;
9724     case Intrinsic::x86_mmx_psrli_d:
9725       NewIntNo = Intrinsic::x86_mmx_psrl_d;
9726       break;
9727     case Intrinsic::x86_mmx_psrli_q:
9728       NewIntNo = Intrinsic::x86_mmx_psrl_q;
9729       break;
9730     case Intrinsic::x86_mmx_psrai_w:
9731       NewIntNo = Intrinsic::x86_mmx_psra_w;
9732       break;
9733     case Intrinsic::x86_mmx_psrai_d:
9734       NewIntNo = Intrinsic::x86_mmx_psra_d;
9735       break;
9736     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9737     }
9738
9739     // The vector shift intrinsics with scalars uses 32b shift amounts but
9740     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9741     // to be zero.
9742     ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9743                          DAG.getConstant(0, MVT::i32));
9744 // FIXME this must be lowered to get rid of the invalid type.
9745
9746     EVT VT = Op.getValueType();
9747     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9748     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9749                        DAG.getConstant(NewIntNo, MVT::i32),
9750                        Op.getOperand(1), ShAmt);
9751   }
9752   }
9753 }
9754
9755 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9756                                            SelectionDAG &DAG) const {
9757   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9758   MFI->setReturnAddressIsTaken(true);
9759
9760   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9761   DebugLoc dl = Op.getDebugLoc();
9762
9763   if (Depth > 0) {
9764     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9765     SDValue Offset =
9766       DAG.getConstant(TD->getPointerSize(),
9767                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9768     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9769                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9770                                    FrameAddr, Offset),
9771                        MachinePointerInfo(), false, false, false, 0);
9772   }
9773
9774   // Just load the return address.
9775   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9776   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9777                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9778 }
9779
9780 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9781   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9782   MFI->setFrameAddressIsTaken(true);
9783
9784   EVT VT = Op.getValueType();
9785   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9786   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9787   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9788   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9789   while (Depth--)
9790     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9791                             MachinePointerInfo(),
9792                             false, false, false, 0);
9793   return FrameAddr;
9794 }
9795
9796 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9797                                                      SelectionDAG &DAG) const {
9798   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9799 }
9800
9801 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9802   MachineFunction &MF = DAG.getMachineFunction();
9803   SDValue Chain     = Op.getOperand(0);
9804   SDValue Offset    = Op.getOperand(1);
9805   SDValue Handler   = Op.getOperand(2);
9806   DebugLoc dl       = Op.getDebugLoc();
9807
9808   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9809                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9810                                      getPointerTy());
9811   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9812
9813   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9814                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9815   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9816   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9817                        false, false, 0);
9818   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9819   MF.getRegInfo().addLiveOut(StoreAddrReg);
9820
9821   return DAG.getNode(X86ISD::EH_RETURN, dl,
9822                      MVT::Other,
9823                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9824 }
9825
9826 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9827                                                   SelectionDAG &DAG) const {
9828   return Op.getOperand(0);
9829 }
9830
9831 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9832                                                 SelectionDAG &DAG) const {
9833   SDValue Root = Op.getOperand(0);
9834   SDValue Trmp = Op.getOperand(1); // trampoline
9835   SDValue FPtr = Op.getOperand(2); // nested function
9836   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9837   DebugLoc dl  = Op.getDebugLoc();
9838
9839   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9840
9841   if (Subtarget->is64Bit()) {
9842     SDValue OutChains[6];
9843
9844     // Large code-model.
9845     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9846     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9847
9848     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9849     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9850
9851     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9852
9853     // Load the pointer to the nested function into R11.
9854     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9855     SDValue Addr = Trmp;
9856     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9857                                 Addr, MachinePointerInfo(TrmpAddr),
9858                                 false, false, 0);
9859
9860     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9861                        DAG.getConstant(2, MVT::i64));
9862     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9863                                 MachinePointerInfo(TrmpAddr, 2),
9864                                 false, false, 2);
9865
9866     // Load the 'nest' parameter value into R10.
9867     // R10 is specified in X86CallingConv.td
9868     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9869     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9870                        DAG.getConstant(10, MVT::i64));
9871     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9872                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9873                                 false, false, 0);
9874
9875     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9876                        DAG.getConstant(12, MVT::i64));
9877     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9878                                 MachinePointerInfo(TrmpAddr, 12),
9879                                 false, false, 2);
9880
9881     // Jump to the nested function.
9882     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9883     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9884                        DAG.getConstant(20, MVT::i64));
9885     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9886                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9887                                 false, false, 0);
9888
9889     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9890     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9891                        DAG.getConstant(22, MVT::i64));
9892     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9893                                 MachinePointerInfo(TrmpAddr, 22),
9894                                 false, false, 0);
9895
9896     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9897   } else {
9898     const Function *Func =
9899       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9900     CallingConv::ID CC = Func->getCallingConv();
9901     unsigned NestReg;
9902
9903     switch (CC) {
9904     default:
9905       llvm_unreachable("Unsupported calling convention");
9906     case CallingConv::C:
9907     case CallingConv::X86_StdCall: {
9908       // Pass 'nest' parameter in ECX.
9909       // Must be kept in sync with X86CallingConv.td
9910       NestReg = X86::ECX;
9911
9912       // Check that ECX wasn't needed by an 'inreg' parameter.
9913       FunctionType *FTy = Func->getFunctionType();
9914       const AttrListPtr &Attrs = Func->getAttributes();
9915
9916       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9917         unsigned InRegCount = 0;
9918         unsigned Idx = 1;
9919
9920         for (FunctionType::param_iterator I = FTy->param_begin(),
9921              E = FTy->param_end(); I != E; ++I, ++Idx)
9922           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9923             // FIXME: should only count parameters that are lowered to integers.
9924             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9925
9926         if (InRegCount > 2) {
9927           report_fatal_error("Nest register in use - reduce number of inreg"
9928                              " parameters!");
9929         }
9930       }
9931       break;
9932     }
9933     case CallingConv::X86_FastCall:
9934     case CallingConv::X86_ThisCall:
9935     case CallingConv::Fast:
9936       // Pass 'nest' parameter in EAX.
9937       // Must be kept in sync with X86CallingConv.td
9938       NestReg = X86::EAX;
9939       break;
9940     }
9941
9942     SDValue OutChains[4];
9943     SDValue Addr, Disp;
9944
9945     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9946                        DAG.getConstant(10, MVT::i32));
9947     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9948
9949     // This is storing the opcode for MOV32ri.
9950     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9951     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9952     OutChains[0] = DAG.getStore(Root, dl,
9953                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9954                                 Trmp, MachinePointerInfo(TrmpAddr),
9955                                 false, false, 0);
9956
9957     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9958                        DAG.getConstant(1, MVT::i32));
9959     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9960                                 MachinePointerInfo(TrmpAddr, 1),
9961                                 false, false, 1);
9962
9963     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9964     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9965                        DAG.getConstant(5, MVT::i32));
9966     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9967                                 MachinePointerInfo(TrmpAddr, 5),
9968                                 false, false, 1);
9969
9970     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9971                        DAG.getConstant(6, MVT::i32));
9972     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9973                                 MachinePointerInfo(TrmpAddr, 6),
9974                                 false, false, 1);
9975
9976     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9977   }
9978 }
9979
9980 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9981                                             SelectionDAG &DAG) const {
9982   /*
9983    The rounding mode is in bits 11:10 of FPSR, and has the following
9984    settings:
9985      00 Round to nearest
9986      01 Round to -inf
9987      10 Round to +inf
9988      11 Round to 0
9989
9990   FLT_ROUNDS, on the other hand, expects the following:
9991     -1 Undefined
9992      0 Round to 0
9993      1 Round to nearest
9994      2 Round to +inf
9995      3 Round to -inf
9996
9997   To perform the conversion, we do:
9998     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9999   */
10000
10001   MachineFunction &MF = DAG.getMachineFunction();
10002   const TargetMachine &TM = MF.getTarget();
10003   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10004   unsigned StackAlignment = TFI.getStackAlignment();
10005   EVT VT = Op.getValueType();
10006   DebugLoc DL = Op.getDebugLoc();
10007
10008   // Save FP Control Word to stack slot
10009   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10010   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10011
10012
10013   MachineMemOperand *MMO =
10014    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10015                            MachineMemOperand::MOStore, 2, 2);
10016
10017   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10018   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10019                                           DAG.getVTList(MVT::Other),
10020                                           Ops, 2, MVT::i16, MMO);
10021
10022   // Load FP Control Word from stack slot
10023   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10024                             MachinePointerInfo(), false, false, false, 0);
10025
10026   // Transform as necessary
10027   SDValue CWD1 =
10028     DAG.getNode(ISD::SRL, DL, MVT::i16,
10029                 DAG.getNode(ISD::AND, DL, MVT::i16,
10030                             CWD, DAG.getConstant(0x800, MVT::i16)),
10031                 DAG.getConstant(11, MVT::i8));
10032   SDValue CWD2 =
10033     DAG.getNode(ISD::SRL, DL, MVT::i16,
10034                 DAG.getNode(ISD::AND, DL, MVT::i16,
10035                             CWD, DAG.getConstant(0x400, MVT::i16)),
10036                 DAG.getConstant(9, MVT::i8));
10037
10038   SDValue RetVal =
10039     DAG.getNode(ISD::AND, DL, MVT::i16,
10040                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10041                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10042                             DAG.getConstant(1, MVT::i16)),
10043                 DAG.getConstant(3, MVT::i16));
10044
10045
10046   return DAG.getNode((VT.getSizeInBits() < 16 ?
10047                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10048 }
10049
10050 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10051   EVT VT = Op.getValueType();
10052   EVT OpVT = VT;
10053   unsigned NumBits = VT.getSizeInBits();
10054   DebugLoc dl = Op.getDebugLoc();
10055
10056   Op = Op.getOperand(0);
10057   if (VT == MVT::i8) {
10058     // Zero extend to i32 since there is not an i8 bsr.
10059     OpVT = MVT::i32;
10060     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10061   }
10062
10063   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10064   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10065   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10066
10067   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10068   SDValue Ops[] = {
10069     Op,
10070     DAG.getConstant(NumBits+NumBits-1, OpVT),
10071     DAG.getConstant(X86::COND_E, MVT::i8),
10072     Op.getValue(1)
10073   };
10074   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10075
10076   // Finally xor with NumBits-1.
10077   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10078
10079   if (VT == MVT::i8)
10080     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10081   return Op;
10082 }
10083
10084 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10085                                                 SelectionDAG &DAG) const {
10086   EVT VT = Op.getValueType();
10087   EVT OpVT = VT;
10088   unsigned NumBits = VT.getSizeInBits();
10089   DebugLoc dl = Op.getDebugLoc();
10090
10091   Op = Op.getOperand(0);
10092   if (VT == MVT::i8) {
10093     // Zero extend to i32 since there is not an i8 bsr.
10094     OpVT = MVT::i32;
10095     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10096   }
10097
10098   // Issue a bsr (scan bits in reverse).
10099   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10100   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10101
10102   // And xor with NumBits-1.
10103   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10104
10105   if (VT == MVT::i8)
10106     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10107   return Op;
10108 }
10109
10110 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10111   EVT VT = Op.getValueType();
10112   unsigned NumBits = VT.getSizeInBits();
10113   DebugLoc dl = Op.getDebugLoc();
10114   Op = Op.getOperand(0);
10115
10116   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10117   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10118   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10119
10120   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10121   SDValue Ops[] = {
10122     Op,
10123     DAG.getConstant(NumBits, VT),
10124     DAG.getConstant(X86::COND_E, MVT::i8),
10125     Op.getValue(1)
10126   };
10127   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10128 }
10129
10130 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10131 // ones, and then concatenate the result back.
10132 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10133   EVT VT = Op.getValueType();
10134
10135   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10136          "Unsupported value type for operation");
10137
10138   int NumElems = VT.getVectorNumElements();
10139   DebugLoc dl = Op.getDebugLoc();
10140
10141   // Extract the LHS vectors
10142   SDValue LHS = Op.getOperand(0);
10143   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10144   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10145
10146   // Extract the RHS vectors
10147   SDValue RHS = Op.getOperand(1);
10148   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10149   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10150
10151   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10152   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10153
10154   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10155                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10156                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10157 }
10158
10159 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10160   assert(Op.getValueType().getSizeInBits() == 256 &&
10161          Op.getValueType().isInteger() &&
10162          "Only handle AVX 256-bit vector integer operation");
10163   return Lower256IntArith(Op, DAG);
10164 }
10165
10166 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10167   assert(Op.getValueType().getSizeInBits() == 256 &&
10168          Op.getValueType().isInteger() &&
10169          "Only handle AVX 256-bit vector integer operation");
10170   return Lower256IntArith(Op, DAG);
10171 }
10172
10173 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10174   EVT VT = Op.getValueType();
10175
10176   // Decompose 256-bit ops into smaller 128-bit ops.
10177   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10178     return Lower256IntArith(Op, DAG);
10179
10180   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10181          "Only know how to lower V2I64/V4I64 multiply");
10182
10183   DebugLoc dl = Op.getDebugLoc();
10184
10185   //  Ahi = psrlqi(a, 32);
10186   //  Bhi = psrlqi(b, 32);
10187   //
10188   //  AloBlo = pmuludq(a, b);
10189   //  AloBhi = pmuludq(a, Bhi);
10190   //  AhiBlo = pmuludq(Ahi, b);
10191
10192   //  AloBhi = psllqi(AloBhi, 32);
10193   //  AhiBlo = psllqi(AhiBlo, 32);
10194   //  return AloBlo + AloBhi + AhiBlo;
10195
10196   SDValue A = Op.getOperand(0);
10197   SDValue B = Op.getOperand(1);
10198
10199   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10200
10201   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10202   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10203
10204   // Bit cast to 32-bit vectors for MULUDQ
10205   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10206   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10207   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10208   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10209   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10210
10211   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10212   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10213   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10214
10215   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10216   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10217
10218   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10219   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10220 }
10221
10222 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10223
10224   EVT VT = Op.getValueType();
10225   DebugLoc dl = Op.getDebugLoc();
10226   SDValue R = Op.getOperand(0);
10227   SDValue Amt = Op.getOperand(1);
10228   LLVMContext *Context = DAG.getContext();
10229
10230   if (!Subtarget->hasSSE2())
10231     return SDValue();
10232
10233   // Optimize shl/srl/sra with constant shift amount.
10234   if (isSplatVector(Amt.getNode())) {
10235     SDValue SclrAmt = Amt->getOperand(0);
10236     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10237       uint64_t ShiftAmt = C->getZExtValue();
10238
10239       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10240           (Subtarget->hasAVX2() &&
10241            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10242         if (Op.getOpcode() == ISD::SHL)
10243           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10244                              DAG.getConstant(ShiftAmt, MVT::i32));
10245         if (Op.getOpcode() == ISD::SRL)
10246           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10247                              DAG.getConstant(ShiftAmt, MVT::i32));
10248         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10249           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10250                              DAG.getConstant(ShiftAmt, MVT::i32));
10251       }
10252
10253       if (VT == MVT::v16i8) {
10254         if (Op.getOpcode() == ISD::SHL) {
10255           // Make a large shift.
10256           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10257                                     DAG.getConstant(ShiftAmt, MVT::i32));
10258           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10259           // Zero out the rightmost bits.
10260           SmallVector<SDValue, 16> V(16,
10261                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10262                                                      MVT::i8));
10263           return DAG.getNode(ISD::AND, dl, VT, SHL,
10264                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10265         }
10266         if (Op.getOpcode() == ISD::SRL) {
10267           // Make a large shift.
10268           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10269                                     DAG.getConstant(ShiftAmt, MVT::i32));
10270           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10271           // Zero out the leftmost bits.
10272           SmallVector<SDValue, 16> V(16,
10273                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10274                                                      MVT::i8));
10275           return DAG.getNode(ISD::AND, dl, VT, SRL,
10276                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10277         }
10278         if (Op.getOpcode() == ISD::SRA) {
10279           if (ShiftAmt == 7) {
10280             // R s>> 7  ===  R s< 0
10281             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10282             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10283           }
10284
10285           // R s>> a === ((R u>> a) ^ m) - m
10286           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10287           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10288                                                          MVT::i8));
10289           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10290           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10291           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10292           return Res;
10293         }
10294         llvm_unreachable("Unknown shift opcode.");
10295       }
10296
10297       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10298         if (Op.getOpcode() == ISD::SHL) {
10299           // Make a large shift.
10300           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10301                                     DAG.getConstant(ShiftAmt, MVT::i32));
10302           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10303           // Zero out the rightmost bits.
10304           SmallVector<SDValue, 32> V(32,
10305                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
10306                                                      MVT::i8));
10307           return DAG.getNode(ISD::AND, dl, VT, SHL,
10308                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10309         }
10310         if (Op.getOpcode() == ISD::SRL) {
10311           // Make a large shift.
10312           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10313                                     DAG.getConstant(ShiftAmt, MVT::i32));
10314           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10315           // Zero out the leftmost bits.
10316           SmallVector<SDValue, 32> V(32,
10317                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10318                                                      MVT::i8));
10319           return DAG.getNode(ISD::AND, dl, VT, SRL,
10320                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10321         }
10322         if (Op.getOpcode() == ISD::SRA) {
10323           if (ShiftAmt == 7) {
10324             // R s>> 7  ===  R s< 0
10325             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10326             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10327           }
10328
10329           // R s>> a === ((R u>> a) ^ m) - m
10330           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10331           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10332                                                          MVT::i8));
10333           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10334           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10335           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10336           return Res;
10337         }
10338         llvm_unreachable("Unknown shift opcode.");
10339       }
10340     }
10341   }
10342
10343   // Lower SHL with variable shift amount.
10344   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10345     Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10346                      DAG.getConstant(23, MVT::i32));
10347
10348     const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10349     Constant *C = ConstantDataVector::get(*Context, CV);
10350     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10351     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10352                                  MachinePointerInfo::getConstantPool(),
10353                                  false, false, false, 16);
10354
10355     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10356     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10357     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10358     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10359   }
10360   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10361     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10362
10363     // a = a << 5;
10364     Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10365                      DAG.getConstant(5, MVT::i32));
10366     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10367
10368     // Turn 'a' into a mask suitable for VSELECT
10369     SDValue VSelM = DAG.getConstant(0x80, VT);
10370     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10371     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10372
10373     SDValue CM1 = DAG.getConstant(0x0f, VT);
10374     SDValue CM2 = DAG.getConstant(0x3f, VT);
10375
10376     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10377     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10378     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10379                             DAG.getConstant(4, MVT::i32), DAG);
10380     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10381     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10382
10383     // a += a
10384     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10385     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10386     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10387
10388     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10389     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10390     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10391                             DAG.getConstant(2, MVT::i32), DAG);
10392     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10393     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10394
10395     // a += a
10396     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10397     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10398     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10399
10400     // return VSELECT(r, r+r, a);
10401     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10402                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10403     return R;
10404   }
10405
10406   // Decompose 256-bit shifts into smaller 128-bit shifts.
10407   if (VT.getSizeInBits() == 256) {
10408     unsigned NumElems = VT.getVectorNumElements();
10409     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10410     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10411
10412     // Extract the two vectors
10413     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10414     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10415
10416     // Recreate the shift amount vectors
10417     SDValue Amt1, Amt2;
10418     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10419       // Constant shift amount
10420       SmallVector<SDValue, 4> Amt1Csts;
10421       SmallVector<SDValue, 4> Amt2Csts;
10422       for (unsigned i = 0; i != NumElems/2; ++i)
10423         Amt1Csts.push_back(Amt->getOperand(i));
10424       for (unsigned i = NumElems/2; i != NumElems; ++i)
10425         Amt2Csts.push_back(Amt->getOperand(i));
10426
10427       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10428                                  &Amt1Csts[0], NumElems/2);
10429       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10430                                  &Amt2Csts[0], NumElems/2);
10431     } else {
10432       // Variable shift amount
10433       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10434       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10435     }
10436
10437     // Issue new vector shifts for the smaller types
10438     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10439     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10440
10441     // Concatenate the result back
10442     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10443   }
10444
10445   return SDValue();
10446 }
10447
10448 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10449   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10450   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10451   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10452   // has only one use.
10453   SDNode *N = Op.getNode();
10454   SDValue LHS = N->getOperand(0);
10455   SDValue RHS = N->getOperand(1);
10456   unsigned BaseOp = 0;
10457   unsigned Cond = 0;
10458   DebugLoc DL = Op.getDebugLoc();
10459   switch (Op.getOpcode()) {
10460   default: llvm_unreachable("Unknown ovf instruction!");
10461   case ISD::SADDO:
10462     // A subtract of one will be selected as a INC. Note that INC doesn't
10463     // set CF, so we can't do this for UADDO.
10464     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10465       if (C->isOne()) {
10466         BaseOp = X86ISD::INC;
10467         Cond = X86::COND_O;
10468         break;
10469       }
10470     BaseOp = X86ISD::ADD;
10471     Cond = X86::COND_O;
10472     break;
10473   case ISD::UADDO:
10474     BaseOp = X86ISD::ADD;
10475     Cond = X86::COND_B;
10476     break;
10477   case ISD::SSUBO:
10478     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10479     // set CF, so we can't do this for USUBO.
10480     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10481       if (C->isOne()) {
10482         BaseOp = X86ISD::DEC;
10483         Cond = X86::COND_O;
10484         break;
10485       }
10486     BaseOp = X86ISD::SUB;
10487     Cond = X86::COND_O;
10488     break;
10489   case ISD::USUBO:
10490     BaseOp = X86ISD::SUB;
10491     Cond = X86::COND_B;
10492     break;
10493   case ISD::SMULO:
10494     BaseOp = X86ISD::SMUL;
10495     Cond = X86::COND_O;
10496     break;
10497   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10498     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10499                                  MVT::i32);
10500     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10501
10502     SDValue SetCC =
10503       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10504                   DAG.getConstant(X86::COND_O, MVT::i32),
10505                   SDValue(Sum.getNode(), 2));
10506
10507     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10508   }
10509   }
10510
10511   // Also sets EFLAGS.
10512   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10513   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10514
10515   SDValue SetCC =
10516     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10517                 DAG.getConstant(Cond, MVT::i32),
10518                 SDValue(Sum.getNode(), 1));
10519
10520   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10521 }
10522
10523 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10524                                                   SelectionDAG &DAG) const {
10525   DebugLoc dl = Op.getDebugLoc();
10526   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10527   EVT VT = Op.getValueType();
10528
10529   if (!Subtarget->hasSSE2() || !VT.isVector())
10530     return SDValue();
10531
10532   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10533                       ExtraVT.getScalarType().getSizeInBits();
10534   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10535
10536   switch (VT.getSimpleVT().SimpleTy) {
10537     default: return SDValue();
10538     case MVT::v8i32:
10539     case MVT::v16i16:
10540       if (!Subtarget->hasAVX())
10541         return SDValue();
10542       if (!Subtarget->hasAVX2()) {
10543         // needs to be split
10544         int NumElems = VT.getVectorNumElements();
10545
10546         // Extract the LHS vectors
10547         SDValue LHS = Op.getOperand(0);
10548         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10549         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10550
10551         MVT EltVT = VT.getVectorElementType().getSimpleVT();
10552         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10553
10554         EVT ExtraEltVT = ExtraVT.getVectorElementType();
10555         int ExtraNumElems = ExtraVT.getVectorNumElements();
10556         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10557                                    ExtraNumElems/2);
10558         SDValue Extra = DAG.getValueType(ExtraVT);
10559
10560         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10561         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10562
10563         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10564       }
10565       // fall through
10566     case MVT::v4i32:
10567     case MVT::v8i16: {
10568       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10569                                          Op.getOperand(0), ShAmt, DAG);
10570       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10571     }
10572   }
10573 }
10574
10575
10576 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10577   DebugLoc dl = Op.getDebugLoc();
10578
10579   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10580   // There isn't any reason to disable it if the target processor supports it.
10581   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10582     SDValue Chain = Op.getOperand(0);
10583     SDValue Zero = DAG.getConstant(0, MVT::i32);
10584     SDValue Ops[] = {
10585       DAG.getRegister(X86::ESP, MVT::i32), // Base
10586       DAG.getTargetConstant(1, MVT::i8),   // Scale
10587       DAG.getRegister(0, MVT::i32),        // Index
10588       DAG.getTargetConstant(0, MVT::i32),  // Disp
10589       DAG.getRegister(0, MVT::i32),        // Segment.
10590       Zero,
10591       Chain
10592     };
10593     SDNode *Res =
10594       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10595                           array_lengthof(Ops));
10596     return SDValue(Res, 0);
10597   }
10598
10599   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10600   if (!isDev)
10601     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10602
10603   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10604   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10605   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10606   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10607
10608   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10609   if (!Op1 && !Op2 && !Op3 && Op4)
10610     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10611
10612   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10613   if (Op1 && !Op2 && !Op3 && !Op4)
10614     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10615
10616   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10617   //           (MFENCE)>;
10618   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10619 }
10620
10621 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10622                                              SelectionDAG &DAG) const {
10623   DebugLoc dl = Op.getDebugLoc();
10624   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10625     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10626   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10627     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10628
10629   // The only fence that needs an instruction is a sequentially-consistent
10630   // cross-thread fence.
10631   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10632     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10633     // no-sse2). There isn't any reason to disable it if the target processor
10634     // supports it.
10635     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10636       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10637
10638     SDValue Chain = Op.getOperand(0);
10639     SDValue Zero = DAG.getConstant(0, MVT::i32);
10640     SDValue Ops[] = {
10641       DAG.getRegister(X86::ESP, MVT::i32), // Base
10642       DAG.getTargetConstant(1, MVT::i8),   // Scale
10643       DAG.getRegister(0, MVT::i32),        // Index
10644       DAG.getTargetConstant(0, MVT::i32),  // Disp
10645       DAG.getRegister(0, MVT::i32),        // Segment.
10646       Zero,
10647       Chain
10648     };
10649     SDNode *Res =
10650       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10651                          array_lengthof(Ops));
10652     return SDValue(Res, 0);
10653   }
10654
10655   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10656   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10657 }
10658
10659
10660 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10661   EVT T = Op.getValueType();
10662   DebugLoc DL = Op.getDebugLoc();
10663   unsigned Reg = 0;
10664   unsigned size = 0;
10665   switch(T.getSimpleVT().SimpleTy) {
10666   default: llvm_unreachable("Invalid value type!");
10667   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10668   case MVT::i16: Reg = X86::AX;  size = 2; break;
10669   case MVT::i32: Reg = X86::EAX; size = 4; break;
10670   case MVT::i64:
10671     assert(Subtarget->is64Bit() && "Node not type legal!");
10672     Reg = X86::RAX; size = 8;
10673     break;
10674   }
10675   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10676                                     Op.getOperand(2), SDValue());
10677   SDValue Ops[] = { cpIn.getValue(0),
10678                     Op.getOperand(1),
10679                     Op.getOperand(3),
10680                     DAG.getTargetConstant(size, MVT::i8),
10681                     cpIn.getValue(1) };
10682   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10683   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10684   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10685                                            Ops, 5, T, MMO);
10686   SDValue cpOut =
10687     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10688   return cpOut;
10689 }
10690
10691 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10692                                                  SelectionDAG &DAG) const {
10693   assert(Subtarget->is64Bit() && "Result not type legalized?");
10694   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10695   SDValue TheChain = Op.getOperand(0);
10696   DebugLoc dl = Op.getDebugLoc();
10697   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10698   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10699   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10700                                    rax.getValue(2));
10701   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10702                             DAG.getConstant(32, MVT::i8));
10703   SDValue Ops[] = {
10704     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10705     rdx.getValue(1)
10706   };
10707   return DAG.getMergeValues(Ops, 2, dl);
10708 }
10709
10710 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10711                                             SelectionDAG &DAG) const {
10712   EVT SrcVT = Op.getOperand(0).getValueType();
10713   EVT DstVT = Op.getValueType();
10714   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10715          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10716   assert((DstVT == MVT::i64 ||
10717           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10718          "Unexpected custom BITCAST");
10719   // i64 <=> MMX conversions are Legal.
10720   if (SrcVT==MVT::i64 && DstVT.isVector())
10721     return Op;
10722   if (DstVT==MVT::i64 && SrcVT.isVector())
10723     return Op;
10724   // MMX <=> MMX conversions are Legal.
10725   if (SrcVT.isVector() && DstVT.isVector())
10726     return Op;
10727   // All other conversions need to be expanded.
10728   return SDValue();
10729 }
10730
10731 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10732   SDNode *Node = Op.getNode();
10733   DebugLoc dl = Node->getDebugLoc();
10734   EVT T = Node->getValueType(0);
10735   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10736                               DAG.getConstant(0, T), Node->getOperand(2));
10737   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10738                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10739                        Node->getOperand(0),
10740                        Node->getOperand(1), negOp,
10741                        cast<AtomicSDNode>(Node)->getSrcValue(),
10742                        cast<AtomicSDNode>(Node)->getAlignment(),
10743                        cast<AtomicSDNode>(Node)->getOrdering(),
10744                        cast<AtomicSDNode>(Node)->getSynchScope());
10745 }
10746
10747 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10748   SDNode *Node = Op.getNode();
10749   DebugLoc dl = Node->getDebugLoc();
10750   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10751
10752   // Convert seq_cst store -> xchg
10753   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10754   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10755   //        (The only way to get a 16-byte store is cmpxchg16b)
10756   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10757   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10758       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10759     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10760                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10761                                  Node->getOperand(0),
10762                                  Node->getOperand(1), Node->getOperand(2),
10763                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10764                                  cast<AtomicSDNode>(Node)->getOrdering(),
10765                                  cast<AtomicSDNode>(Node)->getSynchScope());
10766     return Swap.getValue(1);
10767   }
10768   // Other atomic stores have a simple pattern.
10769   return Op;
10770 }
10771
10772 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10773   EVT VT = Op.getNode()->getValueType(0);
10774
10775   // Let legalize expand this if it isn't a legal type yet.
10776   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10777     return SDValue();
10778
10779   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10780
10781   unsigned Opc;
10782   bool ExtraOp = false;
10783   switch (Op.getOpcode()) {
10784   default: llvm_unreachable("Invalid code");
10785   case ISD::ADDC: Opc = X86ISD::ADD; break;
10786   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10787   case ISD::SUBC: Opc = X86ISD::SUB; break;
10788   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10789   }
10790
10791   if (!ExtraOp)
10792     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10793                        Op.getOperand(1));
10794   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10795                      Op.getOperand(1), Op.getOperand(2));
10796 }
10797
10798 /// LowerOperation - Provide custom lowering hooks for some operations.
10799 ///
10800 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10801   switch (Op.getOpcode()) {
10802   default: llvm_unreachable("Should not custom lower this!");
10803   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10804   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10805   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10806   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10807   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10808   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10809   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10810   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10811   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10812   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10813   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10814   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10815   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10816   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10817   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10818   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10819   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10820   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10821   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10822   case ISD::SHL_PARTS:
10823   case ISD::SRA_PARTS:
10824   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10825   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10826   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10827   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10828   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10829   case ISD::FABS:               return LowerFABS(Op, DAG);
10830   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10831   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10832   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10833   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10834   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10835   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10836   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10837   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10838   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10839   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10840   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10841   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10842   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10843   case ISD::FRAME_TO_ARGS_OFFSET:
10844                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10845   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10846   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10847   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10848   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10849   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10850   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10851   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
10852   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10853   case ISD::MUL:                return LowerMUL(Op, DAG);
10854   case ISD::SRA:
10855   case ISD::SRL:
10856   case ISD::SHL:                return LowerShift(Op, DAG);
10857   case ISD::SADDO:
10858   case ISD::UADDO:
10859   case ISD::SSUBO:
10860   case ISD::USUBO:
10861   case ISD::SMULO:
10862   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10863   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10864   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10865   case ISD::ADDC:
10866   case ISD::ADDE:
10867   case ISD::SUBC:
10868   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10869   case ISD::ADD:                return LowerADD(Op, DAG);
10870   case ISD::SUB:                return LowerSUB(Op, DAG);
10871   }
10872 }
10873
10874 static void ReplaceATOMIC_LOAD(SDNode *Node,
10875                                   SmallVectorImpl<SDValue> &Results,
10876                                   SelectionDAG &DAG) {
10877   DebugLoc dl = Node->getDebugLoc();
10878   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10879
10880   // Convert wide load -> cmpxchg8b/cmpxchg16b
10881   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10882   //        (The only way to get a 16-byte load is cmpxchg16b)
10883   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10884   SDValue Zero = DAG.getConstant(0, VT);
10885   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10886                                Node->getOperand(0),
10887                                Node->getOperand(1), Zero, Zero,
10888                                cast<AtomicSDNode>(Node)->getMemOperand(),
10889                                cast<AtomicSDNode>(Node)->getOrdering(),
10890                                cast<AtomicSDNode>(Node)->getSynchScope());
10891   Results.push_back(Swap.getValue(0));
10892   Results.push_back(Swap.getValue(1));
10893 }
10894
10895 void X86TargetLowering::
10896 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10897                         SelectionDAG &DAG, unsigned NewOp) const {
10898   DebugLoc dl = Node->getDebugLoc();
10899   assert (Node->getValueType(0) == MVT::i64 &&
10900           "Only know how to expand i64 atomics");
10901
10902   SDValue Chain = Node->getOperand(0);
10903   SDValue In1 = Node->getOperand(1);
10904   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10905                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10906   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10907                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10908   SDValue Ops[] = { Chain, In1, In2L, In2H };
10909   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10910   SDValue Result =
10911     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10912                             cast<MemSDNode>(Node)->getMemOperand());
10913   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10914   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10915   Results.push_back(Result.getValue(2));
10916 }
10917
10918 /// ReplaceNodeResults - Replace a node with an illegal result type
10919 /// with a new node built out of custom code.
10920 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10921                                            SmallVectorImpl<SDValue>&Results,
10922                                            SelectionDAG &DAG) const {
10923   DebugLoc dl = N->getDebugLoc();
10924   switch (N->getOpcode()) {
10925   default:
10926     llvm_unreachable("Do not know how to custom type legalize this operation!");
10927   case ISD::SIGN_EXTEND_INREG:
10928   case ISD::ADDC:
10929   case ISD::ADDE:
10930   case ISD::SUBC:
10931   case ISD::SUBE:
10932     // We don't want to expand or promote these.
10933     return;
10934   case ISD::FP_TO_SINT:
10935   case ISD::FP_TO_UINT: {
10936     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
10937
10938     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
10939       return;
10940
10941     std::pair<SDValue,SDValue> Vals =
10942         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
10943     SDValue FIST = Vals.first, StackSlot = Vals.second;
10944     if (FIST.getNode() != 0) {
10945       EVT VT = N->getValueType(0);
10946       // Return a load from the stack slot.
10947       if (StackSlot.getNode() != 0)
10948         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10949                                       MachinePointerInfo(),
10950                                       false, false, false, 0));
10951       else
10952         Results.push_back(FIST);
10953     }
10954     return;
10955   }
10956   case ISD::READCYCLECOUNTER: {
10957     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10958     SDValue TheChain = N->getOperand(0);
10959     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10960     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10961                                      rd.getValue(1));
10962     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10963                                      eax.getValue(2));
10964     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10965     SDValue Ops[] = { eax, edx };
10966     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10967     Results.push_back(edx.getValue(1));
10968     return;
10969   }
10970   case ISD::ATOMIC_CMP_SWAP: {
10971     EVT T = N->getValueType(0);
10972     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10973     bool Regs64bit = T == MVT::i128;
10974     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10975     SDValue cpInL, cpInH;
10976     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10977                         DAG.getConstant(0, HalfT));
10978     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10979                         DAG.getConstant(1, HalfT));
10980     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10981                              Regs64bit ? X86::RAX : X86::EAX,
10982                              cpInL, SDValue());
10983     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10984                              Regs64bit ? X86::RDX : X86::EDX,
10985                              cpInH, cpInL.getValue(1));
10986     SDValue swapInL, swapInH;
10987     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10988                           DAG.getConstant(0, HalfT));
10989     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10990                           DAG.getConstant(1, HalfT));
10991     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10992                                Regs64bit ? X86::RBX : X86::EBX,
10993                                swapInL, cpInH.getValue(1));
10994     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10995                                Regs64bit ? X86::RCX : X86::ECX, 
10996                                swapInH, swapInL.getValue(1));
10997     SDValue Ops[] = { swapInH.getValue(0),
10998                       N->getOperand(1),
10999                       swapInH.getValue(1) };
11000     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11001     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11002     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11003                                   X86ISD::LCMPXCHG8_DAG;
11004     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11005                                              Ops, 3, T, MMO);
11006     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11007                                         Regs64bit ? X86::RAX : X86::EAX,
11008                                         HalfT, Result.getValue(1));
11009     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11010                                         Regs64bit ? X86::RDX : X86::EDX,
11011                                         HalfT, cpOutL.getValue(2));
11012     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11013     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11014     Results.push_back(cpOutH.getValue(1));
11015     return;
11016   }
11017   case ISD::ATOMIC_LOAD_ADD:
11018     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11019     return;
11020   case ISD::ATOMIC_LOAD_AND:
11021     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11022     return;
11023   case ISD::ATOMIC_LOAD_NAND:
11024     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11025     return;
11026   case ISD::ATOMIC_LOAD_OR:
11027     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11028     return;
11029   case ISD::ATOMIC_LOAD_SUB:
11030     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11031     return;
11032   case ISD::ATOMIC_LOAD_XOR:
11033     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11034     return;
11035   case ISD::ATOMIC_SWAP:
11036     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11037     return;
11038   case ISD::ATOMIC_LOAD:
11039     ReplaceATOMIC_LOAD(N, Results, DAG);
11040   }
11041 }
11042
11043 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11044   switch (Opcode) {
11045   default: return NULL;
11046   case X86ISD::BSF:                return "X86ISD::BSF";
11047   case X86ISD::BSR:                return "X86ISD::BSR";
11048   case X86ISD::SHLD:               return "X86ISD::SHLD";
11049   case X86ISD::SHRD:               return "X86ISD::SHRD";
11050   case X86ISD::FAND:               return "X86ISD::FAND";
11051   case X86ISD::FOR:                return "X86ISD::FOR";
11052   case X86ISD::FXOR:               return "X86ISD::FXOR";
11053   case X86ISD::FSRL:               return "X86ISD::FSRL";
11054   case X86ISD::FILD:               return "X86ISD::FILD";
11055   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11056   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11057   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11058   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11059   case X86ISD::FLD:                return "X86ISD::FLD";
11060   case X86ISD::FST:                return "X86ISD::FST";
11061   case X86ISD::CALL:               return "X86ISD::CALL";
11062   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11063   case X86ISD::BT:                 return "X86ISD::BT";
11064   case X86ISD::CMP:                return "X86ISD::CMP";
11065   case X86ISD::COMI:               return "X86ISD::COMI";
11066   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11067   case X86ISD::SETCC:              return "X86ISD::SETCC";
11068   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11069   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11070   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11071   case X86ISD::CMOV:               return "X86ISD::CMOV";
11072   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11073   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11074   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11075   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11076   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11077   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11078   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11079   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11080   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11081   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11082   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11083   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11084   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11085   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11086   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11087   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11088   case X86ISD::BLENDPW:            return "X86ISD::BLENDPW";
11089   case X86ISD::BLENDPS:            return "X86ISD::BLENDPS";
11090   case X86ISD::BLENDPD:            return "X86ISD::BLENDPD";
11091   case X86ISD::HADD:               return "X86ISD::HADD";
11092   case X86ISD::HSUB:               return "X86ISD::HSUB";
11093   case X86ISD::FHADD:              return "X86ISD::FHADD";
11094   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11095   case X86ISD::FMAX:               return "X86ISD::FMAX";
11096   case X86ISD::FMIN:               return "X86ISD::FMIN";
11097   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11098   case X86ISD::FRCP:               return "X86ISD::FRCP";
11099   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11100   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11101   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11102   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11103   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11104   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11105   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11106   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11107   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11108   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11109   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11110   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11111   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11112   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11113   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11114   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
11115   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
11116   case X86ISD::VSHL:               return "X86ISD::VSHL";
11117   case X86ISD::VSRL:               return "X86ISD::VSRL";
11118   case X86ISD::VSRA:               return "X86ISD::VSRA";
11119   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
11120   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
11121   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
11122   case X86ISD::CMPP:               return "X86ISD::CMPP";
11123   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
11124   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
11125   case X86ISD::ADD:                return "X86ISD::ADD";
11126   case X86ISD::SUB:                return "X86ISD::SUB";
11127   case X86ISD::ADC:                return "X86ISD::ADC";
11128   case X86ISD::SBB:                return "X86ISD::SBB";
11129   case X86ISD::SMUL:               return "X86ISD::SMUL";
11130   case X86ISD::UMUL:               return "X86ISD::UMUL";
11131   case X86ISD::INC:                return "X86ISD::INC";
11132   case X86ISD::DEC:                return "X86ISD::DEC";
11133   case X86ISD::OR:                 return "X86ISD::OR";
11134   case X86ISD::XOR:                return "X86ISD::XOR";
11135   case X86ISD::AND:                return "X86ISD::AND";
11136   case X86ISD::ANDN:               return "X86ISD::ANDN";
11137   case X86ISD::BLSI:               return "X86ISD::BLSI";
11138   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11139   case X86ISD::BLSR:               return "X86ISD::BLSR";
11140   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11141   case X86ISD::PTEST:              return "X86ISD::PTEST";
11142   case X86ISD::TESTP:              return "X86ISD::TESTP";
11143   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11144   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11145   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11146   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11147   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
11148   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11149   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11150   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11151   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11152   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11153   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11154   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11155   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11156   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11157   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11158   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
11159   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
11160   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11161   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
11162   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
11163   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
11164   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
11165   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
11166   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11167   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11168   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11169   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11170   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11171   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
11172   }
11173 }
11174
11175 // isLegalAddressingMode - Return true if the addressing mode represented
11176 // by AM is legal for this target, for a load/store of the specified type.
11177 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11178                                               Type *Ty) const {
11179   // X86 supports extremely general addressing modes.
11180   CodeModel::Model M = getTargetMachine().getCodeModel();
11181   Reloc::Model R = getTargetMachine().getRelocationModel();
11182
11183   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11184   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11185     return false;
11186
11187   if (AM.BaseGV) {
11188     unsigned GVFlags =
11189       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11190
11191     // If a reference to this global requires an extra load, we can't fold it.
11192     if (isGlobalStubReference(GVFlags))
11193       return false;
11194
11195     // If BaseGV requires a register for the PIC base, we cannot also have a
11196     // BaseReg specified.
11197     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11198       return false;
11199
11200     // If lower 4G is not available, then we must use rip-relative addressing.
11201     if ((M != CodeModel::Small || R != Reloc::Static) &&
11202         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11203       return false;
11204   }
11205
11206   switch (AM.Scale) {
11207   case 0:
11208   case 1:
11209   case 2:
11210   case 4:
11211   case 8:
11212     // These scales always work.
11213     break;
11214   case 3:
11215   case 5:
11216   case 9:
11217     // These scales are formed with basereg+scalereg.  Only accept if there is
11218     // no basereg yet.
11219     if (AM.HasBaseReg)
11220       return false;
11221     break;
11222   default:  // Other stuff never works.
11223     return false;
11224   }
11225
11226   return true;
11227 }
11228
11229
11230 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11231   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11232     return false;
11233   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11234   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11235   if (NumBits1 <= NumBits2)
11236     return false;
11237   return true;
11238 }
11239
11240 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11241   if (!VT1.isInteger() || !VT2.isInteger())
11242     return false;
11243   unsigned NumBits1 = VT1.getSizeInBits();
11244   unsigned NumBits2 = VT2.getSizeInBits();
11245   if (NumBits1 <= NumBits2)
11246     return false;
11247   return true;
11248 }
11249
11250 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11251   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11252   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11253 }
11254
11255 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11256   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11257   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11258 }
11259
11260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11261   // i16 instructions are longer (0x66 prefix) and potentially slower.
11262   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11263 }
11264
11265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11268 /// are assumed to be legal.
11269 bool
11270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11271                                       EVT VT) const {
11272   // Very little shuffling can be done for 64-bit vectors right now.
11273   if (VT.getSizeInBits() == 64)
11274     return false;
11275
11276   // FIXME: pshufb, blends, shifts.
11277   return (VT.getVectorNumElements() == 2 ||
11278           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11279           isMOVLMask(M, VT) ||
11280           isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11281           isPSHUFDMask(M, VT) ||
11282           isPSHUFHWMask(M, VT) ||
11283           isPSHUFLWMask(M, VT) ||
11284           isPALIGNRMask(M, VT, Subtarget) ||
11285           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11286           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11287           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11288           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11289 }
11290
11291 bool
11292 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11293                                           EVT VT) const {
11294   unsigned NumElts = VT.getVectorNumElements();
11295   // FIXME: This collection of masks seems suspect.
11296   if (NumElts == 2)
11297     return true;
11298   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11299     return (isMOVLMask(Mask, VT)  ||
11300             isCommutedMOVLMask(Mask, VT, true) ||
11301             isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11302             isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11303   }
11304   return false;
11305 }
11306
11307 //===----------------------------------------------------------------------===//
11308 //                           X86 Scheduler Hooks
11309 //===----------------------------------------------------------------------===//
11310
11311 // private utility function
11312 MachineBasicBlock *
11313 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11314                                                        MachineBasicBlock *MBB,
11315                                                        unsigned regOpc,
11316                                                        unsigned immOpc,
11317                                                        unsigned LoadOpc,
11318                                                        unsigned CXchgOpc,
11319                                                        unsigned notOpc,
11320                                                        unsigned EAXreg,
11321                                                  const TargetRegisterClass *RC,
11322                                                        bool Invert) const {
11323   // For the atomic bitwise operator, we generate
11324   //   thisMBB:
11325   //   newMBB:
11326   //     ld  t1 = [bitinstr.addr]
11327   //     op  t2 = t1, [bitinstr.val]
11328   //     not t3 = t2  (if Invert)
11329   //     mov EAX = t1
11330   //     lcs dest = [bitinstr.addr], t3  [EAX is implicit]
11331   //     bz  newMBB
11332   //     fallthrough -->nextMBB
11333   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11334   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11335   MachineFunction::iterator MBBIter = MBB;
11336   ++MBBIter;
11337
11338   /// First build the CFG
11339   MachineFunction *F = MBB->getParent();
11340   MachineBasicBlock *thisMBB = MBB;
11341   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11342   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11343   F->insert(MBBIter, newMBB);
11344   F->insert(MBBIter, nextMBB);
11345
11346   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11347   nextMBB->splice(nextMBB->begin(), thisMBB,
11348                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11349                   thisMBB->end());
11350   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11351
11352   // Update thisMBB to fall through to newMBB
11353   thisMBB->addSuccessor(newMBB);
11354
11355   // newMBB jumps to itself and fall through to nextMBB
11356   newMBB->addSuccessor(nextMBB);
11357   newMBB->addSuccessor(newMBB);
11358
11359   // Insert instructions into newMBB based on incoming instruction
11360   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11361          "unexpected number of operands");
11362   DebugLoc dl = bInstr->getDebugLoc();
11363   MachineOperand& destOper = bInstr->getOperand(0);
11364   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11365   int numArgs = bInstr->getNumOperands() - 1;
11366   for (int i=0; i < numArgs; ++i)
11367     argOpers[i] = &bInstr->getOperand(i+1);
11368
11369   // x86 address has 4 operands: base, index, scale, and displacement
11370   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11371   int valArgIndx = lastAddrIndx + 1;
11372
11373   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11374   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11375   for (int i=0; i <= lastAddrIndx; ++i)
11376     (*MIB).addOperand(*argOpers[i]);
11377
11378   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11379   assert((argOpers[valArgIndx]->isReg() ||
11380           argOpers[valArgIndx]->isImm()) &&
11381          "invalid operand");
11382   if (argOpers[valArgIndx]->isReg())
11383     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11384   else
11385     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11386   MIB.addReg(t1);
11387   (*MIB).addOperand(*argOpers[valArgIndx]);
11388
11389   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11390   if (Invert) {
11391     MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11392   }
11393   else
11394     t3 = t2;
11395
11396   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11397   MIB.addReg(t1);
11398
11399   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11400   for (int i=0; i <= lastAddrIndx; ++i)
11401     (*MIB).addOperand(*argOpers[i]);
11402   MIB.addReg(t3);
11403   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11404   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11405                     bInstr->memoperands_end());
11406
11407   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11408   MIB.addReg(EAXreg);
11409
11410   // insert branch
11411   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11412
11413   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11414   return nextMBB;
11415 }
11416
11417 // private utility function:  64 bit atomics on 32 bit host.
11418 MachineBasicBlock *
11419 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11420                                                        MachineBasicBlock *MBB,
11421                                                        unsigned regOpcL,
11422                                                        unsigned regOpcH,
11423                                                        unsigned immOpcL,
11424                                                        unsigned immOpcH,
11425                                                        bool Invert) const {
11426   // For the atomic bitwise operator, we generate
11427   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11428   //     ld t1,t2 = [bitinstr.addr]
11429   //   newMBB:
11430   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11431   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11432   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11433   //     neg t7, t8 < t5, t6  (if Invert)
11434   //     mov ECX, EBX <- t5, t6
11435   //     mov EAX, EDX <- t1, t2
11436   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11437   //     mov t3, t4 <- EAX, EDX
11438   //     bz  newMBB
11439   //     result in out1, out2
11440   //     fallthrough -->nextMBB
11441
11442   const TargetRegisterClass *RC = &X86::GR32RegClass;
11443   const unsigned LoadOpc = X86::MOV32rm;
11444   const unsigned NotOpc = X86::NOT32r;
11445   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11446   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11447   MachineFunction::iterator MBBIter = MBB;
11448   ++MBBIter;
11449
11450   /// First build the CFG
11451   MachineFunction *F = MBB->getParent();
11452   MachineBasicBlock *thisMBB = MBB;
11453   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11454   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11455   F->insert(MBBIter, newMBB);
11456   F->insert(MBBIter, nextMBB);
11457
11458   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11459   nextMBB->splice(nextMBB->begin(), thisMBB,
11460                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11461                   thisMBB->end());
11462   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11463
11464   // Update thisMBB to fall through to newMBB
11465   thisMBB->addSuccessor(newMBB);
11466
11467   // newMBB jumps to itself and fall through to nextMBB
11468   newMBB->addSuccessor(nextMBB);
11469   newMBB->addSuccessor(newMBB);
11470
11471   DebugLoc dl = bInstr->getDebugLoc();
11472   // Insert instructions into newMBB based on incoming instruction
11473   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11474   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11475          "unexpected number of operands");
11476   MachineOperand& dest1Oper = bInstr->getOperand(0);
11477   MachineOperand& dest2Oper = bInstr->getOperand(1);
11478   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11479   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11480     argOpers[i] = &bInstr->getOperand(i+2);
11481
11482     // We use some of the operands multiple times, so conservatively just
11483     // clear any kill flags that might be present.
11484     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11485       argOpers[i]->setIsKill(false);
11486   }
11487
11488   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11489   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11490
11491   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11492   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11493   for (int i=0; i <= lastAddrIndx; ++i)
11494     (*MIB).addOperand(*argOpers[i]);
11495   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11496   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11497   // add 4 to displacement.
11498   for (int i=0; i <= lastAddrIndx-2; ++i)
11499     (*MIB).addOperand(*argOpers[i]);
11500   MachineOperand newOp3 = *(argOpers[3]);
11501   if (newOp3.isImm())
11502     newOp3.setImm(newOp3.getImm()+4);
11503   else
11504     newOp3.setOffset(newOp3.getOffset()+4);
11505   (*MIB).addOperand(newOp3);
11506   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11507
11508   // t3/4 are defined later, at the bottom of the loop
11509   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11510   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11511   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11512     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11513   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11514     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11515
11516   // The subsequent operations should be using the destination registers of
11517   // the PHI instructions.
11518   t1 = dest1Oper.getReg();
11519   t2 = dest2Oper.getReg();
11520
11521   int valArgIndx = lastAddrIndx + 1;
11522   assert((argOpers[valArgIndx]->isReg() ||
11523           argOpers[valArgIndx]->isImm()) &&
11524          "invalid operand");
11525   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11526   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11527   if (argOpers[valArgIndx]->isReg())
11528     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11529   else
11530     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11531   if (regOpcL != X86::MOV32rr)
11532     MIB.addReg(t1);
11533   (*MIB).addOperand(*argOpers[valArgIndx]);
11534   assert(argOpers[valArgIndx + 1]->isReg() ==
11535          argOpers[valArgIndx]->isReg());
11536   assert(argOpers[valArgIndx + 1]->isImm() ==
11537          argOpers[valArgIndx]->isImm());
11538   if (argOpers[valArgIndx + 1]->isReg())
11539     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11540   else
11541     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11542   if (regOpcH != X86::MOV32rr)
11543     MIB.addReg(t2);
11544   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11545
11546   unsigned t7, t8;
11547   if (Invert) {
11548     t7 = F->getRegInfo().createVirtualRegister(RC);
11549     t8 = F->getRegInfo().createVirtualRegister(RC);
11550     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11551     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11552   } else {
11553     t7 = t5;
11554     t8 = t6;
11555   }
11556
11557   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11558   MIB.addReg(t1);
11559   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11560   MIB.addReg(t2);
11561
11562   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11563   MIB.addReg(t7);
11564   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11565   MIB.addReg(t8);
11566
11567   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11568   for (int i=0; i <= lastAddrIndx; ++i)
11569     (*MIB).addOperand(*argOpers[i]);
11570
11571   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11572   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11573                     bInstr->memoperands_end());
11574
11575   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11576   MIB.addReg(X86::EAX);
11577   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11578   MIB.addReg(X86::EDX);
11579
11580   // insert branch
11581   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11582
11583   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11584   return nextMBB;
11585 }
11586
11587 // private utility function
11588 MachineBasicBlock *
11589 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11590                                                       MachineBasicBlock *MBB,
11591                                                       unsigned cmovOpc) const {
11592   // For the atomic min/max operator, we generate
11593   //   thisMBB:
11594   //   newMBB:
11595   //     ld t1 = [min/max.addr]
11596   //     mov t2 = [min/max.val]
11597   //     cmp  t1, t2
11598   //     cmov[cond] t2 = t1
11599   //     mov EAX = t1
11600   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11601   //     bz   newMBB
11602   //     fallthrough -->nextMBB
11603   //
11604   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11605   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11606   MachineFunction::iterator MBBIter = MBB;
11607   ++MBBIter;
11608
11609   /// First build the CFG
11610   MachineFunction *F = MBB->getParent();
11611   MachineBasicBlock *thisMBB = MBB;
11612   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11613   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11614   F->insert(MBBIter, newMBB);
11615   F->insert(MBBIter, nextMBB);
11616
11617   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11618   nextMBB->splice(nextMBB->begin(), thisMBB,
11619                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11620                   thisMBB->end());
11621   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11622
11623   // Update thisMBB to fall through to newMBB
11624   thisMBB->addSuccessor(newMBB);
11625
11626   // newMBB jumps to newMBB and fall through to nextMBB
11627   newMBB->addSuccessor(nextMBB);
11628   newMBB->addSuccessor(newMBB);
11629
11630   DebugLoc dl = mInstr->getDebugLoc();
11631   // Insert instructions into newMBB based on incoming instruction
11632   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11633          "unexpected number of operands");
11634   MachineOperand& destOper = mInstr->getOperand(0);
11635   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11636   int numArgs = mInstr->getNumOperands() - 1;
11637   for (int i=0; i < numArgs; ++i)
11638     argOpers[i] = &mInstr->getOperand(i+1);
11639
11640   // x86 address has 4 operands: base, index, scale, and displacement
11641   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11642   int valArgIndx = lastAddrIndx + 1;
11643
11644   unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11645   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11646   for (int i=0; i <= lastAddrIndx; ++i)
11647     (*MIB).addOperand(*argOpers[i]);
11648
11649   // We only support register and immediate values
11650   assert((argOpers[valArgIndx]->isReg() ||
11651           argOpers[valArgIndx]->isImm()) &&
11652          "invalid operand");
11653
11654   unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11655   if (argOpers[valArgIndx]->isReg())
11656     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11657   else
11658     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11659   (*MIB).addOperand(*argOpers[valArgIndx]);
11660
11661   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11662   MIB.addReg(t1);
11663
11664   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11665   MIB.addReg(t1);
11666   MIB.addReg(t2);
11667
11668   // Generate movc
11669   unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11670   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11671   MIB.addReg(t2);
11672   MIB.addReg(t1);
11673
11674   // Cmp and exchange if none has modified the memory location
11675   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11676   for (int i=0; i <= lastAddrIndx; ++i)
11677     (*MIB).addOperand(*argOpers[i]);
11678   MIB.addReg(t3);
11679   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11680   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11681                     mInstr->memoperands_end());
11682
11683   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11684   MIB.addReg(X86::EAX);
11685
11686   // insert branch
11687   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11688
11689   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11690   return nextMBB;
11691 }
11692
11693 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11694 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11695 // in the .td file.
11696 MachineBasicBlock *
11697 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11698                             unsigned numArgs, bool memArg) const {
11699   assert(Subtarget->hasSSE42() &&
11700          "Target must have SSE4.2 or AVX features enabled");
11701
11702   DebugLoc dl = MI->getDebugLoc();
11703   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11704   unsigned Opc;
11705   if (!Subtarget->hasAVX()) {
11706     if (memArg)
11707       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11708     else
11709       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11710   } else {
11711     if (memArg)
11712       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11713     else
11714       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11715   }
11716
11717   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11718   for (unsigned i = 0; i < numArgs; ++i) {
11719     MachineOperand &Op = MI->getOperand(i+1);
11720     if (!(Op.isReg() && Op.isImplicit()))
11721       MIB.addOperand(Op);
11722   }
11723   BuildMI(*BB, MI, dl,
11724     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11725              MI->getOperand(0).getReg())
11726     .addReg(X86::XMM0);
11727
11728   MI->eraseFromParent();
11729   return BB;
11730 }
11731
11732 MachineBasicBlock *
11733 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11734   DebugLoc dl = MI->getDebugLoc();
11735   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11736
11737   // Address into RAX/EAX, other two args into ECX, EDX.
11738   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11739   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11740   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11741   for (int i = 0; i < X86::AddrNumOperands; ++i)
11742     MIB.addOperand(MI->getOperand(i));
11743
11744   unsigned ValOps = X86::AddrNumOperands;
11745   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11746     .addReg(MI->getOperand(ValOps).getReg());
11747   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11748     .addReg(MI->getOperand(ValOps+1).getReg());
11749
11750   // The instruction doesn't actually take any operands though.
11751   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11752
11753   MI->eraseFromParent(); // The pseudo is gone now.
11754   return BB;
11755 }
11756
11757 MachineBasicBlock *
11758 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11759   DebugLoc dl = MI->getDebugLoc();
11760   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11761
11762   // First arg in ECX, the second in EAX.
11763   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11764     .addReg(MI->getOperand(0).getReg());
11765   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11766     .addReg(MI->getOperand(1).getReg());
11767
11768   // The instruction doesn't actually take any operands though.
11769   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11770
11771   MI->eraseFromParent(); // The pseudo is gone now.
11772   return BB;
11773 }
11774
11775 MachineBasicBlock *
11776 X86TargetLowering::EmitVAARG64WithCustomInserter(
11777                    MachineInstr *MI,
11778                    MachineBasicBlock *MBB) const {
11779   // Emit va_arg instruction on X86-64.
11780
11781   // Operands to this pseudo-instruction:
11782   // 0  ) Output        : destination address (reg)
11783   // 1-5) Input         : va_list address (addr, i64mem)
11784   // 6  ) ArgSize       : Size (in bytes) of vararg type
11785   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11786   // 8  ) Align         : Alignment of type
11787   // 9  ) EFLAGS (implicit-def)
11788
11789   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11790   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11791
11792   unsigned DestReg = MI->getOperand(0).getReg();
11793   MachineOperand &Base = MI->getOperand(1);
11794   MachineOperand &Scale = MI->getOperand(2);
11795   MachineOperand &Index = MI->getOperand(3);
11796   MachineOperand &Disp = MI->getOperand(4);
11797   MachineOperand &Segment = MI->getOperand(5);
11798   unsigned ArgSize = MI->getOperand(6).getImm();
11799   unsigned ArgMode = MI->getOperand(7).getImm();
11800   unsigned Align = MI->getOperand(8).getImm();
11801
11802   // Memory Reference
11803   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11804   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11805   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11806
11807   // Machine Information
11808   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11809   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11810   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11811   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11812   DebugLoc DL = MI->getDebugLoc();
11813
11814   // struct va_list {
11815   //   i32   gp_offset
11816   //   i32   fp_offset
11817   //   i64   overflow_area (address)
11818   //   i64   reg_save_area (address)
11819   // }
11820   // sizeof(va_list) = 24
11821   // alignment(va_list) = 8
11822
11823   unsigned TotalNumIntRegs = 6;
11824   unsigned TotalNumXMMRegs = 8;
11825   bool UseGPOffset = (ArgMode == 1);
11826   bool UseFPOffset = (ArgMode == 2);
11827   unsigned MaxOffset = TotalNumIntRegs * 8 +
11828                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11829
11830   /* Align ArgSize to a multiple of 8 */
11831   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11832   bool NeedsAlign = (Align > 8);
11833
11834   MachineBasicBlock *thisMBB = MBB;
11835   MachineBasicBlock *overflowMBB;
11836   MachineBasicBlock *offsetMBB;
11837   MachineBasicBlock *endMBB;
11838
11839   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11840   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11841   unsigned OffsetReg = 0;
11842
11843   if (!UseGPOffset && !UseFPOffset) {
11844     // If we only pull from the overflow region, we don't create a branch.
11845     // We don't need to alter control flow.
11846     OffsetDestReg = 0; // unused
11847     OverflowDestReg = DestReg;
11848
11849     offsetMBB = NULL;
11850     overflowMBB = thisMBB;
11851     endMBB = thisMBB;
11852   } else {
11853     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11854     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11855     // If not, pull from overflow_area. (branch to overflowMBB)
11856     //
11857     //       thisMBB
11858     //         |     .
11859     //         |        .
11860     //     offsetMBB   overflowMBB
11861     //         |        .
11862     //         |     .
11863     //        endMBB
11864
11865     // Registers for the PHI in endMBB
11866     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11867     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11868
11869     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11870     MachineFunction *MF = MBB->getParent();
11871     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11872     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11873     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11874
11875     MachineFunction::iterator MBBIter = MBB;
11876     ++MBBIter;
11877
11878     // Insert the new basic blocks
11879     MF->insert(MBBIter, offsetMBB);
11880     MF->insert(MBBIter, overflowMBB);
11881     MF->insert(MBBIter, endMBB);
11882
11883     // Transfer the remainder of MBB and its successor edges to endMBB.
11884     endMBB->splice(endMBB->begin(), thisMBB,
11885                     llvm::next(MachineBasicBlock::iterator(MI)),
11886                     thisMBB->end());
11887     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11888
11889     // Make offsetMBB and overflowMBB successors of thisMBB
11890     thisMBB->addSuccessor(offsetMBB);
11891     thisMBB->addSuccessor(overflowMBB);
11892
11893     // endMBB is a successor of both offsetMBB and overflowMBB
11894     offsetMBB->addSuccessor(endMBB);
11895     overflowMBB->addSuccessor(endMBB);
11896
11897     // Load the offset value into a register
11898     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11899     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11900       .addOperand(Base)
11901       .addOperand(Scale)
11902       .addOperand(Index)
11903       .addDisp(Disp, UseFPOffset ? 4 : 0)
11904       .addOperand(Segment)
11905       .setMemRefs(MMOBegin, MMOEnd);
11906
11907     // Check if there is enough room left to pull this argument.
11908     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11909       .addReg(OffsetReg)
11910       .addImm(MaxOffset + 8 - ArgSizeA8);
11911
11912     // Branch to "overflowMBB" if offset >= max
11913     // Fall through to "offsetMBB" otherwise
11914     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11915       .addMBB(overflowMBB);
11916   }
11917
11918   // In offsetMBB, emit code to use the reg_save_area.
11919   if (offsetMBB) {
11920     assert(OffsetReg != 0);
11921
11922     // Read the reg_save_area address.
11923     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11924     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11925       .addOperand(Base)
11926       .addOperand(Scale)
11927       .addOperand(Index)
11928       .addDisp(Disp, 16)
11929       .addOperand(Segment)
11930       .setMemRefs(MMOBegin, MMOEnd);
11931
11932     // Zero-extend the offset
11933     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11934       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11935         .addImm(0)
11936         .addReg(OffsetReg)
11937         .addImm(X86::sub_32bit);
11938
11939     // Add the offset to the reg_save_area to get the final address.
11940     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11941       .addReg(OffsetReg64)
11942       .addReg(RegSaveReg);
11943
11944     // Compute the offset for the next argument
11945     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11946     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11947       .addReg(OffsetReg)
11948       .addImm(UseFPOffset ? 16 : 8);
11949
11950     // Store it back into the va_list.
11951     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11952       .addOperand(Base)
11953       .addOperand(Scale)
11954       .addOperand(Index)
11955       .addDisp(Disp, UseFPOffset ? 4 : 0)
11956       .addOperand(Segment)
11957       .addReg(NextOffsetReg)
11958       .setMemRefs(MMOBegin, MMOEnd);
11959
11960     // Jump to endMBB
11961     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11962       .addMBB(endMBB);
11963   }
11964
11965   //
11966   // Emit code to use overflow area
11967   //
11968
11969   // Load the overflow_area address into a register.
11970   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11971   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11972     .addOperand(Base)
11973     .addOperand(Scale)
11974     .addOperand(Index)
11975     .addDisp(Disp, 8)
11976     .addOperand(Segment)
11977     .setMemRefs(MMOBegin, MMOEnd);
11978
11979   // If we need to align it, do so. Otherwise, just copy the address
11980   // to OverflowDestReg.
11981   if (NeedsAlign) {
11982     // Align the overflow address
11983     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11984     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11985
11986     // aligned_addr = (addr + (align-1)) & ~(align-1)
11987     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11988       .addReg(OverflowAddrReg)
11989       .addImm(Align-1);
11990
11991     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11992       .addReg(TmpReg)
11993       .addImm(~(uint64_t)(Align-1));
11994   } else {
11995     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11996       .addReg(OverflowAddrReg);
11997   }
11998
11999   // Compute the next overflow address after this argument.
12000   // (the overflow address should be kept 8-byte aligned)
12001   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12002   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12003     .addReg(OverflowDestReg)
12004     .addImm(ArgSizeA8);
12005
12006   // Store the new overflow address.
12007   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12008     .addOperand(Base)
12009     .addOperand(Scale)
12010     .addOperand(Index)
12011     .addDisp(Disp, 8)
12012     .addOperand(Segment)
12013     .addReg(NextAddrReg)
12014     .setMemRefs(MMOBegin, MMOEnd);
12015
12016   // If we branched, emit the PHI to the front of endMBB.
12017   if (offsetMBB) {
12018     BuildMI(*endMBB, endMBB->begin(), DL,
12019             TII->get(X86::PHI), DestReg)
12020       .addReg(OffsetDestReg).addMBB(offsetMBB)
12021       .addReg(OverflowDestReg).addMBB(overflowMBB);
12022   }
12023
12024   // Erase the pseudo instruction
12025   MI->eraseFromParent();
12026
12027   return endMBB;
12028 }
12029
12030 MachineBasicBlock *
12031 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12032                                                  MachineInstr *MI,
12033                                                  MachineBasicBlock *MBB) const {
12034   // Emit code to save XMM registers to the stack. The ABI says that the
12035   // number of registers to save is given in %al, so it's theoretically
12036   // possible to do an indirect jump trick to avoid saving all of them,
12037   // however this code takes a simpler approach and just executes all
12038   // of the stores if %al is non-zero. It's less code, and it's probably
12039   // easier on the hardware branch predictor, and stores aren't all that
12040   // expensive anyway.
12041
12042   // Create the new basic blocks. One block contains all the XMM stores,
12043   // and one block is the final destination regardless of whether any
12044   // stores were performed.
12045   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12046   MachineFunction *F = MBB->getParent();
12047   MachineFunction::iterator MBBIter = MBB;
12048   ++MBBIter;
12049   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12050   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12051   F->insert(MBBIter, XMMSaveMBB);
12052   F->insert(MBBIter, EndMBB);
12053
12054   // Transfer the remainder of MBB and its successor edges to EndMBB.
12055   EndMBB->splice(EndMBB->begin(), MBB,
12056                  llvm::next(MachineBasicBlock::iterator(MI)),
12057                  MBB->end());
12058   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12059
12060   // The original block will now fall through to the XMM save block.
12061   MBB->addSuccessor(XMMSaveMBB);
12062   // The XMMSaveMBB will fall through to the end block.
12063   XMMSaveMBB->addSuccessor(EndMBB);
12064
12065   // Now add the instructions.
12066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12067   DebugLoc DL = MI->getDebugLoc();
12068
12069   unsigned CountReg = MI->getOperand(0).getReg();
12070   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12071   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12072
12073   if (!Subtarget->isTargetWin64()) {
12074     // If %al is 0, branch around the XMM save block.
12075     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12076     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12077     MBB->addSuccessor(EndMBB);
12078   }
12079
12080   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12081   // In the XMM save block, save all the XMM argument registers.
12082   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12083     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12084     MachineMemOperand *MMO =
12085       F->getMachineMemOperand(
12086           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12087         MachineMemOperand::MOStore,
12088         /*Size=*/16, /*Align=*/16);
12089     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12090       .addFrameIndex(RegSaveFrameIndex)
12091       .addImm(/*Scale=*/1)
12092       .addReg(/*IndexReg=*/0)
12093       .addImm(/*Disp=*/Offset)
12094       .addReg(/*Segment=*/0)
12095       .addReg(MI->getOperand(i).getReg())
12096       .addMemOperand(MMO);
12097   }
12098
12099   MI->eraseFromParent();   // The pseudo instruction is gone now.
12100
12101   return EndMBB;
12102 }
12103
12104 // The EFLAGS operand of SelectItr might be missing a kill marker
12105 // because there were multiple uses of EFLAGS, and ISel didn't know
12106 // which to mark. Figure out whether SelectItr should have had a
12107 // kill marker, and set it if it should. Returns the correct kill
12108 // marker value.
12109 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12110                                      MachineBasicBlock* BB,
12111                                      const TargetRegisterInfo* TRI) {
12112   // Scan forward through BB for a use/def of EFLAGS.
12113   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12114   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12115     const MachineInstr& mi = *miI;
12116     if (mi.readsRegister(X86::EFLAGS))
12117       return false;
12118     if (mi.definesRegister(X86::EFLAGS))
12119       break; // Should have kill-flag - update below.
12120   }
12121
12122   // If we hit the end of the block, check whether EFLAGS is live into a
12123   // successor.
12124   if (miI == BB->end()) {
12125     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12126                                           sEnd = BB->succ_end();
12127          sItr != sEnd; ++sItr) {
12128       MachineBasicBlock* succ = *sItr;
12129       if (succ->isLiveIn(X86::EFLAGS))
12130         return false;
12131     }
12132   }
12133
12134   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12135   // out. SelectMI should have a kill flag on EFLAGS.
12136   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12137   return true;
12138 }
12139
12140 MachineBasicBlock *
12141 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12142                                      MachineBasicBlock *BB) const {
12143   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12144   DebugLoc DL = MI->getDebugLoc();
12145
12146   // To "insert" a SELECT_CC instruction, we actually have to insert the
12147   // diamond control-flow pattern.  The incoming instruction knows the
12148   // destination vreg to set, the condition code register to branch on, the
12149   // true/false values to select between, and a branch opcode to use.
12150   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12151   MachineFunction::iterator It = BB;
12152   ++It;
12153
12154   //  thisMBB:
12155   //  ...
12156   //   TrueVal = ...
12157   //   cmpTY ccX, r1, r2
12158   //   bCC copy1MBB
12159   //   fallthrough --> copy0MBB
12160   MachineBasicBlock *thisMBB = BB;
12161   MachineFunction *F = BB->getParent();
12162   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12163   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12164   F->insert(It, copy0MBB);
12165   F->insert(It, sinkMBB);
12166
12167   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12168   // live into the sink and copy blocks.
12169   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12170   if (!MI->killsRegister(X86::EFLAGS) &&
12171       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12172     copy0MBB->addLiveIn(X86::EFLAGS);
12173     sinkMBB->addLiveIn(X86::EFLAGS);
12174   }
12175
12176   // Transfer the remainder of BB and its successor edges to sinkMBB.
12177   sinkMBB->splice(sinkMBB->begin(), BB,
12178                   llvm::next(MachineBasicBlock::iterator(MI)),
12179                   BB->end());
12180   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12181
12182   // Add the true and fallthrough blocks as its successors.
12183   BB->addSuccessor(copy0MBB);
12184   BB->addSuccessor(sinkMBB);
12185
12186   // Create the conditional branch instruction.
12187   unsigned Opc =
12188     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12189   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12190
12191   //  copy0MBB:
12192   //   %FalseValue = ...
12193   //   # fallthrough to sinkMBB
12194   copy0MBB->addSuccessor(sinkMBB);
12195
12196   //  sinkMBB:
12197   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12198   //  ...
12199   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12200           TII->get(X86::PHI), MI->getOperand(0).getReg())
12201     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12202     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12203
12204   MI->eraseFromParent();   // The pseudo instruction is gone now.
12205   return sinkMBB;
12206 }
12207
12208 MachineBasicBlock *
12209 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12210                                         bool Is64Bit) const {
12211   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12212   DebugLoc DL = MI->getDebugLoc();
12213   MachineFunction *MF = BB->getParent();
12214   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12215
12216   assert(getTargetMachine().Options.EnableSegmentedStacks);
12217
12218   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12219   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12220
12221   // BB:
12222   //  ... [Till the alloca]
12223   // If stacklet is not large enough, jump to mallocMBB
12224   //
12225   // bumpMBB:
12226   //  Allocate by subtracting from RSP
12227   //  Jump to continueMBB
12228   //
12229   // mallocMBB:
12230   //  Allocate by call to runtime
12231   //
12232   // continueMBB:
12233   //  ...
12234   //  [rest of original BB]
12235   //
12236
12237   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12238   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12239   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12240
12241   MachineRegisterInfo &MRI = MF->getRegInfo();
12242   const TargetRegisterClass *AddrRegClass =
12243     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12244
12245   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12246     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12247     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12248     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12249     sizeVReg = MI->getOperand(1).getReg(),
12250     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12251
12252   MachineFunction::iterator MBBIter = BB;
12253   ++MBBIter;
12254
12255   MF->insert(MBBIter, bumpMBB);
12256   MF->insert(MBBIter, mallocMBB);
12257   MF->insert(MBBIter, continueMBB);
12258
12259   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12260                       (MachineBasicBlock::iterator(MI)), BB->end());
12261   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12262
12263   // Add code to the main basic block to check if the stack limit has been hit,
12264   // and if so, jump to mallocMBB otherwise to bumpMBB.
12265   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12266   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12267     .addReg(tmpSPVReg).addReg(sizeVReg);
12268   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12269     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12270     .addReg(SPLimitVReg);
12271   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12272
12273   // bumpMBB simply decreases the stack pointer, since we know the current
12274   // stacklet has enough space.
12275   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12276     .addReg(SPLimitVReg);
12277   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12278     .addReg(SPLimitVReg);
12279   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12280
12281   // Calls into a routine in libgcc to allocate more space from the heap.
12282   const uint32_t *RegMask =
12283     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12284   if (Is64Bit) {
12285     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12286       .addReg(sizeVReg);
12287     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12288       .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12289       .addRegMask(RegMask)
12290       .addReg(X86::RAX, RegState::ImplicitDefine);
12291   } else {
12292     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12293       .addImm(12);
12294     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12295     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12296       .addExternalSymbol("__morestack_allocate_stack_space")
12297       .addRegMask(RegMask)
12298       .addReg(X86::EAX, RegState::ImplicitDefine);
12299   }
12300
12301   if (!Is64Bit)
12302     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12303       .addImm(16);
12304
12305   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12306     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12307   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12308
12309   // Set up the CFG correctly.
12310   BB->addSuccessor(bumpMBB);
12311   BB->addSuccessor(mallocMBB);
12312   mallocMBB->addSuccessor(continueMBB);
12313   bumpMBB->addSuccessor(continueMBB);
12314
12315   // Take care of the PHI nodes.
12316   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12317           MI->getOperand(0).getReg())
12318     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12319     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12320
12321   // Delete the original pseudo instruction.
12322   MI->eraseFromParent();
12323
12324   // And we're done.
12325   return continueMBB;
12326 }
12327
12328 MachineBasicBlock *
12329 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12330                                           MachineBasicBlock *BB) const {
12331   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12332   DebugLoc DL = MI->getDebugLoc();
12333
12334   assert(!Subtarget->isTargetEnvMacho());
12335
12336   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12337   // non-trivial part is impdef of ESP.
12338
12339   if (Subtarget->isTargetWin64()) {
12340     if (Subtarget->isTargetCygMing()) {
12341       // ___chkstk(Mingw64):
12342       // Clobbers R10, R11, RAX and EFLAGS.
12343       // Updates RSP.
12344       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12345         .addExternalSymbol("___chkstk")
12346         .addReg(X86::RAX, RegState::Implicit)
12347         .addReg(X86::RSP, RegState::Implicit)
12348         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12349         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12350         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12351     } else {
12352       // __chkstk(MSVCRT): does not update stack pointer.
12353       // Clobbers R10, R11 and EFLAGS.
12354       // FIXME: RAX(allocated size) might be reused and not killed.
12355       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12356         .addExternalSymbol("__chkstk")
12357         .addReg(X86::RAX, RegState::Implicit)
12358         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12359       // RAX has the offset to subtracted from RSP.
12360       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12361         .addReg(X86::RSP)
12362         .addReg(X86::RAX);
12363     }
12364   } else {
12365     const char *StackProbeSymbol =
12366       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12367
12368     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12369       .addExternalSymbol(StackProbeSymbol)
12370       .addReg(X86::EAX, RegState::Implicit)
12371       .addReg(X86::ESP, RegState::Implicit)
12372       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12373       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12374       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12375   }
12376
12377   MI->eraseFromParent();   // The pseudo instruction is gone now.
12378   return BB;
12379 }
12380
12381 MachineBasicBlock *
12382 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12383                                       MachineBasicBlock *BB) const {
12384   // This is pretty easy.  We're taking the value that we received from
12385   // our load from the relocation, sticking it in either RDI (x86-64)
12386   // or EAX and doing an indirect call.  The return value will then
12387   // be in the normal return register.
12388   const X86InstrInfo *TII
12389     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12390   DebugLoc DL = MI->getDebugLoc();
12391   MachineFunction *F = BB->getParent();
12392
12393   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12394   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12395
12396   // Get a register mask for the lowered call.
12397   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12398   // proper register mask.
12399   const uint32_t *RegMask =
12400     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12401   if (Subtarget->is64Bit()) {
12402     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12403                                       TII->get(X86::MOV64rm), X86::RDI)
12404     .addReg(X86::RIP)
12405     .addImm(0).addReg(0)
12406     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12407                       MI->getOperand(3).getTargetFlags())
12408     .addReg(0);
12409     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12410     addDirectMem(MIB, X86::RDI);
12411     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12412   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12413     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12414                                       TII->get(X86::MOV32rm), X86::EAX)
12415     .addReg(0)
12416     .addImm(0).addReg(0)
12417     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12418                       MI->getOperand(3).getTargetFlags())
12419     .addReg(0);
12420     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12421     addDirectMem(MIB, X86::EAX);
12422     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12423   } else {
12424     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12425                                       TII->get(X86::MOV32rm), X86::EAX)
12426     .addReg(TII->getGlobalBaseReg(F))
12427     .addImm(0).addReg(0)
12428     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12429                       MI->getOperand(3).getTargetFlags())
12430     .addReg(0);
12431     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12432     addDirectMem(MIB, X86::EAX);
12433     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12434   }
12435
12436   MI->eraseFromParent(); // The pseudo instruction is gone now.
12437   return BB;
12438 }
12439
12440 MachineBasicBlock *
12441 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12442                                                MachineBasicBlock *BB) const {
12443   switch (MI->getOpcode()) {
12444   default: llvm_unreachable("Unexpected instr type to insert");
12445   case X86::TAILJMPd64:
12446   case X86::TAILJMPr64:
12447   case X86::TAILJMPm64:
12448     llvm_unreachable("TAILJMP64 would not be touched here.");
12449   case X86::TCRETURNdi64:
12450   case X86::TCRETURNri64:
12451   case X86::TCRETURNmi64:
12452     return BB;
12453   case X86::WIN_ALLOCA:
12454     return EmitLoweredWinAlloca(MI, BB);
12455   case X86::SEG_ALLOCA_32:
12456     return EmitLoweredSegAlloca(MI, BB, false);
12457   case X86::SEG_ALLOCA_64:
12458     return EmitLoweredSegAlloca(MI, BB, true);
12459   case X86::TLSCall_32:
12460   case X86::TLSCall_64:
12461     return EmitLoweredTLSCall(MI, BB);
12462   case X86::CMOV_GR8:
12463   case X86::CMOV_FR32:
12464   case X86::CMOV_FR64:
12465   case X86::CMOV_V4F32:
12466   case X86::CMOV_V2F64:
12467   case X86::CMOV_V2I64:
12468   case X86::CMOV_V8F32:
12469   case X86::CMOV_V4F64:
12470   case X86::CMOV_V4I64:
12471   case X86::CMOV_GR16:
12472   case X86::CMOV_GR32:
12473   case X86::CMOV_RFP32:
12474   case X86::CMOV_RFP64:
12475   case X86::CMOV_RFP80:
12476     return EmitLoweredSelect(MI, BB);
12477
12478   case X86::FP32_TO_INT16_IN_MEM:
12479   case X86::FP32_TO_INT32_IN_MEM:
12480   case X86::FP32_TO_INT64_IN_MEM:
12481   case X86::FP64_TO_INT16_IN_MEM:
12482   case X86::FP64_TO_INT32_IN_MEM:
12483   case X86::FP64_TO_INT64_IN_MEM:
12484   case X86::FP80_TO_INT16_IN_MEM:
12485   case X86::FP80_TO_INT32_IN_MEM:
12486   case X86::FP80_TO_INT64_IN_MEM: {
12487     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12488     DebugLoc DL = MI->getDebugLoc();
12489
12490     // Change the floating point control register to use "round towards zero"
12491     // mode when truncating to an integer value.
12492     MachineFunction *F = BB->getParent();
12493     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12494     addFrameReference(BuildMI(*BB, MI, DL,
12495                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12496
12497     // Load the old value of the high byte of the control word...
12498     unsigned OldCW =
12499       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12500     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12501                       CWFrameIdx);
12502
12503     // Set the high part to be round to zero...
12504     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12505       .addImm(0xC7F);
12506
12507     // Reload the modified control word now...
12508     addFrameReference(BuildMI(*BB, MI, DL,
12509                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12510
12511     // Restore the memory image of control word to original value
12512     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12513       .addReg(OldCW);
12514
12515     // Get the X86 opcode to use.
12516     unsigned Opc;
12517     switch (MI->getOpcode()) {
12518     default: llvm_unreachable("illegal opcode!");
12519     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12520     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12521     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12522     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12523     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12524     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12525     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12526     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12527     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12528     }
12529
12530     X86AddressMode AM;
12531     MachineOperand &Op = MI->getOperand(0);
12532     if (Op.isReg()) {
12533       AM.BaseType = X86AddressMode::RegBase;
12534       AM.Base.Reg = Op.getReg();
12535     } else {
12536       AM.BaseType = X86AddressMode::FrameIndexBase;
12537       AM.Base.FrameIndex = Op.getIndex();
12538     }
12539     Op = MI->getOperand(1);
12540     if (Op.isImm())
12541       AM.Scale = Op.getImm();
12542     Op = MI->getOperand(2);
12543     if (Op.isImm())
12544       AM.IndexReg = Op.getImm();
12545     Op = MI->getOperand(3);
12546     if (Op.isGlobal()) {
12547       AM.GV = Op.getGlobal();
12548     } else {
12549       AM.Disp = Op.getImm();
12550     }
12551     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12552                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12553
12554     // Reload the original control word now.
12555     addFrameReference(BuildMI(*BB, MI, DL,
12556                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12557
12558     MI->eraseFromParent();   // The pseudo instruction is gone now.
12559     return BB;
12560   }
12561     // String/text processing lowering.
12562   case X86::PCMPISTRM128REG:
12563   case X86::VPCMPISTRM128REG:
12564     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12565   case X86::PCMPISTRM128MEM:
12566   case X86::VPCMPISTRM128MEM:
12567     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12568   case X86::PCMPESTRM128REG:
12569   case X86::VPCMPESTRM128REG:
12570     return EmitPCMP(MI, BB, 5, false /* in mem */);
12571   case X86::PCMPESTRM128MEM:
12572   case X86::VPCMPESTRM128MEM:
12573     return EmitPCMP(MI, BB, 5, true /* in mem */);
12574
12575     // Thread synchronization.
12576   case X86::MONITOR:
12577     return EmitMonitor(MI, BB);
12578   case X86::MWAIT:
12579     return EmitMwait(MI, BB);
12580
12581     // Atomic Lowering.
12582   case X86::ATOMAND32:
12583     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12584                                                X86::AND32ri, X86::MOV32rm,
12585                                                X86::LCMPXCHG32,
12586                                                X86::NOT32r, X86::EAX,
12587                                                &X86::GR32RegClass);
12588   case X86::ATOMOR32:
12589     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12590                                                X86::OR32ri, X86::MOV32rm,
12591                                                X86::LCMPXCHG32,
12592                                                X86::NOT32r, X86::EAX,
12593                                                &X86::GR32RegClass);
12594   case X86::ATOMXOR32:
12595     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12596                                                X86::XOR32ri, X86::MOV32rm,
12597                                                X86::LCMPXCHG32,
12598                                                X86::NOT32r, X86::EAX,
12599                                                &X86::GR32RegClass);
12600   case X86::ATOMNAND32:
12601     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12602                                                X86::AND32ri, X86::MOV32rm,
12603                                                X86::LCMPXCHG32,
12604                                                X86::NOT32r, X86::EAX,
12605                                                &X86::GR32RegClass, true);
12606   case X86::ATOMMIN32:
12607     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12608   case X86::ATOMMAX32:
12609     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12610   case X86::ATOMUMIN32:
12611     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12612   case X86::ATOMUMAX32:
12613     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12614
12615   case X86::ATOMAND16:
12616     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12617                                                X86::AND16ri, X86::MOV16rm,
12618                                                X86::LCMPXCHG16,
12619                                                X86::NOT16r, X86::AX,
12620                                                &X86::GR16RegClass);
12621   case X86::ATOMOR16:
12622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12623                                                X86::OR16ri, X86::MOV16rm,
12624                                                X86::LCMPXCHG16,
12625                                                X86::NOT16r, X86::AX,
12626                                                &X86::GR16RegClass);
12627   case X86::ATOMXOR16:
12628     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12629                                                X86::XOR16ri, X86::MOV16rm,
12630                                                X86::LCMPXCHG16,
12631                                                X86::NOT16r, X86::AX,
12632                                                &X86::GR16RegClass);
12633   case X86::ATOMNAND16:
12634     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12635                                                X86::AND16ri, X86::MOV16rm,
12636                                                X86::LCMPXCHG16,
12637                                                X86::NOT16r, X86::AX,
12638                                                &X86::GR16RegClass, true);
12639   case X86::ATOMMIN16:
12640     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12641   case X86::ATOMMAX16:
12642     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12643   case X86::ATOMUMIN16:
12644     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12645   case X86::ATOMUMAX16:
12646     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12647
12648   case X86::ATOMAND8:
12649     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12650                                                X86::AND8ri, X86::MOV8rm,
12651                                                X86::LCMPXCHG8,
12652                                                X86::NOT8r, X86::AL,
12653                                                &X86::GR8RegClass);
12654   case X86::ATOMOR8:
12655     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12656                                                X86::OR8ri, X86::MOV8rm,
12657                                                X86::LCMPXCHG8,
12658                                                X86::NOT8r, X86::AL,
12659                                                &X86::GR8RegClass);
12660   case X86::ATOMXOR8:
12661     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12662                                                X86::XOR8ri, X86::MOV8rm,
12663                                                X86::LCMPXCHG8,
12664                                                X86::NOT8r, X86::AL,
12665                                                &X86::GR8RegClass);
12666   case X86::ATOMNAND8:
12667     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12668                                                X86::AND8ri, X86::MOV8rm,
12669                                                X86::LCMPXCHG8,
12670                                                X86::NOT8r, X86::AL,
12671                                                &X86::GR8RegClass, true);
12672   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12673   // This group is for 64-bit host.
12674   case X86::ATOMAND64:
12675     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12676                                                X86::AND64ri32, X86::MOV64rm,
12677                                                X86::LCMPXCHG64,
12678                                                X86::NOT64r, X86::RAX,
12679                                                &X86::GR64RegClass);
12680   case X86::ATOMOR64:
12681     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12682                                                X86::OR64ri32, X86::MOV64rm,
12683                                                X86::LCMPXCHG64,
12684                                                X86::NOT64r, X86::RAX,
12685                                                &X86::GR64RegClass);
12686   case X86::ATOMXOR64:
12687     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12688                                                X86::XOR64ri32, X86::MOV64rm,
12689                                                X86::LCMPXCHG64,
12690                                                X86::NOT64r, X86::RAX,
12691                                                &X86::GR64RegClass);
12692   case X86::ATOMNAND64:
12693     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12694                                                X86::AND64ri32, X86::MOV64rm,
12695                                                X86::LCMPXCHG64,
12696                                                X86::NOT64r, X86::RAX,
12697                                                &X86::GR64RegClass, true);
12698   case X86::ATOMMIN64:
12699     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12700   case X86::ATOMMAX64:
12701     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12702   case X86::ATOMUMIN64:
12703     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12704   case X86::ATOMUMAX64:
12705     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12706
12707   // This group does 64-bit operations on a 32-bit host.
12708   case X86::ATOMAND6432:
12709     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12710                                                X86::AND32rr, X86::AND32rr,
12711                                                X86::AND32ri, X86::AND32ri,
12712                                                false);
12713   case X86::ATOMOR6432:
12714     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12715                                                X86::OR32rr, X86::OR32rr,
12716                                                X86::OR32ri, X86::OR32ri,
12717                                                false);
12718   case X86::ATOMXOR6432:
12719     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12720                                                X86::XOR32rr, X86::XOR32rr,
12721                                                X86::XOR32ri, X86::XOR32ri,
12722                                                false);
12723   case X86::ATOMNAND6432:
12724     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12725                                                X86::AND32rr, X86::AND32rr,
12726                                                X86::AND32ri, X86::AND32ri,
12727                                                true);
12728   case X86::ATOMADD6432:
12729     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12730                                                X86::ADD32rr, X86::ADC32rr,
12731                                                X86::ADD32ri, X86::ADC32ri,
12732                                                false);
12733   case X86::ATOMSUB6432:
12734     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12735                                                X86::SUB32rr, X86::SBB32rr,
12736                                                X86::SUB32ri, X86::SBB32ri,
12737                                                false);
12738   case X86::ATOMSWAP6432:
12739     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12740                                                X86::MOV32rr, X86::MOV32rr,
12741                                                X86::MOV32ri, X86::MOV32ri,
12742                                                false);
12743   case X86::VASTART_SAVE_XMM_REGS:
12744     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12745
12746   case X86::VAARG_64:
12747     return EmitVAARG64WithCustomInserter(MI, BB);
12748   }
12749 }
12750
12751 //===----------------------------------------------------------------------===//
12752 //                           X86 Optimization Hooks
12753 //===----------------------------------------------------------------------===//
12754
12755 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12756                                                        APInt &KnownZero,
12757                                                        APInt &KnownOne,
12758                                                        const SelectionDAG &DAG,
12759                                                        unsigned Depth) const {
12760   unsigned BitWidth = KnownZero.getBitWidth();
12761   unsigned Opc = Op.getOpcode();
12762   assert((Opc >= ISD::BUILTIN_OP_END ||
12763           Opc == ISD::INTRINSIC_WO_CHAIN ||
12764           Opc == ISD::INTRINSIC_W_CHAIN ||
12765           Opc == ISD::INTRINSIC_VOID) &&
12766          "Should use MaskedValueIsZero if you don't know whether Op"
12767          " is a target node!");
12768
12769   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
12770   switch (Opc) {
12771   default: break;
12772   case X86ISD::ADD:
12773   case X86ISD::SUB:
12774   case X86ISD::ADC:
12775   case X86ISD::SBB:
12776   case X86ISD::SMUL:
12777   case X86ISD::UMUL:
12778   case X86ISD::INC:
12779   case X86ISD::DEC:
12780   case X86ISD::OR:
12781   case X86ISD::XOR:
12782   case X86ISD::AND:
12783     // These nodes' second result is a boolean.
12784     if (Op.getResNo() == 0)
12785       break;
12786     // Fallthrough
12787   case X86ISD::SETCC:
12788     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12789     break;
12790   case ISD::INTRINSIC_WO_CHAIN: {
12791     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12792     unsigned NumLoBits = 0;
12793     switch (IntId) {
12794     default: break;
12795     case Intrinsic::x86_sse_movmsk_ps:
12796     case Intrinsic::x86_avx_movmsk_ps_256:
12797     case Intrinsic::x86_sse2_movmsk_pd:
12798     case Intrinsic::x86_avx_movmsk_pd_256:
12799     case Intrinsic::x86_mmx_pmovmskb:
12800     case Intrinsic::x86_sse2_pmovmskb_128:
12801     case Intrinsic::x86_avx2_pmovmskb: {
12802       // High bits of movmskp{s|d}, pmovmskb are known zero.
12803       switch (IntId) {
12804         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12805         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12806         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12807         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12808         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12809         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12810         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12811         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
12812       }
12813       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12814       break;
12815     }
12816     }
12817     break;
12818   }
12819   }
12820 }
12821
12822 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12823                                                          unsigned Depth) const {
12824   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12825   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12826     return Op.getValueType().getScalarType().getSizeInBits();
12827
12828   // Fallback case.
12829   return 1;
12830 }
12831
12832 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12833 /// node is a GlobalAddress + offset.
12834 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12835                                        const GlobalValue* &GA,
12836                                        int64_t &Offset) const {
12837   if (N->getOpcode() == X86ISD::Wrapper) {
12838     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12839       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12840       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12841       return true;
12842     }
12843   }
12844   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12845 }
12846
12847 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12848 /// same as extracting the high 128-bit part of 256-bit vector and then
12849 /// inserting the result into the low part of a new 256-bit vector
12850 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12851   EVT VT = SVOp->getValueType(0);
12852   int NumElems = VT.getVectorNumElements();
12853
12854   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12855   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12856     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12857         SVOp->getMaskElt(j) >= 0)
12858       return false;
12859
12860   return true;
12861 }
12862
12863 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12864 /// same as extracting the low 128-bit part of 256-bit vector and then
12865 /// inserting the result into the high part of a new 256-bit vector
12866 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12867   EVT VT = SVOp->getValueType(0);
12868   int NumElems = VT.getVectorNumElements();
12869
12870   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12871   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12872     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12873         SVOp->getMaskElt(j) >= 0)
12874       return false;
12875
12876   return true;
12877 }
12878
12879 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12880 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12881                                         TargetLowering::DAGCombinerInfo &DCI,
12882                                         const X86Subtarget* Subtarget) {
12883   DebugLoc dl = N->getDebugLoc();
12884   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12885   SDValue V1 = SVOp->getOperand(0);
12886   SDValue V2 = SVOp->getOperand(1);
12887   EVT VT = SVOp->getValueType(0);
12888   int NumElems = VT.getVectorNumElements();
12889
12890   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12891       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12892     //
12893     //                   0,0,0,...
12894     //                      |
12895     //    V      UNDEF    BUILD_VECTOR    UNDEF
12896     //     \      /           \           /
12897     //  CONCAT_VECTOR         CONCAT_VECTOR
12898     //         \                  /
12899     //          \                /
12900     //          RESULT: V + zero extended
12901     //
12902     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12903         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12904         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12905       return SDValue();
12906
12907     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12908       return SDValue();
12909
12910     // To match the shuffle mask, the first half of the mask should
12911     // be exactly the first vector, and all the rest a splat with the
12912     // first element of the second one.
12913     for (int i = 0; i < NumElems/2; ++i)
12914       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12915           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12916         return SDValue();
12917
12918     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
12919     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
12920       SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
12921       SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
12922       SDValue ResNode =
12923         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
12924                                 Ld->getMemoryVT(),
12925                                 Ld->getPointerInfo(),
12926                                 Ld->getAlignment(),
12927                                 false/*isVolatile*/, true/*ReadMem*/,
12928                                 false/*WriteMem*/);
12929       return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
12930     } 
12931
12932     // Emit a zeroed vector and insert the desired subvector on its
12933     // first half.
12934     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
12935     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
12936     return DCI.CombineTo(N, InsV);
12937   }
12938
12939   //===--------------------------------------------------------------------===//
12940   // Combine some shuffles into subvector extracts and inserts:
12941   //
12942
12943   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12944   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12945     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
12946     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
12947     return DCI.CombineTo(N, InsV);
12948   }
12949
12950   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12951   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12952     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
12953     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
12954     return DCI.CombineTo(N, InsV);
12955   }
12956
12957   return SDValue();
12958 }
12959
12960 /// PerformShuffleCombine - Performs several different shuffle combines.
12961 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12962                                      TargetLowering::DAGCombinerInfo &DCI,
12963                                      const X86Subtarget *Subtarget) {
12964   DebugLoc dl = N->getDebugLoc();
12965   EVT VT = N->getValueType(0);
12966
12967   // Don't create instructions with illegal types after legalize types has run.
12968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12969   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12970     return SDValue();
12971
12972   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12973   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12974       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12975     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
12976
12977   // Only handle 128 wide vector from here on.
12978   if (VT.getSizeInBits() != 128)
12979     return SDValue();
12980
12981   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12982   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12983   // consecutive, non-overlapping, and in the right order.
12984   SmallVector<SDValue, 16> Elts;
12985   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12986     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12987
12988   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12989 }
12990
12991
12992 /// PerformTruncateCombine - Converts truncate operation to
12993 /// a sequence of vector shuffle operations.
12994 /// It is possible when we truncate 256-bit vector to 128-bit vector
12995
12996 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG, 
12997                                                   DAGCombinerInfo &DCI) const {
12998   if (!DCI.isBeforeLegalizeOps())
12999     return SDValue();
13000
13001   if (!Subtarget->hasAVX()) return SDValue();
13002
13003   EVT VT = N->getValueType(0);
13004   SDValue Op = N->getOperand(0);
13005   EVT OpVT = Op.getValueType();
13006   DebugLoc dl = N->getDebugLoc();
13007
13008   if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13009
13010     if (Subtarget->hasAVX2()) {
13011       // AVX2: v4i64 -> v4i32
13012
13013       // VPERMD
13014       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13015
13016       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13017       Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13018                                 ShufMask);
13019
13020       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13021                          DAG.getIntPtrConstant(0));
13022     }
13023
13024     // AVX: v4i64 -> v4i32
13025     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13026                                DAG.getIntPtrConstant(0));
13027
13028     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13029                                DAG.getIntPtrConstant(2));
13030
13031     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13032     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13033
13034     // PSHUFD
13035     static const int ShufMask1[] = {0, 2, 0, 0};
13036
13037     OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13038     OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13039
13040     // MOVLHPS
13041     static const int ShufMask2[] = {0, 1, 4, 5};
13042
13043     return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13044   }
13045
13046   if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13047
13048     if (Subtarget->hasAVX2()) {
13049       // AVX2: v8i32 -> v8i16
13050
13051       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13052
13053       // PSHUFB
13054       SmallVector<SDValue,32> pshufbMask;
13055       for (unsigned i = 0; i < 2; ++i) {
13056         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13057         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13058         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13059         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13060         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13061         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13062         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13063         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13064         for (unsigned j = 0; j < 8; ++j)
13065           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13066       }
13067       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13068                                &pshufbMask[0], 32);
13069       Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13070
13071       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13072
13073       static const int ShufMask[] = {0,  2,  -1,  -1};
13074       Op = DAG.getVectorShuffle(MVT::v4i64, dl,  Op, DAG.getUNDEF(MVT::v4i64),
13075                                 &ShufMask[0]);
13076
13077       Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13078                        DAG.getIntPtrConstant(0));
13079
13080       return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13081     }
13082
13083     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13084                                DAG.getIntPtrConstant(0));
13085
13086     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13087                                DAG.getIntPtrConstant(4));
13088
13089     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13090     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13091
13092     // PSHUFB
13093     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13094                                    -1, -1, -1, -1, -1, -1, -1, -1};
13095
13096     OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13097                                 ShufMask1);
13098     OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13099                                 ShufMask1);
13100
13101     OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13102     OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13103
13104     // MOVLHPS
13105     static const int ShufMask2[] = {0, 1, 4, 5};
13106
13107     SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13108     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13109   }
13110
13111   return SDValue();
13112 }
13113
13114 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13115 /// specific shuffle of a load can be folded into a single element load.
13116 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13117 /// shuffles have been customed lowered so we need to handle those here.
13118 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13119                                          TargetLowering::DAGCombinerInfo &DCI) {
13120   if (DCI.isBeforeLegalizeOps())
13121     return SDValue();
13122
13123   SDValue InVec = N->getOperand(0);
13124   SDValue EltNo = N->getOperand(1);
13125
13126   if (!isa<ConstantSDNode>(EltNo))
13127     return SDValue();
13128
13129   EVT VT = InVec.getValueType();
13130
13131   bool HasShuffleIntoBitcast = false;
13132   if (InVec.getOpcode() == ISD::BITCAST) {
13133     // Don't duplicate a load with other uses.
13134     if (!InVec.hasOneUse())
13135       return SDValue();
13136     EVT BCVT = InVec.getOperand(0).getValueType();
13137     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13138       return SDValue();
13139     InVec = InVec.getOperand(0);
13140     HasShuffleIntoBitcast = true;
13141   }
13142
13143   if (!isTargetShuffle(InVec.getOpcode()))
13144     return SDValue();
13145
13146   // Don't duplicate a load with other uses.
13147   if (!InVec.hasOneUse())
13148     return SDValue();
13149
13150   SmallVector<int, 16> ShuffleMask;
13151   bool UnaryShuffle;
13152   if (!getTargetShuffleMask(InVec.getNode(), VT, ShuffleMask, UnaryShuffle))
13153     return SDValue();
13154
13155   // Select the input vector, guarding against out of range extract vector.
13156   unsigned NumElems = VT.getVectorNumElements();
13157   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13158   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13159   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13160                                          : InVec.getOperand(1);
13161
13162   // If inputs to shuffle are the same for both ops, then allow 2 uses
13163   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13164
13165   if (LdNode.getOpcode() == ISD::BITCAST) {
13166     // Don't duplicate a load with other uses.
13167     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13168       return SDValue();
13169
13170     AllowedUses = 1; // only allow 1 load use if we have a bitcast
13171     LdNode = LdNode.getOperand(0);
13172   }
13173
13174   if (!ISD::isNormalLoad(LdNode.getNode()))
13175     return SDValue();
13176
13177   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13178
13179   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13180     return SDValue();
13181
13182   if (HasShuffleIntoBitcast) {
13183     // If there's a bitcast before the shuffle, check if the load type and
13184     // alignment is valid.
13185     unsigned Align = LN0->getAlignment();
13186     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13187     unsigned NewAlign = TLI.getTargetData()->
13188       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13189
13190     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13191       return SDValue();
13192   }
13193
13194   // All checks match so transform back to vector_shuffle so that DAG combiner
13195   // can finish the job
13196   DebugLoc dl = N->getDebugLoc();
13197
13198   // Create shuffle node taking into account the case that its a unary shuffle
13199   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13200   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13201                                  InVec.getOperand(0), Shuffle,
13202                                  &ShuffleMask[0]);
13203   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13204   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13205                      EltNo);
13206 }
13207
13208 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13209 /// generation and convert it from being a bunch of shuffles and extracts
13210 /// to a simple store and scalar loads to extract the elements.
13211 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13212                                          TargetLowering::DAGCombinerInfo &DCI) {
13213   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13214   if (NewOp.getNode())
13215     return NewOp;
13216
13217   SDValue InputVector = N->getOperand(0);
13218
13219   // Only operate on vectors of 4 elements, where the alternative shuffling
13220   // gets to be more expensive.
13221   if (InputVector.getValueType() != MVT::v4i32)
13222     return SDValue();
13223
13224   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13225   // single use which is a sign-extend or zero-extend, and all elements are
13226   // used.
13227   SmallVector<SDNode *, 4> Uses;
13228   unsigned ExtractedElements = 0;
13229   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13230        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13231     if (UI.getUse().getResNo() != InputVector.getResNo())
13232       return SDValue();
13233
13234     SDNode *Extract = *UI;
13235     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13236       return SDValue();
13237
13238     if (Extract->getValueType(0) != MVT::i32)
13239       return SDValue();
13240     if (!Extract->hasOneUse())
13241       return SDValue();
13242     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13243         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13244       return SDValue();
13245     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13246       return SDValue();
13247
13248     // Record which element was extracted.
13249     ExtractedElements |=
13250       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13251
13252     Uses.push_back(Extract);
13253   }
13254
13255   // If not all the elements were used, this may not be worthwhile.
13256   if (ExtractedElements != 15)
13257     return SDValue();
13258
13259   // Ok, we've now decided to do the transformation.
13260   DebugLoc dl = InputVector.getDebugLoc();
13261
13262   // Store the value to a temporary stack slot.
13263   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13264   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13265                             MachinePointerInfo(), false, false, 0);
13266
13267   // Replace each use (extract) with a load of the appropriate element.
13268   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13269        UE = Uses.end(); UI != UE; ++UI) {
13270     SDNode *Extract = *UI;
13271
13272     // cOMpute the element's address.
13273     SDValue Idx = Extract->getOperand(1);
13274     unsigned EltSize =
13275         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13276     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13277     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13278     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13279
13280     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13281                                      StackPtr, OffsetVal);
13282
13283     // Load the scalar.
13284     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13285                                      ScalarAddr, MachinePointerInfo(),
13286                                      false, false, false, 0);
13287
13288     // Replace the exact with the load.
13289     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13290   }
13291
13292   // The replacement was made in place; don't return anything.
13293   return SDValue();
13294 }
13295
13296 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13297 /// nodes.
13298 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13299                                     TargetLowering::DAGCombinerInfo &DCI,
13300                                     const X86Subtarget *Subtarget) {
13301
13302
13303   DebugLoc DL = N->getDebugLoc();
13304   SDValue Cond = N->getOperand(0);
13305   // Get the LHS/RHS of the select.
13306   SDValue LHS = N->getOperand(1);
13307   SDValue RHS = N->getOperand(2);
13308   EVT VT = LHS.getValueType();
13309
13310   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13311   // instructions match the semantics of the common C idiom x<y?x:y but not
13312   // x<=y?x:y, because of how they handle negative zero (which can be
13313   // ignored in unsafe-math mode).
13314   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13315       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13316       (Subtarget->hasSSE2() ||
13317        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13318     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13319
13320     unsigned Opcode = 0;
13321     // Check for x CC y ? x : y.
13322     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13323         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13324       switch (CC) {
13325       default: break;
13326       case ISD::SETULT:
13327         // Converting this to a min would handle NaNs incorrectly, and swapping
13328         // the operands would cause it to handle comparisons between positive
13329         // and negative zero incorrectly.
13330         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13331           if (!DAG.getTarget().Options.UnsafeFPMath &&
13332               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13333             break;
13334           std::swap(LHS, RHS);
13335         }
13336         Opcode = X86ISD::FMIN;
13337         break;
13338       case ISD::SETOLE:
13339         // Converting this to a min would handle comparisons between positive
13340         // and negative zero incorrectly.
13341         if (!DAG.getTarget().Options.UnsafeFPMath &&
13342             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13343           break;
13344         Opcode = X86ISD::FMIN;
13345         break;
13346       case ISD::SETULE:
13347         // Converting this to a min would handle both negative zeros and NaNs
13348         // incorrectly, but we can swap the operands to fix both.
13349         std::swap(LHS, RHS);
13350       case ISD::SETOLT:
13351       case ISD::SETLT:
13352       case ISD::SETLE:
13353         Opcode = X86ISD::FMIN;
13354         break;
13355
13356       case ISD::SETOGE:
13357         // Converting this to a max would handle comparisons between positive
13358         // and negative zero incorrectly.
13359         if (!DAG.getTarget().Options.UnsafeFPMath &&
13360             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13361           break;
13362         Opcode = X86ISD::FMAX;
13363         break;
13364       case ISD::SETUGT:
13365         // Converting this to a max would handle NaNs incorrectly, and swapping
13366         // the operands would cause it to handle comparisons between positive
13367         // and negative zero incorrectly.
13368         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13369           if (!DAG.getTarget().Options.UnsafeFPMath &&
13370               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13371             break;
13372           std::swap(LHS, RHS);
13373         }
13374         Opcode = X86ISD::FMAX;
13375         break;
13376       case ISD::SETUGE:
13377         // Converting this to a max would handle both negative zeros and NaNs
13378         // incorrectly, but we can swap the operands to fix both.
13379         std::swap(LHS, RHS);
13380       case ISD::SETOGT:
13381       case ISD::SETGT:
13382       case ISD::SETGE:
13383         Opcode = X86ISD::FMAX;
13384         break;
13385       }
13386     // Check for x CC y ? y : x -- a min/max with reversed arms.
13387     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13388                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13389       switch (CC) {
13390       default: break;
13391       case ISD::SETOGE:
13392         // Converting this to a min would handle comparisons between positive
13393         // and negative zero incorrectly, and swapping the operands would
13394         // cause it to handle NaNs incorrectly.
13395         if (!DAG.getTarget().Options.UnsafeFPMath &&
13396             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13397           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13398             break;
13399           std::swap(LHS, RHS);
13400         }
13401         Opcode = X86ISD::FMIN;
13402         break;
13403       case ISD::SETUGT:
13404         // Converting this to a min would handle NaNs incorrectly.
13405         if (!DAG.getTarget().Options.UnsafeFPMath &&
13406             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13407           break;
13408         Opcode = X86ISD::FMIN;
13409         break;
13410       case ISD::SETUGE:
13411         // Converting this to a min would handle both negative zeros and NaNs
13412         // incorrectly, but we can swap the operands to fix both.
13413         std::swap(LHS, RHS);
13414       case ISD::SETOGT:
13415       case ISD::SETGT:
13416       case ISD::SETGE:
13417         Opcode = X86ISD::FMIN;
13418         break;
13419
13420       case ISD::SETULT:
13421         // Converting this to a max would handle NaNs incorrectly.
13422         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13423           break;
13424         Opcode = X86ISD::FMAX;
13425         break;
13426       case ISD::SETOLE:
13427         // Converting this to a max would handle comparisons between positive
13428         // and negative zero incorrectly, and swapping the operands would
13429         // cause it to handle NaNs incorrectly.
13430         if (!DAG.getTarget().Options.UnsafeFPMath &&
13431             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13432           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13433             break;
13434           std::swap(LHS, RHS);
13435         }
13436         Opcode = X86ISD::FMAX;
13437         break;
13438       case ISD::SETULE:
13439         // Converting this to a max would handle both negative zeros and NaNs
13440         // incorrectly, but we can swap the operands to fix both.
13441         std::swap(LHS, RHS);
13442       case ISD::SETOLT:
13443       case ISD::SETLT:
13444       case ISD::SETLE:
13445         Opcode = X86ISD::FMAX;
13446         break;
13447       }
13448     }
13449
13450     if (Opcode)
13451       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13452   }
13453
13454   // If this is a select between two integer constants, try to do some
13455   // optimizations.
13456   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13457     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13458       // Don't do this for crazy integer types.
13459       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13460         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13461         // so that TrueC (the true value) is larger than FalseC.
13462         bool NeedsCondInvert = false;
13463
13464         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13465             // Efficiently invertible.
13466             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13467              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13468               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13469           NeedsCondInvert = true;
13470           std::swap(TrueC, FalseC);
13471         }
13472
13473         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13474         if (FalseC->getAPIntValue() == 0 &&
13475             TrueC->getAPIntValue().isPowerOf2()) {
13476           if (NeedsCondInvert) // Invert the condition if needed.
13477             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13478                                DAG.getConstant(1, Cond.getValueType()));
13479
13480           // Zero extend the condition if needed.
13481           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13482
13483           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13484           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13485                              DAG.getConstant(ShAmt, MVT::i8));
13486         }
13487
13488         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13489         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13490           if (NeedsCondInvert) // Invert the condition if needed.
13491             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13492                                DAG.getConstant(1, Cond.getValueType()));
13493
13494           // Zero extend the condition if needed.
13495           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13496                              FalseC->getValueType(0), Cond);
13497           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13498                              SDValue(FalseC, 0));
13499         }
13500
13501         // Optimize cases that will turn into an LEA instruction.  This requires
13502         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13503         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13504           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13505           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13506
13507           bool isFastMultiplier = false;
13508           if (Diff < 10) {
13509             switch ((unsigned char)Diff) {
13510               default: break;
13511               case 1:  // result = add base, cond
13512               case 2:  // result = lea base(    , cond*2)
13513               case 3:  // result = lea base(cond, cond*2)
13514               case 4:  // result = lea base(    , cond*4)
13515               case 5:  // result = lea base(cond, cond*4)
13516               case 8:  // result = lea base(    , cond*8)
13517               case 9:  // result = lea base(cond, cond*8)
13518                 isFastMultiplier = true;
13519                 break;
13520             }
13521           }
13522
13523           if (isFastMultiplier) {
13524             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13525             if (NeedsCondInvert) // Invert the condition if needed.
13526               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13527                                  DAG.getConstant(1, Cond.getValueType()));
13528
13529             // Zero extend the condition if needed.
13530             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13531                                Cond);
13532             // Scale the condition by the difference.
13533             if (Diff != 1)
13534               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13535                                  DAG.getConstant(Diff, Cond.getValueType()));
13536
13537             // Add the base if non-zero.
13538             if (FalseC->getAPIntValue() != 0)
13539               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13540                                  SDValue(FalseC, 0));
13541             return Cond;
13542           }
13543         }
13544       }
13545   }
13546
13547   // Canonicalize max and min:
13548   // (x > y) ? x : y -> (x >= y) ? x : y
13549   // (x < y) ? x : y -> (x <= y) ? x : y
13550   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13551   // the need for an extra compare
13552   // against zero. e.g.
13553   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13554   // subl   %esi, %edi
13555   // testl  %edi, %edi
13556   // movl   $0, %eax
13557   // cmovgl %edi, %eax
13558   // =>
13559   // xorl   %eax, %eax
13560   // subl   %esi, $edi
13561   // cmovsl %eax, %edi
13562   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13563       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13564       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13565     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13566     switch (CC) {
13567     default: break;
13568     case ISD::SETLT:
13569     case ISD::SETGT: {
13570       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13571       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13572                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
13573       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13574     }
13575     }
13576   }
13577
13578   // If we know that this node is legal then we know that it is going to be
13579   // matched by one of the SSE/AVX BLEND instructions. These instructions only
13580   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13581   // to simplify previous instructions.
13582   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13583   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13584       !DCI.isBeforeLegalize() &&
13585       TLI.isOperationLegal(ISD::VSELECT, VT)) {
13586     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13587     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13588     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13589
13590     APInt KnownZero, KnownOne;
13591     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13592                                           DCI.isBeforeLegalizeOps());
13593     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13594         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13595       DCI.CommitTargetLoweringOpt(TLO);
13596   }
13597
13598   return SDValue();
13599 }
13600
13601 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13602 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13603                                   TargetLowering::DAGCombinerInfo &DCI) {
13604   DebugLoc DL = N->getDebugLoc();
13605
13606   // If the flag operand isn't dead, don't touch this CMOV.
13607   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13608     return SDValue();
13609
13610   SDValue FalseOp = N->getOperand(0);
13611   SDValue TrueOp = N->getOperand(1);
13612   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13613   SDValue Cond = N->getOperand(3);
13614   if (CC == X86::COND_E || CC == X86::COND_NE) {
13615     switch (Cond.getOpcode()) {
13616     default: break;
13617     case X86ISD::BSR:
13618     case X86ISD::BSF:
13619       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13620       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13621         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13622     }
13623   }
13624
13625   // If this is a select between two integer constants, try to do some
13626   // optimizations.  Note that the operands are ordered the opposite of SELECT
13627   // operands.
13628   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13629     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13630       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13631       // larger than FalseC (the false value).
13632       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13633         CC = X86::GetOppositeBranchCondition(CC);
13634         std::swap(TrueC, FalseC);
13635       }
13636
13637       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13638       // This is efficient for any integer data type (including i8/i16) and
13639       // shift amount.
13640       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13641         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13642                            DAG.getConstant(CC, MVT::i8), Cond);
13643
13644         // Zero extend the condition if needed.
13645         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13646
13647         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13648         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13649                            DAG.getConstant(ShAmt, MVT::i8));
13650         if (N->getNumValues() == 2)  // Dead flag value?
13651           return DCI.CombineTo(N, Cond, SDValue());
13652         return Cond;
13653       }
13654
13655       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13656       // for any integer data type, including i8/i16.
13657       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13658         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13659                            DAG.getConstant(CC, MVT::i8), Cond);
13660
13661         // Zero extend the condition if needed.
13662         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13663                            FalseC->getValueType(0), Cond);
13664         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13665                            SDValue(FalseC, 0));
13666
13667         if (N->getNumValues() == 2)  // Dead flag value?
13668           return DCI.CombineTo(N, Cond, SDValue());
13669         return Cond;
13670       }
13671
13672       // Optimize cases that will turn into an LEA instruction.  This requires
13673       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13674       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13675         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13676         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13677
13678         bool isFastMultiplier = false;
13679         if (Diff < 10) {
13680           switch ((unsigned char)Diff) {
13681           default: break;
13682           case 1:  // result = add base, cond
13683           case 2:  // result = lea base(    , cond*2)
13684           case 3:  // result = lea base(cond, cond*2)
13685           case 4:  // result = lea base(    , cond*4)
13686           case 5:  // result = lea base(cond, cond*4)
13687           case 8:  // result = lea base(    , cond*8)
13688           case 9:  // result = lea base(cond, cond*8)
13689             isFastMultiplier = true;
13690             break;
13691           }
13692         }
13693
13694         if (isFastMultiplier) {
13695           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13696           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13697                              DAG.getConstant(CC, MVT::i8), Cond);
13698           // Zero extend the condition if needed.
13699           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13700                              Cond);
13701           // Scale the condition by the difference.
13702           if (Diff != 1)
13703             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13704                                DAG.getConstant(Diff, Cond.getValueType()));
13705
13706           // Add the base if non-zero.
13707           if (FalseC->getAPIntValue() != 0)
13708             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13709                                SDValue(FalseC, 0));
13710           if (N->getNumValues() == 2)  // Dead flag value?
13711             return DCI.CombineTo(N, Cond, SDValue());
13712           return Cond;
13713         }
13714       }
13715     }
13716   }
13717   return SDValue();
13718 }
13719
13720
13721 /// PerformMulCombine - Optimize a single multiply with constant into two
13722 /// in order to implement it with two cheaper instructions, e.g.
13723 /// LEA + SHL, LEA + LEA.
13724 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13725                                  TargetLowering::DAGCombinerInfo &DCI) {
13726   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13727     return SDValue();
13728
13729   EVT VT = N->getValueType(0);
13730   if (VT != MVT::i64)
13731     return SDValue();
13732
13733   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13734   if (!C)
13735     return SDValue();
13736   uint64_t MulAmt = C->getZExtValue();
13737   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13738     return SDValue();
13739
13740   uint64_t MulAmt1 = 0;
13741   uint64_t MulAmt2 = 0;
13742   if ((MulAmt % 9) == 0) {
13743     MulAmt1 = 9;
13744     MulAmt2 = MulAmt / 9;
13745   } else if ((MulAmt % 5) == 0) {
13746     MulAmt1 = 5;
13747     MulAmt2 = MulAmt / 5;
13748   } else if ((MulAmt % 3) == 0) {
13749     MulAmt1 = 3;
13750     MulAmt2 = MulAmt / 3;
13751   }
13752   if (MulAmt2 &&
13753       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13754     DebugLoc DL = N->getDebugLoc();
13755
13756     if (isPowerOf2_64(MulAmt2) &&
13757         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13758       // If second multiplifer is pow2, issue it first. We want the multiply by
13759       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13760       // is an add.
13761       std::swap(MulAmt1, MulAmt2);
13762
13763     SDValue NewMul;
13764     if (isPowerOf2_64(MulAmt1))
13765       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13766                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13767     else
13768       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13769                            DAG.getConstant(MulAmt1, VT));
13770
13771     if (isPowerOf2_64(MulAmt2))
13772       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13773                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13774     else
13775       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13776                            DAG.getConstant(MulAmt2, VT));
13777
13778     // Do not add new nodes to DAG combiner worklist.
13779     DCI.CombineTo(N, NewMul, false);
13780   }
13781   return SDValue();
13782 }
13783
13784 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13785   SDValue N0 = N->getOperand(0);
13786   SDValue N1 = N->getOperand(1);
13787   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13788   EVT VT = N0.getValueType();
13789
13790   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13791   // since the result of setcc_c is all zero's or all ones.
13792   if (VT.isInteger() && !VT.isVector() &&
13793       N1C && N0.getOpcode() == ISD::AND &&
13794       N0.getOperand(1).getOpcode() == ISD::Constant) {
13795     SDValue N00 = N0.getOperand(0);
13796     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13797         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13798           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13799          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13800       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13801       APInt ShAmt = N1C->getAPIntValue();
13802       Mask = Mask.shl(ShAmt);
13803       if (Mask != 0)
13804         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13805                            N00, DAG.getConstant(Mask, VT));
13806     }
13807   }
13808
13809
13810   // Hardware support for vector shifts is sparse which makes us scalarize the
13811   // vector operations in many cases. Also, on sandybridge ADD is faster than
13812   // shl.
13813   // (shl V, 1) -> add V,V
13814   if (isSplatVector(N1.getNode())) {
13815     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13816     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13817     // We shift all of the values by one. In many cases we do not have
13818     // hardware support for this operation. This is better expressed as an ADD
13819     // of two values.
13820     if (N1C && (1 == N1C->getZExtValue())) {
13821       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13822     }
13823   }
13824
13825   return SDValue();
13826 }
13827
13828 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13829 ///                       when possible.
13830 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13831                                    TargetLowering::DAGCombinerInfo &DCI,
13832                                    const X86Subtarget *Subtarget) {
13833   EVT VT = N->getValueType(0);
13834   if (N->getOpcode() == ISD::SHL) {
13835     SDValue V = PerformSHLCombine(N, DAG);
13836     if (V.getNode()) return V;
13837   }
13838
13839   // On X86 with SSE2 support, we can transform this to a vector shift if
13840   // all elements are shifted by the same amount.  We can't do this in legalize
13841   // because the a constant vector is typically transformed to a constant pool
13842   // so we have no knowledge of the shift amount.
13843   if (!Subtarget->hasSSE2())
13844     return SDValue();
13845
13846   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13847       (!Subtarget->hasAVX2() ||
13848        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13849     return SDValue();
13850
13851   SDValue ShAmtOp = N->getOperand(1);
13852   EVT EltVT = VT.getVectorElementType();
13853   DebugLoc DL = N->getDebugLoc();
13854   SDValue BaseShAmt = SDValue();
13855   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13856     unsigned NumElts = VT.getVectorNumElements();
13857     unsigned i = 0;
13858     for (; i != NumElts; ++i) {
13859       SDValue Arg = ShAmtOp.getOperand(i);
13860       if (Arg.getOpcode() == ISD::UNDEF) continue;
13861       BaseShAmt = Arg;
13862       break;
13863     }
13864     // Handle the case where the build_vector is all undef
13865     // FIXME: Should DAG allow this?
13866     if (i == NumElts)
13867       return SDValue();
13868
13869     for (; i != NumElts; ++i) {
13870       SDValue Arg = ShAmtOp.getOperand(i);
13871       if (Arg.getOpcode() == ISD::UNDEF) continue;
13872       if (Arg != BaseShAmt) {
13873         return SDValue();
13874       }
13875     }
13876   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13877              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13878     SDValue InVec = ShAmtOp.getOperand(0);
13879     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13880       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13881       unsigned i = 0;
13882       for (; i != NumElts; ++i) {
13883         SDValue Arg = InVec.getOperand(i);
13884         if (Arg.getOpcode() == ISD::UNDEF) continue;
13885         BaseShAmt = Arg;
13886         break;
13887       }
13888     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13889        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13890          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13891          if (C->getZExtValue() == SplatIdx)
13892            BaseShAmt = InVec.getOperand(1);
13893        }
13894     }
13895     if (BaseShAmt.getNode() == 0) {
13896       // Don't create instructions with illegal types after legalize
13897       // types has run.
13898       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
13899           !DCI.isBeforeLegalize())
13900         return SDValue();
13901
13902       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13903                               DAG.getIntPtrConstant(0));
13904     }
13905   } else
13906     return SDValue();
13907
13908   // The shift amount is an i32.
13909   if (EltVT.bitsGT(MVT::i32))
13910     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13911   else if (EltVT.bitsLT(MVT::i32))
13912     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13913
13914   // The shift amount is identical so we can do a vector shift.
13915   SDValue  ValOp = N->getOperand(0);
13916   switch (N->getOpcode()) {
13917   default:
13918     llvm_unreachable("Unknown shift opcode!");
13919   case ISD::SHL:
13920     switch (VT.getSimpleVT().SimpleTy) {
13921     default: return SDValue();
13922     case MVT::v2i64:
13923     case MVT::v4i32:
13924     case MVT::v8i16:
13925     case MVT::v4i64:
13926     case MVT::v8i32:
13927     case MVT::v16i16:
13928       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
13929     }
13930   case ISD::SRA:
13931     switch (VT.getSimpleVT().SimpleTy) {
13932     default: return SDValue();
13933     case MVT::v4i32:
13934     case MVT::v8i16:
13935     case MVT::v8i32:
13936     case MVT::v16i16:
13937       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
13938     }
13939   case ISD::SRL:
13940     switch (VT.getSimpleVT().SimpleTy) {
13941     default: return SDValue();
13942     case MVT::v2i64:
13943     case MVT::v4i32:
13944     case MVT::v8i16:
13945     case MVT::v4i64:
13946     case MVT::v8i32:
13947     case MVT::v16i16:
13948       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
13949     }
13950   }
13951 }
13952
13953
13954 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13955 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13956 // and friends.  Likewise for OR -> CMPNEQSS.
13957 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13958                             TargetLowering::DAGCombinerInfo &DCI,
13959                             const X86Subtarget *Subtarget) {
13960   unsigned opcode;
13961
13962   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13963   // we're requiring SSE2 for both.
13964   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13965     SDValue N0 = N->getOperand(0);
13966     SDValue N1 = N->getOperand(1);
13967     SDValue CMP0 = N0->getOperand(1);
13968     SDValue CMP1 = N1->getOperand(1);
13969     DebugLoc DL = N->getDebugLoc();
13970
13971     // The SETCCs should both refer to the same CMP.
13972     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13973       return SDValue();
13974
13975     SDValue CMP00 = CMP0->getOperand(0);
13976     SDValue CMP01 = CMP0->getOperand(1);
13977     EVT     VT    = CMP00.getValueType();
13978
13979     if (VT == MVT::f32 || VT == MVT::f64) {
13980       bool ExpectingFlags = false;
13981       // Check for any users that want flags:
13982       for (SDNode::use_iterator UI = N->use_begin(),
13983              UE = N->use_end();
13984            !ExpectingFlags && UI != UE; ++UI)
13985         switch (UI->getOpcode()) {
13986         default:
13987         case ISD::BR_CC:
13988         case ISD::BRCOND:
13989         case ISD::SELECT:
13990           ExpectingFlags = true;
13991           break;
13992         case ISD::CopyToReg:
13993         case ISD::SIGN_EXTEND:
13994         case ISD::ZERO_EXTEND:
13995         case ISD::ANY_EXTEND:
13996           break;
13997         }
13998
13999       if (!ExpectingFlags) {
14000         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14001         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14002
14003         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14004           X86::CondCode tmp = cc0;
14005           cc0 = cc1;
14006           cc1 = tmp;
14007         }
14008
14009         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
14010             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14011           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14012           X86ISD::NodeType NTOperator = is64BitFP ?
14013             X86ISD::FSETCCsd : X86ISD::FSETCCss;
14014           // FIXME: need symbolic constants for these magic numbers.
14015           // See X86ATTInstPrinter.cpp:printSSECC().
14016           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14017           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14018                                               DAG.getConstant(x86cc, MVT::i8));
14019           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14020                                               OnesOrZeroesF);
14021           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14022                                       DAG.getConstant(1, MVT::i32));
14023           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14024           return OneBitOfTruth;
14025         }
14026       }
14027     }
14028   }
14029   return SDValue();
14030 }
14031
14032 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14033 /// so it can be folded inside ANDNP.
14034 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14035   EVT VT = N->getValueType(0);
14036
14037   // Match direct AllOnes for 128 and 256-bit vectors
14038   if (ISD::isBuildVectorAllOnes(N))
14039     return true;
14040
14041   // Look through a bit convert.
14042   if (N->getOpcode() == ISD::BITCAST)
14043     N = N->getOperand(0).getNode();
14044
14045   // Sometimes the operand may come from a insert_subvector building a 256-bit
14046   // allones vector
14047   if (VT.getSizeInBits() == 256 &&
14048       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14049     SDValue V1 = N->getOperand(0);
14050     SDValue V2 = N->getOperand(1);
14051
14052     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14053         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14054         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14055         ISD::isBuildVectorAllOnes(V2.getNode()))
14056       return true;
14057   }
14058
14059   return false;
14060 }
14061
14062 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14063                                  TargetLowering::DAGCombinerInfo &DCI,
14064                                  const X86Subtarget *Subtarget) {
14065   if (DCI.isBeforeLegalizeOps())
14066     return SDValue();
14067
14068   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14069   if (R.getNode())
14070     return R;
14071
14072   EVT VT = N->getValueType(0);
14073
14074   // Create ANDN, BLSI, and BLSR instructions
14075   // BLSI is X & (-X)
14076   // BLSR is X & (X-1)
14077   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14078     SDValue N0 = N->getOperand(0);
14079     SDValue N1 = N->getOperand(1);
14080     DebugLoc DL = N->getDebugLoc();
14081
14082     // Check LHS for not
14083     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14084       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14085     // Check RHS for not
14086     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14087       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14088
14089     // Check LHS for neg
14090     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14091         isZero(N0.getOperand(0)))
14092       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14093
14094     // Check RHS for neg
14095     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14096         isZero(N1.getOperand(0)))
14097       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14098
14099     // Check LHS for X-1
14100     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14101         isAllOnes(N0.getOperand(1)))
14102       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14103
14104     // Check RHS for X-1
14105     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14106         isAllOnes(N1.getOperand(1)))
14107       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14108
14109     return SDValue();
14110   }
14111
14112   // Want to form ANDNP nodes:
14113   // 1) In the hopes of then easily combining them with OR and AND nodes
14114   //    to form PBLEND/PSIGN.
14115   // 2) To match ANDN packed intrinsics
14116   if (VT != MVT::v2i64 && VT != MVT::v4i64)
14117     return SDValue();
14118
14119   SDValue N0 = N->getOperand(0);
14120   SDValue N1 = N->getOperand(1);
14121   DebugLoc DL = N->getDebugLoc();
14122
14123   // Check LHS for vnot
14124   if (N0.getOpcode() == ISD::XOR &&
14125       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14126       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14127     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14128
14129   // Check RHS for vnot
14130   if (N1.getOpcode() == ISD::XOR &&
14131       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14132       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14133     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14134
14135   return SDValue();
14136 }
14137
14138 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14139                                 TargetLowering::DAGCombinerInfo &DCI,
14140                                 const X86Subtarget *Subtarget) {
14141   if (DCI.isBeforeLegalizeOps())
14142     return SDValue();
14143
14144   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14145   if (R.getNode())
14146     return R;
14147
14148   EVT VT = N->getValueType(0);
14149
14150   SDValue N0 = N->getOperand(0);
14151   SDValue N1 = N->getOperand(1);
14152
14153   // look for psign/blend
14154   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14155     if (!Subtarget->hasSSSE3() ||
14156         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14157       return SDValue();
14158
14159     // Canonicalize pandn to RHS
14160     if (N0.getOpcode() == X86ISD::ANDNP)
14161       std::swap(N0, N1);
14162     // or (and (m, y), (pandn m, x))
14163     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14164       SDValue Mask = N1.getOperand(0);
14165       SDValue X    = N1.getOperand(1);
14166       SDValue Y;
14167       if (N0.getOperand(0) == Mask)
14168         Y = N0.getOperand(1);
14169       if (N0.getOperand(1) == Mask)
14170         Y = N0.getOperand(0);
14171
14172       // Check to see if the mask appeared in both the AND and ANDNP and
14173       if (!Y.getNode())
14174         return SDValue();
14175
14176       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14177       // Look through mask bitcast.
14178       if (Mask.getOpcode() == ISD::BITCAST)
14179         Mask = Mask.getOperand(0);
14180       if (X.getOpcode() == ISD::BITCAST)
14181         X = X.getOperand(0);
14182       if (Y.getOpcode() == ISD::BITCAST)
14183         Y = Y.getOperand(0);
14184
14185       EVT MaskVT = Mask.getValueType();
14186
14187       // Validate that the Mask operand is a vector sra node.
14188       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14189       // there is no psrai.b
14190       if (Mask.getOpcode() != X86ISD::VSRAI)
14191         return SDValue();
14192
14193       // Check that the SRA is all signbits.
14194       SDValue SraC = Mask.getOperand(1);
14195       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14196       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14197       if ((SraAmt + 1) != EltBits)
14198         return SDValue();
14199
14200       DebugLoc DL = N->getDebugLoc();
14201
14202       // Now we know we at least have a plendvb with the mask val.  See if
14203       // we can form a psignb/w/d.
14204       // psign = x.type == y.type == mask.type && y = sub(0, x);
14205       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14206           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14207           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14208         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14209                "Unsupported VT for PSIGN");
14210         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14211         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14212       }
14213       // PBLENDVB only available on SSE 4.1
14214       if (!Subtarget->hasSSE41())
14215         return SDValue();
14216
14217       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14218
14219       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14220       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14221       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14222       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14223       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14224     }
14225   }
14226
14227   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14228     return SDValue();
14229
14230   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14231   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14232     std::swap(N0, N1);
14233   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14234     return SDValue();
14235   if (!N0.hasOneUse() || !N1.hasOneUse())
14236     return SDValue();
14237
14238   SDValue ShAmt0 = N0.getOperand(1);
14239   if (ShAmt0.getValueType() != MVT::i8)
14240     return SDValue();
14241   SDValue ShAmt1 = N1.getOperand(1);
14242   if (ShAmt1.getValueType() != MVT::i8)
14243     return SDValue();
14244   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14245     ShAmt0 = ShAmt0.getOperand(0);
14246   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14247     ShAmt1 = ShAmt1.getOperand(0);
14248
14249   DebugLoc DL = N->getDebugLoc();
14250   unsigned Opc = X86ISD::SHLD;
14251   SDValue Op0 = N0.getOperand(0);
14252   SDValue Op1 = N1.getOperand(0);
14253   if (ShAmt0.getOpcode() == ISD::SUB) {
14254     Opc = X86ISD::SHRD;
14255     std::swap(Op0, Op1);
14256     std::swap(ShAmt0, ShAmt1);
14257   }
14258
14259   unsigned Bits = VT.getSizeInBits();
14260   if (ShAmt1.getOpcode() == ISD::SUB) {
14261     SDValue Sum = ShAmt1.getOperand(0);
14262     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14263       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14264       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14265         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14266       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14267         return DAG.getNode(Opc, DL, VT,
14268                            Op0, Op1,
14269                            DAG.getNode(ISD::TRUNCATE, DL,
14270                                        MVT::i8, ShAmt0));
14271     }
14272   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14273     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14274     if (ShAmt0C &&
14275         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14276       return DAG.getNode(Opc, DL, VT,
14277                          N0.getOperand(0), N1.getOperand(0),
14278                          DAG.getNode(ISD::TRUNCATE, DL,
14279                                        MVT::i8, ShAmt0));
14280   }
14281
14282   return SDValue();
14283 }
14284
14285 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14286 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14287                                  TargetLowering::DAGCombinerInfo &DCI,
14288                                  const X86Subtarget *Subtarget) {
14289   if (DCI.isBeforeLegalizeOps())
14290     return SDValue();
14291
14292   EVT VT = N->getValueType(0);
14293
14294   if (VT != MVT::i32 && VT != MVT::i64)
14295     return SDValue();
14296
14297   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14298
14299   // Create BLSMSK instructions by finding X ^ (X-1)
14300   SDValue N0 = N->getOperand(0);
14301   SDValue N1 = N->getOperand(1);
14302   DebugLoc DL = N->getDebugLoc();
14303
14304   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14305       isAllOnes(N0.getOperand(1)))
14306     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14307
14308   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14309       isAllOnes(N1.getOperand(1)))
14310     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14311
14312   return SDValue();
14313 }
14314
14315 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14316 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14317                                    const X86Subtarget *Subtarget) {
14318   LoadSDNode *Ld = cast<LoadSDNode>(N);
14319   EVT RegVT = Ld->getValueType(0);
14320   EVT MemVT = Ld->getMemoryVT();
14321   DebugLoc dl = Ld->getDebugLoc();
14322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14323
14324   ISD::LoadExtType Ext = Ld->getExtensionType();
14325
14326   // If this is a vector EXT Load then attempt to optimize it using a
14327   // shuffle. We need SSE4 for the shuffles.
14328   // TODO: It is possible to support ZExt by zeroing the undef values
14329   // during the shuffle phase or after the shuffle.
14330   if (RegVT.isVector() && RegVT.isInteger() &&
14331       Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14332     assert(MemVT != RegVT && "Cannot extend to the same type");
14333     assert(MemVT.isVector() && "Must load a vector from memory");
14334
14335     unsigned NumElems = RegVT.getVectorNumElements();
14336     unsigned RegSz = RegVT.getSizeInBits();
14337     unsigned MemSz = MemVT.getSizeInBits();
14338     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14339     // All sizes must be a power of two
14340     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14341
14342     // Attempt to load the original value using a single load op.
14343     // Find a scalar type which is equal to the loaded word size.
14344     MVT SclrLoadTy = MVT::i8;
14345     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14346          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14347       MVT Tp = (MVT::SimpleValueType)tp;
14348       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14349         SclrLoadTy = Tp;
14350         break;
14351       }
14352     }
14353
14354     // Proceed if a load word is found.
14355     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14356
14357     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14358       RegSz/SclrLoadTy.getSizeInBits());
14359
14360     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14361                                   RegSz/MemVT.getScalarType().getSizeInBits());
14362     // Can't shuffle using an illegal type.
14363     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14364
14365     // Perform a single load.
14366     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14367                                   Ld->getBasePtr(),
14368                                   Ld->getPointerInfo(), Ld->isVolatile(),
14369                                   Ld->isNonTemporal(), Ld->isInvariant(),
14370                                   Ld->getAlignment());
14371
14372     // Insert the word loaded into a vector.
14373     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14374       LoadUnitVecVT, ScalarLoad);
14375
14376     // Bitcast the loaded value to a vector of the original element type, in
14377     // the size of the target vector type.
14378     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14379                                     ScalarInVector);
14380     unsigned SizeRatio = RegSz/MemSz;
14381
14382     // Redistribute the loaded elements into the different locations.
14383     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14384     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14385
14386     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14387                                          DAG.getUNDEF(WideVecVT),
14388                                          &ShuffleVec[0]);
14389
14390     // Bitcast to the requested type.
14391     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14392     // Replace the original load with the new sequence
14393     // and return the new chain.
14394     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14395     return SDValue(ScalarLoad.getNode(), 1);
14396   }
14397
14398   return SDValue();
14399 }
14400
14401 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14402 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14403                                    const X86Subtarget *Subtarget) {
14404   StoreSDNode *St = cast<StoreSDNode>(N);
14405   EVT VT = St->getValue().getValueType();
14406   EVT StVT = St->getMemoryVT();
14407   DebugLoc dl = St->getDebugLoc();
14408   SDValue StoredVal = St->getOperand(1);
14409   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14410
14411   // If we are saving a concatenation of two XMM registers, perform two stores.
14412   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14413   // 128-bit ones. If in the future the cost becomes only one memory access the
14414   // first version would be better.
14415   if (VT.getSizeInBits() == 256 &&
14416     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14417     StoredVal.getNumOperands() == 2) {
14418
14419     SDValue Value0 = StoredVal.getOperand(0);
14420     SDValue Value1 = StoredVal.getOperand(1);
14421
14422     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14423     SDValue Ptr0 = St->getBasePtr();
14424     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14425
14426     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14427                                 St->getPointerInfo(), St->isVolatile(),
14428                                 St->isNonTemporal(), St->getAlignment());
14429     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14430                                 St->getPointerInfo(), St->isVolatile(),
14431                                 St->isNonTemporal(), St->getAlignment());
14432     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14433   }
14434
14435   // Optimize trunc store (of multiple scalars) to shuffle and store.
14436   // First, pack all of the elements in one place. Next, store to memory
14437   // in fewer chunks.
14438   if (St->isTruncatingStore() && VT.isVector()) {
14439     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14440     unsigned NumElems = VT.getVectorNumElements();
14441     assert(StVT != VT && "Cannot truncate to the same type");
14442     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14443     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14444
14445     // From, To sizes and ElemCount must be pow of two
14446     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14447     // We are going to use the original vector elt for storing.
14448     // Accumulated smaller vector elements must be a multiple of the store size.
14449     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14450
14451     unsigned SizeRatio  = FromSz / ToSz;
14452
14453     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14454
14455     // Create a type on which we perform the shuffle
14456     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14457             StVT.getScalarType(), NumElems*SizeRatio);
14458
14459     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14460
14461     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14462     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14463     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14464
14465     // Can't shuffle using an illegal type
14466     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14467
14468     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14469                                          DAG.getUNDEF(WideVecVT),
14470                                          &ShuffleVec[0]);
14471     // At this point all of the data is stored at the bottom of the
14472     // register. We now need to save it to mem.
14473
14474     // Find the largest store unit
14475     MVT StoreType = MVT::i8;
14476     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14477          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14478       MVT Tp = (MVT::SimpleValueType)tp;
14479       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14480         StoreType = Tp;
14481     }
14482
14483     // Bitcast the original vector into a vector of store-size units
14484     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14485             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14486     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14487     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14488     SmallVector<SDValue, 8> Chains;
14489     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14490                                         TLI.getPointerTy());
14491     SDValue Ptr = St->getBasePtr();
14492
14493     // Perform one or more big stores into memory.
14494     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14495       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14496                                    StoreType, ShuffWide,
14497                                    DAG.getIntPtrConstant(i));
14498       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14499                                 St->getPointerInfo(), St->isVolatile(),
14500                                 St->isNonTemporal(), St->getAlignment());
14501       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14502       Chains.push_back(Ch);
14503     }
14504
14505     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14506                                Chains.size());
14507   }
14508
14509
14510   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14511   // the FP state in cases where an emms may be missing.
14512   // A preferable solution to the general problem is to figure out the right
14513   // places to insert EMMS.  This qualifies as a quick hack.
14514
14515   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14516   if (VT.getSizeInBits() != 64)
14517     return SDValue();
14518
14519   const Function *F = DAG.getMachineFunction().getFunction();
14520   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14521   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14522                      && Subtarget->hasSSE2();
14523   if ((VT.isVector() ||
14524        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14525       isa<LoadSDNode>(St->getValue()) &&
14526       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14527       St->getChain().hasOneUse() && !St->isVolatile()) {
14528     SDNode* LdVal = St->getValue().getNode();
14529     LoadSDNode *Ld = 0;
14530     int TokenFactorIndex = -1;
14531     SmallVector<SDValue, 8> Ops;
14532     SDNode* ChainVal = St->getChain().getNode();
14533     // Must be a store of a load.  We currently handle two cases:  the load
14534     // is a direct child, and it's under an intervening TokenFactor.  It is
14535     // possible to dig deeper under nested TokenFactors.
14536     if (ChainVal == LdVal)
14537       Ld = cast<LoadSDNode>(St->getChain());
14538     else if (St->getValue().hasOneUse() &&
14539              ChainVal->getOpcode() == ISD::TokenFactor) {
14540       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14541         if (ChainVal->getOperand(i).getNode() == LdVal) {
14542           TokenFactorIndex = i;
14543           Ld = cast<LoadSDNode>(St->getValue());
14544         } else
14545           Ops.push_back(ChainVal->getOperand(i));
14546       }
14547     }
14548
14549     if (!Ld || !ISD::isNormalLoad(Ld))
14550       return SDValue();
14551
14552     // If this is not the MMX case, i.e. we are just turning i64 load/store
14553     // into f64 load/store, avoid the transformation if there are multiple
14554     // uses of the loaded value.
14555     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14556       return SDValue();
14557
14558     DebugLoc LdDL = Ld->getDebugLoc();
14559     DebugLoc StDL = N->getDebugLoc();
14560     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14561     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14562     // pair instead.
14563     if (Subtarget->is64Bit() || F64IsLegal) {
14564       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14565       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14566                                   Ld->getPointerInfo(), Ld->isVolatile(),
14567                                   Ld->isNonTemporal(), Ld->isInvariant(),
14568                                   Ld->getAlignment());
14569       SDValue NewChain = NewLd.getValue(1);
14570       if (TokenFactorIndex != -1) {
14571         Ops.push_back(NewChain);
14572         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14573                                Ops.size());
14574       }
14575       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14576                           St->getPointerInfo(),
14577                           St->isVolatile(), St->isNonTemporal(),
14578                           St->getAlignment());
14579     }
14580
14581     // Otherwise, lower to two pairs of 32-bit loads / stores.
14582     SDValue LoAddr = Ld->getBasePtr();
14583     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14584                                  DAG.getConstant(4, MVT::i32));
14585
14586     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14587                                Ld->getPointerInfo(),
14588                                Ld->isVolatile(), Ld->isNonTemporal(),
14589                                Ld->isInvariant(), Ld->getAlignment());
14590     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14591                                Ld->getPointerInfo().getWithOffset(4),
14592                                Ld->isVolatile(), Ld->isNonTemporal(),
14593                                Ld->isInvariant(),
14594                                MinAlign(Ld->getAlignment(), 4));
14595
14596     SDValue NewChain = LoLd.getValue(1);
14597     if (TokenFactorIndex != -1) {
14598       Ops.push_back(LoLd);
14599       Ops.push_back(HiLd);
14600       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14601                              Ops.size());
14602     }
14603
14604     LoAddr = St->getBasePtr();
14605     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14606                          DAG.getConstant(4, MVT::i32));
14607
14608     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14609                                 St->getPointerInfo(),
14610                                 St->isVolatile(), St->isNonTemporal(),
14611                                 St->getAlignment());
14612     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14613                                 St->getPointerInfo().getWithOffset(4),
14614                                 St->isVolatile(),
14615                                 St->isNonTemporal(),
14616                                 MinAlign(St->getAlignment(), 4));
14617     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14618   }
14619   return SDValue();
14620 }
14621
14622 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14623 /// and return the operands for the horizontal operation in LHS and RHS.  A
14624 /// horizontal operation performs the binary operation on successive elements
14625 /// of its first operand, then on successive elements of its second operand,
14626 /// returning the resulting values in a vector.  For example, if
14627 ///   A = < float a0, float a1, float a2, float a3 >
14628 /// and
14629 ///   B = < float b0, float b1, float b2, float b3 >
14630 /// then the result of doing a horizontal operation on A and B is
14631 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14632 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14633 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14634 /// set to A, RHS to B, and the routine returns 'true'.
14635 /// Note that the binary operation should have the property that if one of the
14636 /// operands is UNDEF then the result is UNDEF.
14637 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14638   // Look for the following pattern: if
14639   //   A = < float a0, float a1, float a2, float a3 >
14640   //   B = < float b0, float b1, float b2, float b3 >
14641   // and
14642   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14643   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14644   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14645   // which is A horizontal-op B.
14646
14647   // At least one of the operands should be a vector shuffle.
14648   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14649       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14650     return false;
14651
14652   EVT VT = LHS.getValueType();
14653
14654   assert((VT.is128BitVector() || VT.is256BitVector()) &&
14655          "Unsupported vector type for horizontal add/sub");
14656
14657   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14658   // operate independently on 128-bit lanes.
14659   unsigned NumElts = VT.getVectorNumElements();
14660   unsigned NumLanes = VT.getSizeInBits()/128;
14661   unsigned NumLaneElts = NumElts / NumLanes;
14662   assert((NumLaneElts % 2 == 0) &&
14663          "Vector type should have an even number of elements in each lane");
14664   unsigned HalfLaneElts = NumLaneElts/2;
14665
14666   // View LHS in the form
14667   //   LHS = VECTOR_SHUFFLE A, B, LMask
14668   // If LHS is not a shuffle then pretend it is the shuffle
14669   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14670   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14671   // type VT.
14672   SDValue A, B;
14673   SmallVector<int, 16> LMask(NumElts);
14674   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14675     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14676       A = LHS.getOperand(0);
14677     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14678       B = LHS.getOperand(1);
14679     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14680     std::copy(Mask.begin(), Mask.end(), LMask.begin());
14681   } else {
14682     if (LHS.getOpcode() != ISD::UNDEF)
14683       A = LHS;
14684     for (unsigned i = 0; i != NumElts; ++i)
14685       LMask[i] = i;
14686   }
14687
14688   // Likewise, view RHS in the form
14689   //   RHS = VECTOR_SHUFFLE C, D, RMask
14690   SDValue C, D;
14691   SmallVector<int, 16> RMask(NumElts);
14692   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14693     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14694       C = RHS.getOperand(0);
14695     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14696       D = RHS.getOperand(1);
14697     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14698     std::copy(Mask.begin(), Mask.end(), RMask.begin());
14699   } else {
14700     if (RHS.getOpcode() != ISD::UNDEF)
14701       C = RHS;
14702     for (unsigned i = 0; i != NumElts; ++i)
14703       RMask[i] = i;
14704   }
14705
14706   // Check that the shuffles are both shuffling the same vectors.
14707   if (!(A == C && B == D) && !(A == D && B == C))
14708     return false;
14709
14710   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14711   if (!A.getNode() && !B.getNode())
14712     return false;
14713
14714   // If A and B occur in reverse order in RHS, then "swap" them (which means
14715   // rewriting the mask).
14716   if (A != C)
14717     CommuteVectorShuffleMask(RMask, NumElts);
14718
14719   // At this point LHS and RHS are equivalent to
14720   //   LHS = VECTOR_SHUFFLE A, B, LMask
14721   //   RHS = VECTOR_SHUFFLE A, B, RMask
14722   // Check that the masks correspond to performing a horizontal operation.
14723   for (unsigned i = 0; i != NumElts; ++i) {
14724     int LIdx = LMask[i], RIdx = RMask[i];
14725
14726     // Ignore any UNDEF components.
14727     if (LIdx < 0 || RIdx < 0 ||
14728         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14729         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14730       continue;
14731
14732     // Check that successive elements are being operated on.  If not, this is
14733     // not a horizontal operation.
14734     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14735     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14736     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14737     if (!(LIdx == Index && RIdx == Index + 1) &&
14738         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14739       return false;
14740   }
14741
14742   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14743   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14744   return true;
14745 }
14746
14747 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14748 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14749                                   const X86Subtarget *Subtarget) {
14750   EVT VT = N->getValueType(0);
14751   SDValue LHS = N->getOperand(0);
14752   SDValue RHS = N->getOperand(1);
14753
14754   // Try to synthesize horizontal adds from adds of shuffles.
14755   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14756        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14757       isHorizontalBinOp(LHS, RHS, true))
14758     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14759   return SDValue();
14760 }
14761
14762 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14763 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14764                                   const X86Subtarget *Subtarget) {
14765   EVT VT = N->getValueType(0);
14766   SDValue LHS = N->getOperand(0);
14767   SDValue RHS = N->getOperand(1);
14768
14769   // Try to synthesize horizontal subs from subs of shuffles.
14770   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14771        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14772       isHorizontalBinOp(LHS, RHS, false))
14773     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14774   return SDValue();
14775 }
14776
14777 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14778 /// X86ISD::FXOR nodes.
14779 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14780   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14781   // F[X]OR(0.0, x) -> x
14782   // F[X]OR(x, 0.0) -> x
14783   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14784     if (C->getValueAPF().isPosZero())
14785       return N->getOperand(1);
14786   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14787     if (C->getValueAPF().isPosZero())
14788       return N->getOperand(0);
14789   return SDValue();
14790 }
14791
14792 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14793 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14794   // FAND(0.0, x) -> 0.0
14795   // FAND(x, 0.0) -> 0.0
14796   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14797     if (C->getValueAPF().isPosZero())
14798       return N->getOperand(0);
14799   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14800     if (C->getValueAPF().isPosZero())
14801       return N->getOperand(1);
14802   return SDValue();
14803 }
14804
14805 static SDValue PerformBTCombine(SDNode *N,
14806                                 SelectionDAG &DAG,
14807                                 TargetLowering::DAGCombinerInfo &DCI) {
14808   // BT ignores high bits in the bit index operand.
14809   SDValue Op1 = N->getOperand(1);
14810   if (Op1.hasOneUse()) {
14811     unsigned BitWidth = Op1.getValueSizeInBits();
14812     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14813     APInt KnownZero, KnownOne;
14814     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14815                                           !DCI.isBeforeLegalizeOps());
14816     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14817     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14818         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14819       DCI.CommitTargetLoweringOpt(TLO);
14820   }
14821   return SDValue();
14822 }
14823
14824 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14825   SDValue Op = N->getOperand(0);
14826   if (Op.getOpcode() == ISD::BITCAST)
14827     Op = Op.getOperand(0);
14828   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14829   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14830       VT.getVectorElementType().getSizeInBits() ==
14831       OpVT.getVectorElementType().getSizeInBits()) {
14832     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14833   }
14834   return SDValue();
14835 }
14836
14837 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14838                                   TargetLowering::DAGCombinerInfo &DCI,
14839                                   const X86Subtarget *Subtarget) {
14840   if (!DCI.isBeforeLegalizeOps())
14841     return SDValue();
14842
14843   if (!Subtarget->hasAVX()) 
14844     return SDValue();
14845
14846   EVT VT = N->getValueType(0);
14847   SDValue Op = N->getOperand(0);
14848   EVT OpVT = Op.getValueType();
14849   DebugLoc dl = N->getDebugLoc();
14850
14851   if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
14852       (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
14853
14854     if (Subtarget->hasAVX2()) {
14855       return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
14856     }
14857
14858     // Optimize vectors in AVX mode
14859     // Sign extend  v8i16 to v8i32 and
14860     //              v4i32 to v4i64
14861     //
14862     // Divide input vector into two parts
14863     // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14864     // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14865     // concat the vectors to original VT
14866
14867     unsigned NumElems = OpVT.getVectorNumElements();
14868     SmallVector<int,8> ShufMask1(NumElems, -1);
14869     for (unsigned i = 0; i < NumElems/2; i++) ShufMask1[i] = i;
14870
14871     SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14872                                         &ShufMask1[0]);
14873
14874     SmallVector<int,8> ShufMask2(NumElems, -1);
14875     for (unsigned i = 0; i < NumElems/2; i++) ShufMask2[i] = i + NumElems/2;
14876
14877     SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
14878                                         &ShufMask2[0]);
14879
14880     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 
14881                                   VT.getVectorNumElements()/2);
14882
14883     OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo); 
14884     OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
14885
14886     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14887   }
14888   return SDValue();
14889 }
14890
14891 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
14892                                   const X86Subtarget *Subtarget) {
14893   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14894   //           (and (i32 x86isd::setcc_carry), 1)
14895   // This eliminates the zext. This transformation is necessary because
14896   // ISD::SETCC is always legalized to i8.
14897   DebugLoc dl = N->getDebugLoc();
14898   SDValue N0 = N->getOperand(0);
14899   EVT VT = N->getValueType(0);
14900   EVT OpVT = N0.getValueType();
14901
14902   if (N0.getOpcode() == ISD::AND &&
14903       N0.hasOneUse() &&
14904       N0.getOperand(0).hasOneUse()) {
14905     SDValue N00 = N0.getOperand(0);
14906     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14907       return SDValue();
14908     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14909     if (!C || C->getZExtValue() != 1)
14910       return SDValue();
14911     return DAG.getNode(ISD::AND, dl, VT,
14912                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14913                                    N00.getOperand(0), N00.getOperand(1)),
14914                        DAG.getConstant(1, VT));
14915   }
14916
14917   // Optimize vectors in AVX mode:
14918   //
14919   //   v8i16 -> v8i32
14920   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
14921   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
14922   //   Concat upper and lower parts.
14923   //
14924   //   v4i32 -> v4i64
14925   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
14926   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
14927   //   Concat upper and lower parts.
14928   //
14929   if (Subtarget->hasAVX()) {
14930
14931     if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
14932         ((VT == MVT::v4i64) && (OpVT == MVT::v4i32)))  {
14933
14934       if (Subtarget->hasAVX2())
14935         return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
14936
14937       SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
14938       SDValue OpLo = getTargetShuffleNode(X86ISD::UNPCKL, dl, OpVT, N0, ZeroVec,
14939                                           DAG);
14940       SDValue OpHi = getTargetShuffleNode(X86ISD::UNPCKH, dl, OpVT, N0, ZeroVec,
14941                                           DAG);
14942
14943       EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
14944                                  VT.getVectorNumElements()/2);
14945
14946       OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
14947       OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
14948
14949       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14950     }
14951   }
14952
14953   return SDValue();
14954 }
14955
14956 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14957 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14958   unsigned X86CC = N->getConstantOperandVal(0);
14959   SDValue EFLAG = N->getOperand(1);
14960   DebugLoc DL = N->getDebugLoc();
14961
14962   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14963   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14964   // cases.
14965   if (X86CC == X86::COND_B)
14966     return DAG.getNode(ISD::AND, DL, MVT::i8,
14967                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14968                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14969                        DAG.getConstant(1, MVT::i8));
14970
14971   return SDValue();
14972 }
14973
14974 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14975                                         const X86TargetLowering *XTLI) {
14976   SDValue Op0 = N->getOperand(0);
14977   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14978   // a 32-bit target where SSE doesn't support i64->FP operations.
14979   if (Op0.getOpcode() == ISD::LOAD) {
14980     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14981     EVT VT = Ld->getValueType(0);
14982     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14983         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14984         !XTLI->getSubtarget()->is64Bit() &&
14985         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14986       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14987                                           Ld->getChain(), Op0, DAG);
14988       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14989       return FILDChain;
14990     }
14991   }
14992   return SDValue();
14993 }
14994
14995 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14996 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14997                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14998   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14999   // the result is either zero or one (depending on the input carry bit).
15000   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15001   if (X86::isZeroNode(N->getOperand(0)) &&
15002       X86::isZeroNode(N->getOperand(1)) &&
15003       // We don't have a good way to replace an EFLAGS use, so only do this when
15004       // dead right now.
15005       SDValue(N, 1).use_empty()) {
15006     DebugLoc DL = N->getDebugLoc();
15007     EVT VT = N->getValueType(0);
15008     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15009     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15010                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15011                                            DAG.getConstant(X86::COND_B,MVT::i8),
15012                                            N->getOperand(2)),
15013                                DAG.getConstant(1, VT));
15014     return DCI.CombineTo(N, Res1, CarryOut);
15015   }
15016
15017   return SDValue();
15018 }
15019
15020 // fold (add Y, (sete  X, 0)) -> adc  0, Y
15021 //      (add Y, (setne X, 0)) -> sbb -1, Y
15022 //      (sub (sete  X, 0), Y) -> sbb  0, Y
15023 //      (sub (setne X, 0), Y) -> adc -1, Y
15024 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15025   DebugLoc DL = N->getDebugLoc();
15026
15027   // Look through ZExts.
15028   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15029   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15030     return SDValue();
15031
15032   SDValue SetCC = Ext.getOperand(0);
15033   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15034     return SDValue();
15035
15036   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15037   if (CC != X86::COND_E && CC != X86::COND_NE)
15038     return SDValue();
15039
15040   SDValue Cmp = SetCC.getOperand(1);
15041   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15042       !X86::isZeroNode(Cmp.getOperand(1)) ||
15043       !Cmp.getOperand(0).getValueType().isInteger())
15044     return SDValue();
15045
15046   SDValue CmpOp0 = Cmp.getOperand(0);
15047   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15048                                DAG.getConstant(1, CmpOp0.getValueType()));
15049
15050   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15051   if (CC == X86::COND_NE)
15052     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15053                        DL, OtherVal.getValueType(), OtherVal,
15054                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15055   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15056                      DL, OtherVal.getValueType(), OtherVal,
15057                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15058 }
15059
15060 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15061 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15062                                  const X86Subtarget *Subtarget) {
15063   EVT VT = N->getValueType(0);
15064   SDValue Op0 = N->getOperand(0);
15065   SDValue Op1 = N->getOperand(1);
15066
15067   // Try to synthesize horizontal adds from adds of shuffles.
15068   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15069        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15070       isHorizontalBinOp(Op0, Op1, true))
15071     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15072
15073   return OptimizeConditionalInDecrement(N, DAG);
15074 }
15075
15076 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15077                                  const X86Subtarget *Subtarget) {
15078   SDValue Op0 = N->getOperand(0);
15079   SDValue Op1 = N->getOperand(1);
15080
15081   // X86 can't encode an immediate LHS of a sub. See if we can push the
15082   // negation into a preceding instruction.
15083   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15084     // If the RHS of the sub is a XOR with one use and a constant, invert the
15085     // immediate. Then add one to the LHS of the sub so we can turn
15086     // X-Y -> X+~Y+1, saving one register.
15087     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15088         isa<ConstantSDNode>(Op1.getOperand(1))) {
15089       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15090       EVT VT = Op0.getValueType();
15091       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15092                                    Op1.getOperand(0),
15093                                    DAG.getConstant(~XorC, VT));
15094       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15095                          DAG.getConstant(C->getAPIntValue()+1, VT));
15096     }
15097   }
15098
15099   // Try to synthesize horizontal adds from adds of shuffles.
15100   EVT VT = N->getValueType(0);
15101   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15102        (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15103       isHorizontalBinOp(Op0, Op1, true))
15104     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15105
15106   return OptimizeConditionalInDecrement(N, DAG);
15107 }
15108
15109 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15110                                              DAGCombinerInfo &DCI) const {
15111   SelectionDAG &DAG = DCI.DAG;
15112   switch (N->getOpcode()) {
15113   default: break;
15114   case ISD::EXTRACT_VECTOR_ELT:
15115     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15116   case ISD::VSELECT:
15117   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15118   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
15119   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
15120   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
15121   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
15122   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
15123   case ISD::SHL:
15124   case ISD::SRA:
15125   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
15126   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
15127   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
15128   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
15129   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
15130   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
15131   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
15132   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
15133   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
15134   case X86ISD::FXOR:
15135   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
15136   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
15137   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
15138   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
15139   case ISD::ANY_EXTEND:
15140   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, Subtarget);
15141   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
15142   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG, DCI);
15143   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
15144   case X86ISD::SHUFP:       // Handle all target specific shuffles
15145   case X86ISD::PALIGN:
15146   case X86ISD::UNPCKH:
15147   case X86ISD::UNPCKL:
15148   case X86ISD::MOVHLPS:
15149   case X86ISD::MOVLHPS:
15150   case X86ISD::PSHUFD:
15151   case X86ISD::PSHUFHW:
15152   case X86ISD::PSHUFLW:
15153   case X86ISD::MOVSS:
15154   case X86ISD::MOVSD:
15155   case X86ISD::VPERMILP:
15156   case X86ISD::VPERM2X128:
15157   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15158   }
15159
15160   return SDValue();
15161 }
15162
15163 /// isTypeDesirableForOp - Return true if the target has native support for
15164 /// the specified value type and it is 'desirable' to use the type for the
15165 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15166 /// instruction encodings are longer and some i16 instructions are slow.
15167 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15168   if (!isTypeLegal(VT))
15169     return false;
15170   if (VT != MVT::i16)
15171     return true;
15172
15173   switch (Opc) {
15174   default:
15175     return true;
15176   case ISD::LOAD:
15177   case ISD::SIGN_EXTEND:
15178   case ISD::ZERO_EXTEND:
15179   case ISD::ANY_EXTEND:
15180   case ISD::SHL:
15181   case ISD::SRL:
15182   case ISD::SUB:
15183   case ISD::ADD:
15184   case ISD::MUL:
15185   case ISD::AND:
15186   case ISD::OR:
15187   case ISD::XOR:
15188     return false;
15189   }
15190 }
15191
15192 /// IsDesirableToPromoteOp - This method query the target whether it is
15193 /// beneficial for dag combiner to promote the specified node. If true, it
15194 /// should return the desired promotion type by reference.
15195 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15196   EVT VT = Op.getValueType();
15197   if (VT != MVT::i16)
15198     return false;
15199
15200   bool Promote = false;
15201   bool Commute = false;
15202   switch (Op.getOpcode()) {
15203   default: break;
15204   case ISD::LOAD: {
15205     LoadSDNode *LD = cast<LoadSDNode>(Op);
15206     // If the non-extending load has a single use and it's not live out, then it
15207     // might be folded.
15208     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15209                                                      Op.hasOneUse()*/) {
15210       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15211              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15212         // The only case where we'd want to promote LOAD (rather then it being
15213         // promoted as an operand is when it's only use is liveout.
15214         if (UI->getOpcode() != ISD::CopyToReg)
15215           return false;
15216       }
15217     }
15218     Promote = true;
15219     break;
15220   }
15221   case ISD::SIGN_EXTEND:
15222   case ISD::ZERO_EXTEND:
15223   case ISD::ANY_EXTEND:
15224     Promote = true;
15225     break;
15226   case ISD::SHL:
15227   case ISD::SRL: {
15228     SDValue N0 = Op.getOperand(0);
15229     // Look out for (store (shl (load), x)).
15230     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15231       return false;
15232     Promote = true;
15233     break;
15234   }
15235   case ISD::ADD:
15236   case ISD::MUL:
15237   case ISD::AND:
15238   case ISD::OR:
15239   case ISD::XOR:
15240     Commute = true;
15241     // fallthrough
15242   case ISD::SUB: {
15243     SDValue N0 = Op.getOperand(0);
15244     SDValue N1 = Op.getOperand(1);
15245     if (!Commute && MayFoldLoad(N1))
15246       return false;
15247     // Avoid disabling potential load folding opportunities.
15248     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15249       return false;
15250     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15251       return false;
15252     Promote = true;
15253   }
15254   }
15255
15256   PVT = MVT::i32;
15257   return Promote;
15258 }
15259
15260 //===----------------------------------------------------------------------===//
15261 //                           X86 Inline Assembly Support
15262 //===----------------------------------------------------------------------===//
15263
15264 namespace {
15265   // Helper to match a string separated by whitespace.
15266   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15267     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15268
15269     for (unsigned i = 0, e = args.size(); i != e; ++i) {
15270       StringRef piece(*args[i]);
15271       if (!s.startswith(piece)) // Check if the piece matches.
15272         return false;
15273
15274       s = s.substr(piece.size());
15275       StringRef::size_type pos = s.find_first_not_of(" \t");
15276       if (pos == 0) // We matched a prefix.
15277         return false;
15278
15279       s = s.substr(pos);
15280     }
15281
15282     return s.empty();
15283   }
15284   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15285 }
15286
15287 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15288   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15289
15290   std::string AsmStr = IA->getAsmString();
15291
15292   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15293   if (!Ty || Ty->getBitWidth() % 16 != 0)
15294     return false;
15295
15296   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15297   SmallVector<StringRef, 4> AsmPieces;
15298   SplitString(AsmStr, AsmPieces, ";\n");
15299
15300   switch (AsmPieces.size()) {
15301   default: return false;
15302   case 1:
15303     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15304     // we will turn this bswap into something that will be lowered to logical
15305     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
15306     // lower so don't worry about this.
15307     // bswap $0
15308     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15309         matchAsm(AsmPieces[0], "bswapl", "$0") ||
15310         matchAsm(AsmPieces[0], "bswapq", "$0") ||
15311         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15312         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15313         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15314       // No need to check constraints, nothing other than the equivalent of
15315       // "=r,0" would be valid here.
15316       return IntrinsicLowering::LowerToByteSwap(CI);
15317     }
15318
15319     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15320     if (CI->getType()->isIntegerTy(16) &&
15321         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15322         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15323          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15324       AsmPieces.clear();
15325       const std::string &ConstraintsStr = IA->getConstraintString();
15326       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15327       std::sort(AsmPieces.begin(), AsmPieces.end());
15328       if (AsmPieces.size() == 4 &&
15329           AsmPieces[0] == "~{cc}" &&
15330           AsmPieces[1] == "~{dirflag}" &&
15331           AsmPieces[2] == "~{flags}" &&
15332           AsmPieces[3] == "~{fpsr}")
15333       return IntrinsicLowering::LowerToByteSwap(CI);
15334     }
15335     break;
15336   case 3:
15337     if (CI->getType()->isIntegerTy(32) &&
15338         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15339         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15340         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15341         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15342       AsmPieces.clear();
15343       const std::string &ConstraintsStr = IA->getConstraintString();
15344       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15345       std::sort(AsmPieces.begin(), AsmPieces.end());
15346       if (AsmPieces.size() == 4 &&
15347           AsmPieces[0] == "~{cc}" &&
15348           AsmPieces[1] == "~{dirflag}" &&
15349           AsmPieces[2] == "~{flags}" &&
15350           AsmPieces[3] == "~{fpsr}")
15351         return IntrinsicLowering::LowerToByteSwap(CI);
15352     }
15353
15354     if (CI->getType()->isIntegerTy(64)) {
15355       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15356       if (Constraints.size() >= 2 &&
15357           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15358           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15359         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15360         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15361             matchAsm(AsmPieces[1], "bswap", "%edx") &&
15362             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15363           return IntrinsicLowering::LowerToByteSwap(CI);
15364       }
15365     }
15366     break;
15367   }
15368   return false;
15369 }
15370
15371
15372
15373 /// getConstraintType - Given a constraint letter, return the type of
15374 /// constraint it is for this target.
15375 X86TargetLowering::ConstraintType
15376 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15377   if (Constraint.size() == 1) {
15378     switch (Constraint[0]) {
15379     case 'R':
15380     case 'q':
15381     case 'Q':
15382     case 'f':
15383     case 't':
15384     case 'u':
15385     case 'y':
15386     case 'x':
15387     case 'Y':
15388     case 'l':
15389       return C_RegisterClass;
15390     case 'a':
15391     case 'b':
15392     case 'c':
15393     case 'd':
15394     case 'S':
15395     case 'D':
15396     case 'A':
15397       return C_Register;
15398     case 'I':
15399     case 'J':
15400     case 'K':
15401     case 'L':
15402     case 'M':
15403     case 'N':
15404     case 'G':
15405     case 'C':
15406     case 'e':
15407     case 'Z':
15408       return C_Other;
15409     default:
15410       break;
15411     }
15412   }
15413   return TargetLowering::getConstraintType(Constraint);
15414 }
15415
15416 /// Examine constraint type and operand type and determine a weight value.
15417 /// This object must already have been set up with the operand type
15418 /// and the current alternative constraint selected.
15419 TargetLowering::ConstraintWeight
15420   X86TargetLowering::getSingleConstraintMatchWeight(
15421     AsmOperandInfo &info, const char *constraint) const {
15422   ConstraintWeight weight = CW_Invalid;
15423   Value *CallOperandVal = info.CallOperandVal;
15424     // If we don't have a value, we can't do a match,
15425     // but allow it at the lowest weight.
15426   if (CallOperandVal == NULL)
15427     return CW_Default;
15428   Type *type = CallOperandVal->getType();
15429   // Look at the constraint type.
15430   switch (*constraint) {
15431   default:
15432     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15433   case 'R':
15434   case 'q':
15435   case 'Q':
15436   case 'a':
15437   case 'b':
15438   case 'c':
15439   case 'd':
15440   case 'S':
15441   case 'D':
15442   case 'A':
15443     if (CallOperandVal->getType()->isIntegerTy())
15444       weight = CW_SpecificReg;
15445     break;
15446   case 'f':
15447   case 't':
15448   case 'u':
15449       if (type->isFloatingPointTy())
15450         weight = CW_SpecificReg;
15451       break;
15452   case 'y':
15453       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15454         weight = CW_SpecificReg;
15455       break;
15456   case 'x':
15457   case 'Y':
15458     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15459         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15460       weight = CW_Register;
15461     break;
15462   case 'I':
15463     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15464       if (C->getZExtValue() <= 31)
15465         weight = CW_Constant;
15466     }
15467     break;
15468   case 'J':
15469     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15470       if (C->getZExtValue() <= 63)
15471         weight = CW_Constant;
15472     }
15473     break;
15474   case 'K':
15475     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15476       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15477         weight = CW_Constant;
15478     }
15479     break;
15480   case 'L':
15481     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15482       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15483         weight = CW_Constant;
15484     }
15485     break;
15486   case 'M':
15487     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15488       if (C->getZExtValue() <= 3)
15489         weight = CW_Constant;
15490     }
15491     break;
15492   case 'N':
15493     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15494       if (C->getZExtValue() <= 0xff)
15495         weight = CW_Constant;
15496     }
15497     break;
15498   case 'G':
15499   case 'C':
15500     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15501       weight = CW_Constant;
15502     }
15503     break;
15504   case 'e':
15505     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15506       if ((C->getSExtValue() >= -0x80000000LL) &&
15507           (C->getSExtValue() <= 0x7fffffffLL))
15508         weight = CW_Constant;
15509     }
15510     break;
15511   case 'Z':
15512     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15513       if (C->getZExtValue() <= 0xffffffff)
15514         weight = CW_Constant;
15515     }
15516     break;
15517   }
15518   return weight;
15519 }
15520
15521 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15522 /// with another that has more specific requirements based on the type of the
15523 /// corresponding operand.
15524 const char *X86TargetLowering::
15525 LowerXConstraint(EVT ConstraintVT) const {
15526   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15527   // 'f' like normal targets.
15528   if (ConstraintVT.isFloatingPoint()) {
15529     if (Subtarget->hasSSE2())
15530       return "Y";
15531     if (Subtarget->hasSSE1())
15532       return "x";
15533   }
15534
15535   return TargetLowering::LowerXConstraint(ConstraintVT);
15536 }
15537
15538 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15539 /// vector.  If it is invalid, don't add anything to Ops.
15540 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15541                                                      std::string &Constraint,
15542                                                      std::vector<SDValue>&Ops,
15543                                                      SelectionDAG &DAG) const {
15544   SDValue Result(0, 0);
15545
15546   // Only support length 1 constraints for now.
15547   if (Constraint.length() > 1) return;
15548
15549   char ConstraintLetter = Constraint[0];
15550   switch (ConstraintLetter) {
15551   default: break;
15552   case 'I':
15553     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15554       if (C->getZExtValue() <= 31) {
15555         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15556         break;
15557       }
15558     }
15559     return;
15560   case 'J':
15561     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15562       if (C->getZExtValue() <= 63) {
15563         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15564         break;
15565       }
15566     }
15567     return;
15568   case 'K':
15569     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15570       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15571         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15572         break;
15573       }
15574     }
15575     return;
15576   case 'N':
15577     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15578       if (C->getZExtValue() <= 255) {
15579         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15580         break;
15581       }
15582     }
15583     return;
15584   case 'e': {
15585     // 32-bit signed value
15586     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15587       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15588                                            C->getSExtValue())) {
15589         // Widen to 64 bits here to get it sign extended.
15590         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15591         break;
15592       }
15593     // FIXME gcc accepts some relocatable values here too, but only in certain
15594     // memory models; it's complicated.
15595     }
15596     return;
15597   }
15598   case 'Z': {
15599     // 32-bit unsigned value
15600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15601       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15602                                            C->getZExtValue())) {
15603         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15604         break;
15605       }
15606     }
15607     // FIXME gcc accepts some relocatable values here too, but only in certain
15608     // memory models; it's complicated.
15609     return;
15610   }
15611   case 'i': {
15612     // Literal immediates are always ok.
15613     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15614       // Widen to 64 bits here to get it sign extended.
15615       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15616       break;
15617     }
15618
15619     // In any sort of PIC mode addresses need to be computed at runtime by
15620     // adding in a register or some sort of table lookup.  These can't
15621     // be used as immediates.
15622     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15623       return;
15624
15625     // If we are in non-pic codegen mode, we allow the address of a global (with
15626     // an optional displacement) to be used with 'i'.
15627     GlobalAddressSDNode *GA = 0;
15628     int64_t Offset = 0;
15629
15630     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15631     while (1) {
15632       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15633         Offset += GA->getOffset();
15634         break;
15635       } else if (Op.getOpcode() == ISD::ADD) {
15636         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15637           Offset += C->getZExtValue();
15638           Op = Op.getOperand(0);
15639           continue;
15640         }
15641       } else if (Op.getOpcode() == ISD::SUB) {
15642         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15643           Offset += -C->getZExtValue();
15644           Op = Op.getOperand(0);
15645           continue;
15646         }
15647       }
15648
15649       // Otherwise, this isn't something we can handle, reject it.
15650       return;
15651     }
15652
15653     const GlobalValue *GV = GA->getGlobal();
15654     // If we require an extra load to get this address, as in PIC mode, we
15655     // can't accept it.
15656     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15657                                                         getTargetMachine())))
15658       return;
15659
15660     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15661                                         GA->getValueType(0), Offset);
15662     break;
15663   }
15664   }
15665
15666   if (Result.getNode()) {
15667     Ops.push_back(Result);
15668     return;
15669   }
15670   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15671 }
15672
15673 std::pair<unsigned, const TargetRegisterClass*>
15674 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15675                                                 EVT VT) const {
15676   // First, see if this is a constraint that directly corresponds to an LLVM
15677   // register class.
15678   if (Constraint.size() == 1) {
15679     // GCC Constraint Letters
15680     switch (Constraint[0]) {
15681     default: break;
15682       // TODO: Slight differences here in allocation order and leaving
15683       // RIP in the class. Do they matter any more here than they do
15684       // in the normal allocation?
15685     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15686       if (Subtarget->is64Bit()) {
15687         if (VT == MVT::i32 || VT == MVT::f32)
15688           return std::make_pair(0U, &X86::GR32RegClass);
15689         if (VT == MVT::i16)
15690           return std::make_pair(0U, &X86::GR16RegClass);
15691         if (VT == MVT::i8 || VT == MVT::i1)
15692           return std::make_pair(0U, &X86::GR8RegClass);
15693         if (VT == MVT::i64 || VT == MVT::f64)
15694           return std::make_pair(0U, &X86::GR64RegClass);
15695         break;
15696       }
15697       // 32-bit fallthrough
15698     case 'Q':   // Q_REGS
15699       if (VT == MVT::i32 || VT == MVT::f32)
15700         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15701       if (VT == MVT::i16)
15702         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15703       if (VT == MVT::i8 || VT == MVT::i1)
15704         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15705       if (VT == MVT::i64)
15706         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15707       break;
15708     case 'r':   // GENERAL_REGS
15709     case 'l':   // INDEX_REGS
15710       if (VT == MVT::i8 || VT == MVT::i1)
15711         return std::make_pair(0U, &X86::GR8RegClass);
15712       if (VT == MVT::i16)
15713         return std::make_pair(0U, &X86::GR16RegClass);
15714       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15715         return std::make_pair(0U, &X86::GR32RegClass);
15716       return std::make_pair(0U, &X86::GR64RegClass);
15717     case 'R':   // LEGACY_REGS
15718       if (VT == MVT::i8 || VT == MVT::i1)
15719         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15720       if (VT == MVT::i16)
15721         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15722       if (VT == MVT::i32 || !Subtarget->is64Bit())
15723         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15724       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15725     case 'f':  // FP Stack registers.
15726       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15727       // value to the correct fpstack register class.
15728       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15729         return std::make_pair(0U, &X86::RFP32RegClass);
15730       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15731         return std::make_pair(0U, &X86::RFP64RegClass);
15732       return std::make_pair(0U, &X86::RFP80RegClass);
15733     case 'y':   // MMX_REGS if MMX allowed.
15734       if (!Subtarget->hasMMX()) break;
15735       return std::make_pair(0U, &X86::VR64RegClass);
15736     case 'Y':   // SSE_REGS if SSE2 allowed
15737       if (!Subtarget->hasSSE2()) break;
15738       // FALL THROUGH.
15739     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15740       if (!Subtarget->hasSSE1()) break;
15741
15742       switch (VT.getSimpleVT().SimpleTy) {
15743       default: break;
15744       // Scalar SSE types.
15745       case MVT::f32:
15746       case MVT::i32:
15747         return std::make_pair(0U, &X86::FR32RegClass);
15748       case MVT::f64:
15749       case MVT::i64:
15750         return std::make_pair(0U, &X86::FR64RegClass);
15751       // Vector types.
15752       case MVT::v16i8:
15753       case MVT::v8i16:
15754       case MVT::v4i32:
15755       case MVT::v2i64:
15756       case MVT::v4f32:
15757       case MVT::v2f64:
15758         return std::make_pair(0U, &X86::VR128RegClass);
15759       // AVX types.
15760       case MVT::v32i8:
15761       case MVT::v16i16:
15762       case MVT::v8i32:
15763       case MVT::v4i64:
15764       case MVT::v8f32:
15765       case MVT::v4f64:
15766         return std::make_pair(0U, &X86::VR256RegClass);
15767       }
15768       break;
15769     }
15770   }
15771
15772   // Use the default implementation in TargetLowering to convert the register
15773   // constraint into a member of a register class.
15774   std::pair<unsigned, const TargetRegisterClass*> Res;
15775   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15776
15777   // Not found as a standard register?
15778   if (Res.second == 0) {
15779     // Map st(0) -> st(7) -> ST0
15780     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15781         tolower(Constraint[1]) == 's' &&
15782         tolower(Constraint[2]) == 't' &&
15783         Constraint[3] == '(' &&
15784         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15785         Constraint[5] == ')' &&
15786         Constraint[6] == '}') {
15787
15788       Res.first = X86::ST0+Constraint[4]-'0';
15789       Res.second = &X86::RFP80RegClass;
15790       return Res;
15791     }
15792
15793     // GCC allows "st(0)" to be called just plain "st".
15794     if (StringRef("{st}").equals_lower(Constraint)) {
15795       Res.first = X86::ST0;
15796       Res.second = &X86::RFP80RegClass;
15797       return Res;
15798     }
15799
15800     // flags -> EFLAGS
15801     if (StringRef("{flags}").equals_lower(Constraint)) {
15802       Res.first = X86::EFLAGS;
15803       Res.second = &X86::CCRRegClass;
15804       return Res;
15805     }
15806
15807     // 'A' means EAX + EDX.
15808     if (Constraint == "A") {
15809       Res.first = X86::EAX;
15810       Res.second = &X86::GR32_ADRegClass;
15811       return Res;
15812     }
15813     return Res;
15814   }
15815
15816   // Otherwise, check to see if this is a register class of the wrong value
15817   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15818   // turn into {ax},{dx}.
15819   if (Res.second->hasType(VT))
15820     return Res;   // Correct type already, nothing to do.
15821
15822   // All of the single-register GCC register classes map their values onto
15823   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15824   // really want an 8-bit or 32-bit register, map to the appropriate register
15825   // class and return the appropriate register.
15826   if (Res.second == &X86::GR16RegClass) {
15827     if (VT == MVT::i8) {
15828       unsigned DestReg = 0;
15829       switch (Res.first) {
15830       default: break;
15831       case X86::AX: DestReg = X86::AL; break;
15832       case X86::DX: DestReg = X86::DL; break;
15833       case X86::CX: DestReg = X86::CL; break;
15834       case X86::BX: DestReg = X86::BL; break;
15835       }
15836       if (DestReg) {
15837         Res.first = DestReg;
15838         Res.second = &X86::GR8RegClass;
15839       }
15840     } else if (VT == MVT::i32) {
15841       unsigned DestReg = 0;
15842       switch (Res.first) {
15843       default: break;
15844       case X86::AX: DestReg = X86::EAX; break;
15845       case X86::DX: DestReg = X86::EDX; break;
15846       case X86::CX: DestReg = X86::ECX; break;
15847       case X86::BX: DestReg = X86::EBX; break;
15848       case X86::SI: DestReg = X86::ESI; break;
15849       case X86::DI: DestReg = X86::EDI; break;
15850       case X86::BP: DestReg = X86::EBP; break;
15851       case X86::SP: DestReg = X86::ESP; break;
15852       }
15853       if (DestReg) {
15854         Res.first = DestReg;
15855         Res.second = &X86::GR32RegClass;
15856       }
15857     } else if (VT == MVT::i64) {
15858       unsigned DestReg = 0;
15859       switch (Res.first) {
15860       default: break;
15861       case X86::AX: DestReg = X86::RAX; break;
15862       case X86::DX: DestReg = X86::RDX; break;
15863       case X86::CX: DestReg = X86::RCX; break;
15864       case X86::BX: DestReg = X86::RBX; break;
15865       case X86::SI: DestReg = X86::RSI; break;
15866       case X86::DI: DestReg = X86::RDI; break;
15867       case X86::BP: DestReg = X86::RBP; break;
15868       case X86::SP: DestReg = X86::RSP; break;
15869       }
15870       if (DestReg) {
15871         Res.first = DestReg;
15872         Res.second = &X86::GR64RegClass;
15873       }
15874     }
15875   } else if (Res.second == &X86::FR32RegClass ||
15876              Res.second == &X86::FR64RegClass ||
15877              Res.second == &X86::VR128RegClass) {
15878     // Handle references to XMM physical registers that got mapped into the
15879     // wrong class.  This can happen with constraints like {xmm0} where the
15880     // target independent register mapper will just pick the first match it can
15881     // find, ignoring the required type.
15882     if (VT == MVT::f32)
15883       Res.second = &X86::FR32RegClass;
15884     else if (VT == MVT::f64)
15885       Res.second = &X86::FR64RegClass;
15886     else if (X86::VR128RegClass.hasType(VT))
15887       Res.second = &X86::VR128RegClass;
15888   }
15889
15890   return Res;
15891 }