f85c201d01c2079a383d740caff6ea5bddf0d4ca
[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 "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.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/CodeGen/PseudoSourceValue.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/VectorExtras.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/Dwarf.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 using namespace llvm;
56 using namespace dwarf;
57
58 STATISTIC(NumTailCalls, "Number of tail calls");
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static SDValue Insert128BitVector(SDValue Result,
65                                   SDValue Vec,
66                                   SDValue Idx,
67                                   SelectionDAG &DAG,
68                                   DebugLoc dl);
69
70 static SDValue Extract128BitVector(SDValue Vec,
71                                    SDValue Idx,
72                                    SelectionDAG &DAG,
73                                    DebugLoc dl);
74
75 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
76 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
77 /// simple subregister reference.  Idx is an index in the 128 bits we
78 /// want.  It need not be aligned to a 128-bit bounday.  That makes
79 /// lowering EXTRACT_VECTOR_ELT operations easier.
80 static SDValue Extract128BitVector(SDValue Vec,
81                                    SDValue Idx,
82                                    SelectionDAG &DAG,
83                                    DebugLoc dl) {
84   EVT VT = Vec.getValueType();
85   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
86   EVT ElVT = VT.getVectorElementType();
87   int Factor = VT.getSizeInBits()/128;
88   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
89                                   VT.getVectorNumElements()/Factor);
90
91   // Extract from UNDEF is UNDEF.
92   if (Vec.getOpcode() == ISD::UNDEF)
93     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
94
95   if (isa<ConstantSDNode>(Idx)) {
96     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
97
98     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
99     // we can match to VEXTRACTF128.
100     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
101
102     // This is the index of the first element of the 128-bit chunk
103     // we want.
104     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
105                                  * ElemsPerChunk);
106
107     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
108     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                  VecIdx);
110
111     return Result;
112   }
113
114   return SDValue();
115 }
116
117 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
118 /// sets things up to match to an AVX VINSERTF128 instruction or a
119 /// simple superregister reference.  Idx is an index in the 128 bits
120 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
121 /// lowering INSERT_VECTOR_ELT operations easier.
122 static SDValue Insert128BitVector(SDValue Result,
123                                   SDValue Vec,
124                                   SDValue Idx,
125                                   SelectionDAG &DAG,
126                                   DebugLoc dl) {
127   if (isa<ConstantSDNode>(Idx)) {
128     EVT VT = Vec.getValueType();
129     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
130
131     EVT ElVT = VT.getVectorElementType();
132     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
133     EVT ResultVT = Result.getValueType();
134
135     // Insert the relevant 128 bits.
136     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
137
138     // This is the index of the first element of the 128-bit chunk
139     // we want.
140     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
141                                  * ElemsPerChunk);
142
143     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
144     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
145                          VecIdx);
146     return Result;
147   }
148
149   return SDValue();
150 }
151
152 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
153   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
154   bool is64Bit = Subtarget->is64Bit();
155
156   if (Subtarget->isTargetEnvMacho()) {
157     if (is64Bit)
158       return new X8664_MachoTargetObjectFile();
159     return new TargetLoweringObjectFileMachO();
160   }
161
162   if (Subtarget->isTargetELF())
163     return new TargetLoweringObjectFileELF();
164   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
165     return new TargetLoweringObjectFileCOFF();
166   llvm_unreachable("unknown subtarget type");
167 }
168
169 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
170   : TargetLowering(TM, createTLOF(TM)) {
171   Subtarget = &TM.getSubtarget<X86Subtarget>();
172   X86ScalarSSEf64 = Subtarget->hasXMMInt();
173   X86ScalarSSEf32 = Subtarget->hasXMM();
174   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
175
176   RegInfo = TM.getRegisterInfo();
177   TD = getTargetData();
178
179   // Set up the TargetLowering object.
180   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
181
182   // X86 is weird, it always uses i8 for shift amounts and setcc results.
183   setBooleanContents(ZeroOrOneBooleanContent);
184   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
185   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
186
187   // For 64-bit since we have so many registers use the ILP scheduler, for
188   // 32-bit code use the register pressure specific scheduling.
189   if (Subtarget->is64Bit())
190     setSchedulingPreference(Sched::ILP);
191   else
192     setSchedulingPreference(Sched::RegPressure);
193   setStackPointerRegisterToSaveRestore(X86StackPtr);
194
195   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
196     // Setup Windows compiler runtime calls.
197     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
198     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
199     setLibcallName(RTLIB::SREM_I64, "_allrem");
200     setLibcallName(RTLIB::UREM_I64, "_aullrem");
201     setLibcallName(RTLIB::MUL_I64, "_allmul");
202     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
203     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
204     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
210     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
211   }
212
213   if (Subtarget->isTargetDarwin()) {
214     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
215     setUseUnderscoreSetJmp(false);
216     setUseUnderscoreLongJmp(false);
217   } else if (Subtarget->isTargetMingw()) {
218     // MS runtime is weird: it exports _setjmp, but longjmp!
219     setUseUnderscoreSetJmp(true);
220     setUseUnderscoreLongJmp(false);
221   } else {
222     setUseUnderscoreSetJmp(true);
223     setUseUnderscoreLongJmp(true);
224   }
225
226   // Set up the register classes.
227   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
228   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
229   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
230   if (Subtarget->is64Bit())
231     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
232
233   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234
235   // We don't accept any truncstore of integer registers.
236   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
238   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
239   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
240   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
241   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
242
243   // SETOEQ and SETUNE require checking two conditions.
244   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
246   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
249   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250
251   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252   // operation.
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
255   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
256
257   if (Subtarget->is64Bit()) {
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
259     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
260   } else if (!UseSoftFloat) {
261     // We have an algorithm for SSE2->double, and we turn this into a
262     // 64-bit FILD followed by conditional FADD for other targets.
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264     // We have an algorithm for SSE2, and we turn this into a 64-bit
265     // FILD for other targets.
266     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
267   }
268
269   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270   // this operation.
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
272   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
273
274   if (!UseSoftFloat) {
275     // SSE has no i16 to fp conversion, only i32
276     if (X86ScalarSSEf32) {
277       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
278       // f32 and f64 cases are Legal, f80 case is not
279       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
280     } else {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
282       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
283     }
284   } else {
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
286     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
287   }
288
289   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
290   // are Legal, f80 is custom lowered.
291   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
292   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
293
294   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295   // this operation.
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
297   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
298
299   if (X86ScalarSSEf32) {
300     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
301     // f32 and f64 cases are Legal, f80 case is not
302     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
303   } else {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
305     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
306   }
307
308   // Handle FP_TO_UINT by promoting the destination to a larger signed
309   // conversion.
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
312   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
313
314   if (Subtarget->is64Bit()) {
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
316     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
317   } else if (!UseSoftFloat) {
318     // Since AVX is a superset of SSE3, only check for SSE here.
319     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
320       // Expand FP_TO_UINT into a select.
321       // FIXME: We would like to use a Custom expander here eventually to do
322       // the optimal thing for SSE vs. the default expansion in the legalizer.
323       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
324     else
325       // With SSE3 we can use fisttpll to convert to a signed i64; without
326       // SSE, we're stuck with a fistpll.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
328   }
329
330   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
331   if (!X86ScalarSSEf64) {
332     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
333     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
334     if (Subtarget->is64Bit()) {
335       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
336       // Without SSE, i64->f64 goes through memory.
337       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
338     }
339   }
340
341   // Scalar integer divide and remainder are lowered to use operations that
342   // produce two results, to match the available instructions. This exposes
343   // the two-result form to trivial CSE, which is able to combine x/y and x%y
344   // into a single instruction.
345   //
346   // Scalar integer multiply-high is also lowered to use two-result
347   // operations, to match the available instructions. However, plain multiply
348   // (low) operations are left as Legal, as there are single-result
349   // instructions for this in x86. Using the two-result multiply instructions
350   // when both high and low results are needed must be arranged by dagcombine.
351   for (unsigned i = 0, e = 4; i != e; ++i) {
352     MVT VT = IntVTs[i];
353     setOperationAction(ISD::MULHS, VT, Expand);
354     setOperationAction(ISD::MULHU, VT, Expand);
355     setOperationAction(ISD::SDIV, VT, Expand);
356     setOperationAction(ISD::UDIV, VT, Expand);
357     setOperationAction(ISD::SREM, VT, Expand);
358     setOperationAction(ISD::UREM, VT, Expand);
359
360     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
361     setOperationAction(ISD::ADDC, VT, Custom);
362     setOperationAction(ISD::ADDE, VT, Custom);
363     setOperationAction(ISD::SUBC, VT, Custom);
364     setOperationAction(ISD::SUBE, VT, Custom);
365   }
366
367   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
368   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
369   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
370   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
371   if (Subtarget->is64Bit())
372     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
375   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
376   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
379   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
380   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
381
382   if (Subtarget->hasBMI()) {
383     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
384   } else {
385     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
387     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
388     if (Subtarget->is64Bit())
389       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
390   }
391
392   if (Subtarget->hasLZCNT()) {
393     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
394   } else {
395     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
397     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
398     if (Subtarget->is64Bit())
399       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
400   }
401
402   if (Subtarget->hasPOPCNT()) {
403     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
404   } else {
405     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
407     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
408     if (Subtarget->is64Bit())
409       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
410   }
411
412   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
413   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
414
415   // These should be promoted to a larger select which is supported.
416   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
417   // X86 wants to expand cmov itself.
418   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
423   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
429   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
430   if (Subtarget->is64Bit()) {
431     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
432     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
433   }
434   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
435
436   // Darwin ABI issue.
437   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
438   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
440   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
441   if (Subtarget->is64Bit())
442     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
443   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
444   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
445   if (Subtarget->is64Bit()) {
446     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
447     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
448     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
449     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
450     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
451   }
452   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
453   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
455   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
456   if (Subtarget->is64Bit()) {
457     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
459     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
460   }
461
462   if (Subtarget->hasXMM())
463     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
464
465   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
466   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
467
468   // On X86 and X86-64, atomic operations are lowered to locked instructions.
469   // Locked instructions, in turn, have implicit fence semantics (all memory
470   // operations are flushed before issuing the locked instruction, and they
471   // are not buffered), so we can fold away the common pattern of
472   // fence-atomic-fence.
473   setShouldFoldAtomicFences(true);
474
475   // Expand certain atomics
476   for (unsigned i = 0, e = 4; i != e; ++i) {
477     MVT VT = IntVTs[i];
478     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
479     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
480     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
481   }
482
483   if (!Subtarget->is64Bit()) {
484     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
491     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
492   }
493
494   if (Subtarget->hasCmpxchg16b()) {
495     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
496   }
497
498   // FIXME - use subtarget debug flags
499   if (!Subtarget->isTargetDarwin() &&
500       !Subtarget->isTargetELF() &&
501       !Subtarget->isTargetCygMing()) {
502     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
506   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
507   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
508   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
509   if (Subtarget->is64Bit()) {
510     setExceptionPointerRegister(X86::RAX);
511     setExceptionSelectorRegister(X86::RDX);
512   } else {
513     setExceptionPointerRegister(X86::EAX);
514     setExceptionSelectorRegister(X86::EDX);
515   }
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
517   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
518
519   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
520   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
521
522   setOperationAction(ISD::TRAP, MVT::Other, Legal);
523
524   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
525   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
526   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
529     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
530   } else {
531     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
532     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
533   }
534
535   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
536   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
537
538   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
539     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
540                        MVT::i64 : MVT::i32, Custom);
541   else if (EnableSegmentedStacks)
542     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
543                        MVT::i64 : MVT::i32, Custom);
544   else
545     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
546                        MVT::i64 : MVT::i32, Expand);
547
548   if (!UseSoftFloat && X86ScalarSSEf64) {
549     // f32 and f64 use SSE.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
552     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
553
554     // Use ANDPD to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f64, Custom);
556     setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558     // Use XORP to simulate FNEG.
559     setOperationAction(ISD::FNEG , MVT::f64, Custom);
560     setOperationAction(ISD::FNEG , MVT::f32, Custom);
561
562     // Use ANDPD and ORPD to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // Lower this to FGETSIGNx86 plus an AND.
567     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
568     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
569
570     // We don't support sin/cos/fmod
571     setOperationAction(ISD::FSIN , MVT::f64, Expand);
572     setOperationAction(ISD::FCOS , MVT::f64, Expand);
573     setOperationAction(ISD::FSIN , MVT::f32, Expand);
574     setOperationAction(ISD::FCOS , MVT::f32, Expand);
575
576     // Expand FP immediates into loads from the stack, except for the special
577     // cases we handle.
578     addLegalFPImmediate(APFloat(+0.0)); // xorpd
579     addLegalFPImmediate(APFloat(+0.0f)); // xorps
580   } else if (!UseSoftFloat && X86ScalarSSEf32) {
581     // Use SSE for f32, x87 for f64.
582     // Set up the FP register classes.
583     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
584     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
585
586     // Use ANDPS to simulate FABS.
587     setOperationAction(ISD::FABS , MVT::f32, Custom);
588
589     // Use XORP to simulate FNEG.
590     setOperationAction(ISD::FNEG , MVT::f32, Custom);
591
592     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
593
594     // Use ANDPS and ORPS to simulate FCOPYSIGN.
595     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
596     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
597
598     // We don't support sin/cos/fmod
599     setOperationAction(ISD::FSIN , MVT::f32, Expand);
600     setOperationAction(ISD::FCOS , MVT::f32, Expand);
601
602     // Special cases we handle for FP constants.
603     addLegalFPImmediate(APFloat(+0.0f)); // xorps
604     addLegalFPImmediate(APFloat(+0.0)); // FLD0
605     addLegalFPImmediate(APFloat(+1.0)); // FLD1
606     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
607     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
608
609     if (!UnsafeFPMath) {
610       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
611       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
612     }
613   } else if (!UseSoftFloat) {
614     // f32 and f64 in x87.
615     // Set up the FP register classes.
616     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
617     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
618
619     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
620     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
623
624     if (!UnsafeFPMath) {
625       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
626       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
627     }
628     addLegalFPImmediate(APFloat(+0.0)); // FLD0
629     addLegalFPImmediate(APFloat(+1.0)); // FLD1
630     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
631     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
632     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
633     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
634     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
635     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
636   }
637
638   // We don't support FMA.
639   setOperationAction(ISD::FMA, MVT::f64, Expand);
640   setOperationAction(ISD::FMA, MVT::f32, Expand);
641
642   // Long double always uses X87.
643   if (!UseSoftFloat) {
644     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
645     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
646     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
647     {
648       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
649       addLegalFPImmediate(TmpFlt);  // FLD0
650       TmpFlt.changeSign();
651       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
652
653       bool ignored;
654       APFloat TmpFlt2(+1.0);
655       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
656                       &ignored);
657       addLegalFPImmediate(TmpFlt2);  // FLD1
658       TmpFlt2.changeSign();
659       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
660     }
661
662     if (!UnsafeFPMath) {
663       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
664       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
665     }
666
667     setOperationAction(ISD::FMA, MVT::f80, Expand);
668   }
669
670   // Always use a library call for pow.
671   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
673   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
674
675   setOperationAction(ISD::FLOG, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
677   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP, MVT::f80, Expand);
679   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
680
681   // First set operation action for all vector types to either promote
682   // (for widening) or expand (for scalarization). Then we will selectively
683   // turn on ones that can be effectively codegen'd.
684   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
685        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
686     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
700     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
701     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
702     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
704     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
735     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
736     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
740     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
741     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
742          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
743       setTruncStoreAction((MVT::SimpleValueType)VT,
744                           (MVT::SimpleValueType)InnerVT, Expand);
745     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
747     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
748   }
749
750   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
751   // with -msoft-float, disable use of MMX as well.
752   if (!UseSoftFloat && Subtarget->hasMMX()) {
753     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
754     // No operations on x86mmx supported, everything uses intrinsics.
755   }
756
757   // MMX-sized vectors (other than x86mmx) are expected to be expanded
758   // into smaller operations.
759   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
760   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
762   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
763   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
764   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
765   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
766   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
767   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
768   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
769   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
770   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
771   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
772   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
773   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
774   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
778   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
779   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
780   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
781   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
783   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
787   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
788
789   if (!UseSoftFloat && Subtarget->hasXMM()) {
790     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
791
792     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
796     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
797     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
798     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
799     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
800     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
801     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
803     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
804   }
805
806   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
807     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
808
809     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
810     // registers cannot be used even for integer operations.
811     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
814     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
815
816     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
817     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
818     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
819     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
820     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
821     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
822     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
823     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
824     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
825     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
826     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
830     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
831     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
848     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
849
850     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
851     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
852       EVT VT = (MVT::SimpleValueType)i;
853       // Do not attempt to custom lower non-power-of-2 vectors
854       if (!isPowerOf2_32(VT.getVectorNumElements()))
855         continue;
856       // Do not attempt to custom lower non-128-bit vectors
857       if (!VT.is128BitVector())
858         continue;
859       setOperationAction(ISD::BUILD_VECTOR,
860                          VT.getSimpleVT().SimpleTy, Custom);
861       setOperationAction(ISD::VECTOR_SHUFFLE,
862                          VT.getSimpleVT().SimpleTy, Custom);
863       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
864                          VT.getSimpleVT().SimpleTy, Custom);
865     }
866
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
868     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
870     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
871     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
873
874     if (Subtarget->is64Bit()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
876       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
877     }
878
879     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
880     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
881       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
882       EVT VT = SVT;
883
884       // Do not attempt to promote non-128-bit vectors
885       if (!VT.is128BitVector())
886         continue;
887
888       setOperationAction(ISD::AND,    SVT, Promote);
889       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
890       setOperationAction(ISD::OR,     SVT, Promote);
891       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
892       setOperationAction(ISD::XOR,    SVT, Promote);
893       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
894       setOperationAction(ISD::LOAD,   SVT, Promote);
895       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
896       setOperationAction(ISD::SELECT, SVT, Promote);
897       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
898     }
899
900     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
901
902     // Custom lower v2i64 and v2f64 selects.
903     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
905     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
906     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
907
908     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
909     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
910   }
911
912   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
913     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
914     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
915     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
916     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
917     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
918     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
919     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
920     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
921     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
922     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
923
924     // FIXME: Do we need to handle scalar-to-vector here?
925     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
926
927     // Can turn SHL into an integer multiply.
928     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
929     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
930
931     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
932     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
933     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
934     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
935     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
936
937     // i8 and i16 vectors are custom , because the source register and source
938     // source memory operand types are not the same width.  f32 vectors are
939     // custom since the immediate controlling the insert encodes additional
940     // information.
941     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
942     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
943     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
944     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
945
946     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
947     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
948     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
949     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
950
951     if (Subtarget->is64Bit()) {
952       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
953       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
954     }
955   }
956
957   if (Subtarget->hasXMMInt()) {
958     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
959     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
960     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
961     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
962
963     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
964     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
965     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
966
967     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
968     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
969   }
970
971   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
972     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
973
974   if (!UseSoftFloat && Subtarget->hasAVX()) {
975     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
976     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
977     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
978     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
979     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
980     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
981
982     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
983     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
984     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
985
986     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
987     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
988     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
989     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
990     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
991     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
992
993     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
994     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
995     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
996     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
997     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
998     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
999
1000     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1001     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1002     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1003
1004     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1005     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1006     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1007     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1008     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1009     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1010
1011     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1012     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1013     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1014     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1015
1016     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1017     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1018     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1019     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1020
1021     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1022     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1023
1024     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1025     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1026     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1027     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1028
1029     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1030     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1031     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1032
1033     setOperationAction(ISD::VSELECT,            MVT::v4f64, Legal);
1034     setOperationAction(ISD::VSELECT,            MVT::v4i64, Legal);
1035     setOperationAction(ISD::VSELECT,            MVT::v8i32, Legal);
1036     setOperationAction(ISD::VSELECT,            MVT::v8f32, Legal);
1037
1038     setOperationAction(ISD::ADD,               MVT::v4i64, Custom);
1039     setOperationAction(ISD::ADD,               MVT::v8i32, Custom);
1040     setOperationAction(ISD::ADD,               MVT::v16i16, Custom);
1041     setOperationAction(ISD::ADD,               MVT::v32i8, Custom);
1042
1043     setOperationAction(ISD::SUB,               MVT::v4i64, Custom);
1044     setOperationAction(ISD::SUB,               MVT::v8i32, Custom);
1045     setOperationAction(ISD::SUB,               MVT::v16i16, Custom);
1046     setOperationAction(ISD::SUB,               MVT::v32i8, Custom);
1047
1048     setOperationAction(ISD::MUL,               MVT::v4i64, Custom);
1049     setOperationAction(ISD::MUL,               MVT::v8i32, Custom);
1050     setOperationAction(ISD::MUL,               MVT::v16i16, Custom);
1051     // Don't lower v32i8 because there is no 128-bit byte mul
1052
1053     // Custom lower several nodes for 256-bit types.
1054     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1055                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1056       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1057       EVT VT = SVT;
1058
1059       // Extract subvector is special because the value type
1060       // (result) is 128-bit but the source is 256-bit wide.
1061       if (VT.is128BitVector())
1062         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1063
1064       // Do not attempt to custom lower other non-256-bit vectors
1065       if (!VT.is256BitVector())
1066         continue;
1067
1068       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1069       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1070       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1071       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1072       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1073       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1074     }
1075
1076     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1077     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1078       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1079       EVT VT = SVT;
1080
1081       // Do not attempt to promote non-256-bit vectors
1082       if (!VT.is256BitVector())
1083         continue;
1084
1085       setOperationAction(ISD::AND,    SVT, Promote);
1086       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1087       setOperationAction(ISD::OR,     SVT, Promote);
1088       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1089       setOperationAction(ISD::XOR,    SVT, Promote);
1090       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1091       setOperationAction(ISD::LOAD,   SVT, Promote);
1092       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1093       setOperationAction(ISD::SELECT, SVT, Promote);
1094       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1095     }
1096   }
1097
1098   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1099   // of this type with custom code.
1100   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1101          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1102     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1103   }
1104
1105   // We want to custom lower some of our intrinsics.
1106   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1107
1108
1109   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1110   // handle type legalization for these operations here.
1111   //
1112   // FIXME: We really should do custom legalization for addition and
1113   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1114   // than generic legalization for 64-bit multiplication-with-overflow, though.
1115   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1116     // Add/Sub/Mul with overflow operations are custom lowered.
1117     MVT VT = IntVTs[i];
1118     setOperationAction(ISD::SADDO, VT, Custom);
1119     setOperationAction(ISD::UADDO, VT, Custom);
1120     setOperationAction(ISD::SSUBO, VT, Custom);
1121     setOperationAction(ISD::USUBO, VT, Custom);
1122     setOperationAction(ISD::SMULO, VT, Custom);
1123     setOperationAction(ISD::UMULO, VT, Custom);
1124   }
1125
1126   // There are no 8-bit 3-address imul/mul instructions
1127   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1128   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1129
1130   if (!Subtarget->is64Bit()) {
1131     // These libcalls are not available in 32-bit.
1132     setLibcallName(RTLIB::SHL_I128, 0);
1133     setLibcallName(RTLIB::SRL_I128, 0);
1134     setLibcallName(RTLIB::SRA_I128, 0);
1135   }
1136
1137   // We have target-specific dag combine patterns for the following nodes:
1138   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1139   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1140   setTargetDAGCombine(ISD::BUILD_VECTOR);
1141   setTargetDAGCombine(ISD::VSELECT);
1142   setTargetDAGCombine(ISD::SELECT);
1143   setTargetDAGCombine(ISD::SHL);
1144   setTargetDAGCombine(ISD::SRA);
1145   setTargetDAGCombine(ISD::SRL);
1146   setTargetDAGCombine(ISD::OR);
1147   setTargetDAGCombine(ISD::AND);
1148   setTargetDAGCombine(ISD::ADD);
1149   setTargetDAGCombine(ISD::FADD);
1150   setTargetDAGCombine(ISD::FSUB);
1151   setTargetDAGCombine(ISD::SUB);
1152   setTargetDAGCombine(ISD::LOAD);
1153   setTargetDAGCombine(ISD::STORE);
1154   setTargetDAGCombine(ISD::ZERO_EXTEND);
1155   setTargetDAGCombine(ISD::SINT_TO_FP);
1156   if (Subtarget->is64Bit())
1157     setTargetDAGCombine(ISD::MUL);
1158
1159   computeRegisterProperties();
1160
1161   // On Darwin, -Os means optimize for size without hurting performance,
1162   // do not reduce the limit.
1163   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1164   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1165   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1166   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1167   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1168   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1169   setPrefLoopAlignment(16);
1170   benefitFromCodePlacementOpt = true;
1171
1172   setPrefFunctionAlignment(4);
1173 }
1174
1175
1176 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1177   if (!VT.isVector()) return MVT::i8;
1178   return VT.changeVectorElementTypeToInteger();
1179 }
1180
1181
1182 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1183 /// the desired ByVal argument alignment.
1184 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1185   if (MaxAlign == 16)
1186     return;
1187   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1188     if (VTy->getBitWidth() == 128)
1189       MaxAlign = 16;
1190   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1191     unsigned EltAlign = 0;
1192     getMaxByValAlign(ATy->getElementType(), EltAlign);
1193     if (EltAlign > MaxAlign)
1194       MaxAlign = EltAlign;
1195   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1196     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1197       unsigned EltAlign = 0;
1198       getMaxByValAlign(STy->getElementType(i), EltAlign);
1199       if (EltAlign > MaxAlign)
1200         MaxAlign = EltAlign;
1201       if (MaxAlign == 16)
1202         break;
1203     }
1204   }
1205   return;
1206 }
1207
1208 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1209 /// function arguments in the caller parameter area. For X86, aggregates
1210 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1211 /// are at 4-byte boundaries.
1212 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1213   if (Subtarget->is64Bit()) {
1214     // Max of 8 and alignment of type.
1215     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1216     if (TyAlign > 8)
1217       return TyAlign;
1218     return 8;
1219   }
1220
1221   unsigned Align = 4;
1222   if (Subtarget->hasXMM())
1223     getMaxByValAlign(Ty, Align);
1224   return Align;
1225 }
1226
1227 /// getOptimalMemOpType - Returns the target specific optimal type for load
1228 /// and store operations as a result of memset, memcpy, and memmove
1229 /// lowering. If DstAlign is zero that means it's safe to destination
1230 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1231 /// means there isn't a need to check it against alignment requirement,
1232 /// probably because the source does not need to be loaded. If
1233 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1234 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1235 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1236 /// constant so it does not need to be loaded.
1237 /// It returns EVT::Other if the type should be determined using generic
1238 /// target-independent logic.
1239 EVT
1240 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1241                                        unsigned DstAlign, unsigned SrcAlign,
1242                                        bool NonScalarIntSafe,
1243                                        bool MemcpyStrSrc,
1244                                        MachineFunction &MF) const {
1245   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1246   // linux.  This is because the stack realignment code can't handle certain
1247   // cases like PR2962.  This should be removed when PR2962 is fixed.
1248   const Function *F = MF.getFunction();
1249   if (NonScalarIntSafe &&
1250       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1251     if (Size >= 16 &&
1252         (Subtarget->isUnalignedMemAccessFast() ||
1253          ((DstAlign == 0 || DstAlign >= 16) &&
1254           (SrcAlign == 0 || SrcAlign >= 16))) &&
1255         Subtarget->getStackAlignment() >= 16) {
1256       if (Subtarget->hasAVX() &&
1257           Subtarget->getStackAlignment() >= 32)
1258         return MVT::v8f32;
1259       if (Subtarget->hasXMMInt())
1260         return MVT::v4i32;
1261       if (Subtarget->hasXMM())
1262         return MVT::v4f32;
1263     } else if (!MemcpyStrSrc && Size >= 8 &&
1264                !Subtarget->is64Bit() &&
1265                Subtarget->getStackAlignment() >= 8 &&
1266                Subtarget->hasXMMInt()) {
1267       // Do not use f64 to lower memcpy if source is string constant. It's
1268       // better to use i32 to avoid the loads.
1269       return MVT::f64;
1270     }
1271   }
1272   if (Subtarget->is64Bit() && Size >= 8)
1273     return MVT::i64;
1274   return MVT::i32;
1275 }
1276
1277 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1278 /// current function.  The returned value is a member of the
1279 /// MachineJumpTableInfo::JTEntryKind enum.
1280 unsigned X86TargetLowering::getJumpTableEncoding() const {
1281   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1282   // symbol.
1283   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1284       Subtarget->isPICStyleGOT())
1285     return MachineJumpTableInfo::EK_Custom32;
1286
1287   // Otherwise, use the normal jump table encoding heuristics.
1288   return TargetLowering::getJumpTableEncoding();
1289 }
1290
1291 const MCExpr *
1292 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1293                                              const MachineBasicBlock *MBB,
1294                                              unsigned uid,MCContext &Ctx) const{
1295   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1296          Subtarget->isPICStyleGOT());
1297   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1298   // entries.
1299   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1300                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1301 }
1302
1303 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1304 /// jumptable.
1305 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1306                                                     SelectionDAG &DAG) const {
1307   if (!Subtarget->is64Bit())
1308     // This doesn't have DebugLoc associated with it, but is not really the
1309     // same as a Register.
1310     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1311   return Table;
1312 }
1313
1314 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1315 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1316 /// MCExpr.
1317 const MCExpr *X86TargetLowering::
1318 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1319                              MCContext &Ctx) const {
1320   // X86-64 uses RIP relative addressing based on the jump table label.
1321   if (Subtarget->isPICStyleRIPRel())
1322     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1323
1324   // Otherwise, the reference is relative to the PIC base.
1325   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1326 }
1327
1328 // FIXME: Why this routine is here? Move to RegInfo!
1329 std::pair<const TargetRegisterClass*, uint8_t>
1330 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1331   const TargetRegisterClass *RRC = 0;
1332   uint8_t Cost = 1;
1333   switch (VT.getSimpleVT().SimpleTy) {
1334   default:
1335     return TargetLowering::findRepresentativeClass(VT);
1336   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1337     RRC = (Subtarget->is64Bit()
1338            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1339     break;
1340   case MVT::x86mmx:
1341     RRC = X86::VR64RegisterClass;
1342     break;
1343   case MVT::f32: case MVT::f64:
1344   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1345   case MVT::v4f32: case MVT::v2f64:
1346   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1347   case MVT::v4f64:
1348     RRC = X86::VR128RegisterClass;
1349     break;
1350   }
1351   return std::make_pair(RRC, Cost);
1352 }
1353
1354 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1355                                                unsigned &Offset) const {
1356   if (!Subtarget->isTargetLinux())
1357     return false;
1358
1359   if (Subtarget->is64Bit()) {
1360     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1361     Offset = 0x28;
1362     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1363       AddressSpace = 256;
1364     else
1365       AddressSpace = 257;
1366   } else {
1367     // %gs:0x14 on i386
1368     Offset = 0x14;
1369     AddressSpace = 256;
1370   }
1371   return true;
1372 }
1373
1374
1375 //===----------------------------------------------------------------------===//
1376 //               Return Value Calling Convention Implementation
1377 //===----------------------------------------------------------------------===//
1378
1379 #include "X86GenCallingConv.inc"
1380
1381 bool
1382 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1383                                   MachineFunction &MF, bool isVarArg,
1384                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1385                         LLVMContext &Context) const {
1386   SmallVector<CCValAssign, 16> RVLocs;
1387   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1388                  RVLocs, Context);
1389   return CCInfo.CheckReturn(Outs, RetCC_X86);
1390 }
1391
1392 SDValue
1393 X86TargetLowering::LowerReturn(SDValue Chain,
1394                                CallingConv::ID CallConv, bool isVarArg,
1395                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1396                                const SmallVectorImpl<SDValue> &OutVals,
1397                                DebugLoc dl, SelectionDAG &DAG) const {
1398   MachineFunction &MF = DAG.getMachineFunction();
1399   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1400
1401   SmallVector<CCValAssign, 16> RVLocs;
1402   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1403                  RVLocs, *DAG.getContext());
1404   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1405
1406   // Add the regs to the liveout set for the function.
1407   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1408   for (unsigned i = 0; i != RVLocs.size(); ++i)
1409     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1410       MRI.addLiveOut(RVLocs[i].getLocReg());
1411
1412   SDValue Flag;
1413
1414   SmallVector<SDValue, 6> RetOps;
1415   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1416   // Operand #1 = Bytes To Pop
1417   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1418                    MVT::i16));
1419
1420   // Copy the result values into the output registers.
1421   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1422     CCValAssign &VA = RVLocs[i];
1423     assert(VA.isRegLoc() && "Can only return in registers!");
1424     SDValue ValToCopy = OutVals[i];
1425     EVT ValVT = ValToCopy.getValueType();
1426
1427     // If this is x86-64, and we disabled SSE, we can't return FP values,
1428     // or SSE or MMX vectors.
1429     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1430          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1431           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1432       report_fatal_error("SSE register return with SSE disabled");
1433     }
1434     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1435     // llvm-gcc has never done it right and no one has noticed, so this
1436     // should be OK for now.
1437     if (ValVT == MVT::f64 &&
1438         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1439       report_fatal_error("SSE2 register return with SSE2 disabled");
1440
1441     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1442     // the RET instruction and handled by the FP Stackifier.
1443     if (VA.getLocReg() == X86::ST0 ||
1444         VA.getLocReg() == X86::ST1) {
1445       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1446       // change the value to the FP stack register class.
1447       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1448         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1449       RetOps.push_back(ValToCopy);
1450       // Don't emit a copytoreg.
1451       continue;
1452     }
1453
1454     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1455     // which is returned in RAX / RDX.
1456     if (Subtarget->is64Bit()) {
1457       if (ValVT == MVT::x86mmx) {
1458         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1459           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1460           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1461                                   ValToCopy);
1462           // If we don't have SSE2 available, convert to v4f32 so the generated
1463           // register is legal.
1464           if (!Subtarget->hasXMMInt())
1465             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1466         }
1467       }
1468     }
1469
1470     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1471     Flag = Chain.getValue(1);
1472   }
1473
1474   // The x86-64 ABI for returning structs by value requires that we copy
1475   // the sret argument into %rax for the return. We saved the argument into
1476   // a virtual register in the entry block, so now we copy the value out
1477   // and into %rax.
1478   if (Subtarget->is64Bit() &&
1479       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1480     MachineFunction &MF = DAG.getMachineFunction();
1481     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1482     unsigned Reg = FuncInfo->getSRetReturnReg();
1483     assert(Reg &&
1484            "SRetReturnReg should have been set in LowerFormalArguments().");
1485     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1486
1487     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1488     Flag = Chain.getValue(1);
1489
1490     // RAX now acts like a return value.
1491     MRI.addLiveOut(X86::RAX);
1492   }
1493
1494   RetOps[0] = Chain;  // Update chain.
1495
1496   // Add the flag if we have it.
1497   if (Flag.getNode())
1498     RetOps.push_back(Flag);
1499
1500   return DAG.getNode(X86ISD::RET_FLAG, dl,
1501                      MVT::Other, &RetOps[0], RetOps.size());
1502 }
1503
1504 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1505   if (N->getNumValues() != 1)
1506     return false;
1507   if (!N->hasNUsesOfValue(1, 0))
1508     return false;
1509
1510   SDNode *Copy = *N->use_begin();
1511   if (Copy->getOpcode() != ISD::CopyToReg &&
1512       Copy->getOpcode() != ISD::FP_EXTEND)
1513     return false;
1514
1515   bool HasRet = false;
1516   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1517        UI != UE; ++UI) {
1518     if (UI->getOpcode() != X86ISD::RET_FLAG)
1519       return false;
1520     HasRet = true;
1521   }
1522
1523   return HasRet;
1524 }
1525
1526 EVT
1527 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1528                                             ISD::NodeType ExtendKind) const {
1529   MVT ReturnMVT;
1530   // TODO: Is this also valid on 32-bit?
1531   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1532     ReturnMVT = MVT::i8;
1533   else
1534     ReturnMVT = MVT::i32;
1535
1536   EVT MinVT = getRegisterType(Context, ReturnMVT);
1537   return VT.bitsLT(MinVT) ? MinVT : VT;
1538 }
1539
1540 /// LowerCallResult - Lower the result values of a call into the
1541 /// appropriate copies out of appropriate physical registers.
1542 ///
1543 SDValue
1544 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1545                                    CallingConv::ID CallConv, bool isVarArg,
1546                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1547                                    DebugLoc dl, SelectionDAG &DAG,
1548                                    SmallVectorImpl<SDValue> &InVals) const {
1549
1550   // Assign locations to each value returned by this call.
1551   SmallVector<CCValAssign, 16> RVLocs;
1552   bool Is64Bit = Subtarget->is64Bit();
1553   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1554                  getTargetMachine(), RVLocs, *DAG.getContext());
1555   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1556
1557   // Copy all of the result registers out of their specified physreg.
1558   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1559     CCValAssign &VA = RVLocs[i];
1560     EVT CopyVT = VA.getValVT();
1561
1562     // If this is x86-64, and we disabled SSE, we can't return FP values
1563     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1564         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1565       report_fatal_error("SSE register return with SSE disabled");
1566     }
1567
1568     SDValue Val;
1569
1570     // If this is a call to a function that returns an fp value on the floating
1571     // point stack, we must guarantee the the value is popped from the stack, so
1572     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1573     // if the return value is not used. We use the FpPOP_RETVAL instruction
1574     // instead.
1575     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1576       // If we prefer to use the value in xmm registers, copy it out as f80 and
1577       // use a truncate to move it from fp stack reg to xmm reg.
1578       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1579       SDValue Ops[] = { Chain, InFlag };
1580       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1581                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1582       Val = Chain.getValue(0);
1583
1584       // Round the f80 to the right size, which also moves it to the appropriate
1585       // xmm register.
1586       if (CopyVT != VA.getValVT())
1587         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1588                           // This truncation won't change the value.
1589                           DAG.getIntPtrConstant(1));
1590     } else {
1591       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1592                                  CopyVT, InFlag).getValue(1);
1593       Val = Chain.getValue(0);
1594     }
1595     InFlag = Chain.getValue(2);
1596     InVals.push_back(Val);
1597   }
1598
1599   return Chain;
1600 }
1601
1602
1603 //===----------------------------------------------------------------------===//
1604 //                C & StdCall & Fast Calling Convention implementation
1605 //===----------------------------------------------------------------------===//
1606 //  StdCall calling convention seems to be standard for many Windows' API
1607 //  routines and around. It differs from C calling convention just a little:
1608 //  callee should clean up the stack, not caller. Symbols should be also
1609 //  decorated in some fancy way :) It doesn't support any vector arguments.
1610 //  For info on fast calling convention see Fast Calling Convention (tail call)
1611 //  implementation LowerX86_32FastCCCallTo.
1612
1613 /// CallIsStructReturn - Determines whether a call uses struct return
1614 /// semantics.
1615 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1616   if (Outs.empty())
1617     return false;
1618
1619   return Outs[0].Flags.isSRet();
1620 }
1621
1622 /// ArgsAreStructReturn - Determines whether a function uses struct
1623 /// return semantics.
1624 static bool
1625 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1626   if (Ins.empty())
1627     return false;
1628
1629   return Ins[0].Flags.isSRet();
1630 }
1631
1632 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1633 /// by "Src" to address "Dst" with size and alignment information specified by
1634 /// the specific parameter attribute. The copy will be passed as a byval
1635 /// function parameter.
1636 static SDValue
1637 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1638                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1639                           DebugLoc dl) {
1640   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1641
1642   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1643                        /*isVolatile*/false, /*AlwaysInline=*/true,
1644                        MachinePointerInfo(), MachinePointerInfo());
1645 }
1646
1647 /// IsTailCallConvention - Return true if the calling convention is one that
1648 /// supports tail call optimization.
1649 static bool IsTailCallConvention(CallingConv::ID CC) {
1650   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1651 }
1652
1653 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1654   if (!CI->isTailCall())
1655     return false;
1656
1657   CallSite CS(CI);
1658   CallingConv::ID CalleeCC = CS.getCallingConv();
1659   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1660     return false;
1661
1662   return true;
1663 }
1664
1665 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1666 /// a tailcall target by changing its ABI.
1667 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1668   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1669 }
1670
1671 SDValue
1672 X86TargetLowering::LowerMemArgument(SDValue Chain,
1673                                     CallingConv::ID CallConv,
1674                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1675                                     DebugLoc dl, SelectionDAG &DAG,
1676                                     const CCValAssign &VA,
1677                                     MachineFrameInfo *MFI,
1678                                     unsigned i) const {
1679   // Create the nodes corresponding to a load from this parameter slot.
1680   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1681   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1682   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1683   EVT ValVT;
1684
1685   // If value is passed by pointer we have address passed instead of the value
1686   // itself.
1687   if (VA.getLocInfo() == CCValAssign::Indirect)
1688     ValVT = VA.getLocVT();
1689   else
1690     ValVT = VA.getValVT();
1691
1692   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1693   // changed with more analysis.
1694   // In case of tail call optimization mark all arguments mutable. Since they
1695   // could be overwritten by lowering of arguments in case of a tail call.
1696   if (Flags.isByVal()) {
1697     unsigned Bytes = Flags.getByValSize();
1698     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1699     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1700     return DAG.getFrameIndex(FI, getPointerTy());
1701   } else {
1702     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1703                                     VA.getLocMemOffset(), isImmutable);
1704     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1705     return DAG.getLoad(ValVT, dl, Chain, FIN,
1706                        MachinePointerInfo::getFixedStack(FI),
1707                        false, false, 0);
1708   }
1709 }
1710
1711 SDValue
1712 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1713                                         CallingConv::ID CallConv,
1714                                         bool isVarArg,
1715                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1716                                         DebugLoc dl,
1717                                         SelectionDAG &DAG,
1718                                         SmallVectorImpl<SDValue> &InVals)
1719                                           const {
1720   MachineFunction &MF = DAG.getMachineFunction();
1721   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1722
1723   const Function* Fn = MF.getFunction();
1724   if (Fn->hasExternalLinkage() &&
1725       Subtarget->isTargetCygMing() &&
1726       Fn->getName() == "main")
1727     FuncInfo->setForceFramePointer(true);
1728
1729   MachineFrameInfo *MFI = MF.getFrameInfo();
1730   bool Is64Bit = Subtarget->is64Bit();
1731   bool IsWin64 = Subtarget->isTargetWin64();
1732
1733   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1734          "Var args not supported with calling convention fastcc or ghc");
1735
1736   // Assign locations to all of the incoming arguments.
1737   SmallVector<CCValAssign, 16> ArgLocs;
1738   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1739                  ArgLocs, *DAG.getContext());
1740
1741   // Allocate shadow area for Win64
1742   if (IsWin64) {
1743     CCInfo.AllocateStack(32, 8);
1744   }
1745
1746   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1747
1748   unsigned LastVal = ~0U;
1749   SDValue ArgValue;
1750   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1751     CCValAssign &VA = ArgLocs[i];
1752     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1753     // places.
1754     assert(VA.getValNo() != LastVal &&
1755            "Don't support value assigned to multiple locs yet");
1756     LastVal = VA.getValNo();
1757
1758     if (VA.isRegLoc()) {
1759       EVT RegVT = VA.getLocVT();
1760       TargetRegisterClass *RC = NULL;
1761       if (RegVT == MVT::i32)
1762         RC = X86::GR32RegisterClass;
1763       else if (Is64Bit && RegVT == MVT::i64)
1764         RC = X86::GR64RegisterClass;
1765       else if (RegVT == MVT::f32)
1766         RC = X86::FR32RegisterClass;
1767       else if (RegVT == MVT::f64)
1768         RC = X86::FR64RegisterClass;
1769       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1770         RC = X86::VR256RegisterClass;
1771       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1772         RC = X86::VR128RegisterClass;
1773       else if (RegVT == MVT::x86mmx)
1774         RC = X86::VR64RegisterClass;
1775       else
1776         llvm_unreachable("Unknown argument type!");
1777
1778       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1779       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1780
1781       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1782       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1783       // right size.
1784       if (VA.getLocInfo() == CCValAssign::SExt)
1785         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1786                                DAG.getValueType(VA.getValVT()));
1787       else if (VA.getLocInfo() == CCValAssign::ZExt)
1788         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1789                                DAG.getValueType(VA.getValVT()));
1790       else if (VA.getLocInfo() == CCValAssign::BCvt)
1791         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1792
1793       if (VA.isExtInLoc()) {
1794         // Handle MMX values passed in XMM regs.
1795         if (RegVT.isVector()) {
1796           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1797                                  ArgValue);
1798         } else
1799           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1800       }
1801     } else {
1802       assert(VA.isMemLoc());
1803       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1804     }
1805
1806     // If value is passed via pointer - do a load.
1807     if (VA.getLocInfo() == CCValAssign::Indirect)
1808       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1809                              MachinePointerInfo(), false, false, 0);
1810
1811     InVals.push_back(ArgValue);
1812   }
1813
1814   // The x86-64 ABI for returning structs by value requires that we copy
1815   // the sret argument into %rax for the return. Save the argument into
1816   // a virtual register so that we can access it from the return points.
1817   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1818     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1819     unsigned Reg = FuncInfo->getSRetReturnReg();
1820     if (!Reg) {
1821       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1822       FuncInfo->setSRetReturnReg(Reg);
1823     }
1824     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1825     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1826   }
1827
1828   unsigned StackSize = CCInfo.getNextStackOffset();
1829   // Align stack specially for tail calls.
1830   if (FuncIsMadeTailCallSafe(CallConv))
1831     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1832
1833   // If the function takes variable number of arguments, make a frame index for
1834   // the start of the first vararg value... for expansion of llvm.va_start.
1835   if (isVarArg) {
1836     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1837                     CallConv != CallingConv::X86_ThisCall)) {
1838       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1839     }
1840     if (Is64Bit) {
1841       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1842
1843       // FIXME: We should really autogenerate these arrays
1844       static const unsigned GPR64ArgRegsWin64[] = {
1845         X86::RCX, X86::RDX, X86::R8,  X86::R9
1846       };
1847       static const unsigned GPR64ArgRegs64Bit[] = {
1848         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1849       };
1850       static const unsigned XMMArgRegs64Bit[] = {
1851         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1852         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1853       };
1854       const unsigned *GPR64ArgRegs;
1855       unsigned NumXMMRegs = 0;
1856
1857       if (IsWin64) {
1858         // The XMM registers which might contain var arg parameters are shadowed
1859         // in their paired GPR.  So we only need to save the GPR to their home
1860         // slots.
1861         TotalNumIntRegs = 4;
1862         GPR64ArgRegs = GPR64ArgRegsWin64;
1863       } else {
1864         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1865         GPR64ArgRegs = GPR64ArgRegs64Bit;
1866
1867         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1868       }
1869       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1870                                                        TotalNumIntRegs);
1871
1872       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1873       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1874              "SSE register cannot be used when SSE is disabled!");
1875       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1876              "SSE register cannot be used when SSE is disabled!");
1877       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1878         // Kernel mode asks for SSE to be disabled, so don't push them
1879         // on the stack.
1880         TotalNumXMMRegs = 0;
1881
1882       if (IsWin64) {
1883         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1884         // Get to the caller-allocated home save location.  Add 8 to account
1885         // for the return address.
1886         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1887         FuncInfo->setRegSaveFrameIndex(
1888           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1889         // Fixup to set vararg frame on shadow area (4 x i64).
1890         if (NumIntRegs < 4)
1891           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1892       } else {
1893         // For X86-64, if there are vararg parameters that are passed via
1894         // registers, then we must store them to their spots on the stack so they
1895         // may be loaded by deferencing the result of va_next.
1896         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1897         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1898         FuncInfo->setRegSaveFrameIndex(
1899           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1900                                false));
1901       }
1902
1903       // Store the integer parameter registers.
1904       SmallVector<SDValue, 8> MemOps;
1905       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1906                                         getPointerTy());
1907       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1908       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1909         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1910                                   DAG.getIntPtrConstant(Offset));
1911         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1912                                      X86::GR64RegisterClass);
1913         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1914         SDValue Store =
1915           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1916                        MachinePointerInfo::getFixedStack(
1917                          FuncInfo->getRegSaveFrameIndex(), Offset),
1918                        false, false, 0);
1919         MemOps.push_back(Store);
1920         Offset += 8;
1921       }
1922
1923       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1924         // Now store the XMM (fp + vector) parameter registers.
1925         SmallVector<SDValue, 11> SaveXMMOps;
1926         SaveXMMOps.push_back(Chain);
1927
1928         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1929         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1930         SaveXMMOps.push_back(ALVal);
1931
1932         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1933                                FuncInfo->getRegSaveFrameIndex()));
1934         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1935                                FuncInfo->getVarArgsFPOffset()));
1936
1937         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1938           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1939                                        X86::VR128RegisterClass);
1940           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1941           SaveXMMOps.push_back(Val);
1942         }
1943         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1944                                      MVT::Other,
1945                                      &SaveXMMOps[0], SaveXMMOps.size()));
1946       }
1947
1948       if (!MemOps.empty())
1949         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1950                             &MemOps[0], MemOps.size());
1951     }
1952   }
1953
1954   // Some CCs need callee pop.
1955   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
1956     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1957   } else {
1958     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1959     // If this is an sret function, the return should pop the hidden pointer.
1960     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1961       FuncInfo->setBytesToPopOnReturn(4);
1962   }
1963
1964   if (!Is64Bit) {
1965     // RegSaveFrameIndex is X86-64 only.
1966     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1967     if (CallConv == CallingConv::X86_FastCall ||
1968         CallConv == CallingConv::X86_ThisCall)
1969       // fastcc functions can't have varargs.
1970       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1971   }
1972
1973   FuncInfo->setArgumentStackSize(StackSize);
1974
1975   return Chain;
1976 }
1977
1978 SDValue
1979 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1980                                     SDValue StackPtr, SDValue Arg,
1981                                     DebugLoc dl, SelectionDAG &DAG,
1982                                     const CCValAssign &VA,
1983                                     ISD::ArgFlagsTy Flags) const {
1984   unsigned LocMemOffset = VA.getLocMemOffset();
1985   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1986   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1987   if (Flags.isByVal())
1988     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1989
1990   return DAG.getStore(Chain, dl, Arg, PtrOff,
1991                       MachinePointerInfo::getStack(LocMemOffset),
1992                       false, false, 0);
1993 }
1994
1995 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1996 /// optimization is performed and it is required.
1997 SDValue
1998 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1999                                            SDValue &OutRetAddr, SDValue Chain,
2000                                            bool IsTailCall, bool Is64Bit,
2001                                            int FPDiff, DebugLoc dl) const {
2002   // Adjust the Return address stack slot.
2003   EVT VT = getPointerTy();
2004   OutRetAddr = getReturnAddressFrameIndex(DAG);
2005
2006   // Load the "old" Return address.
2007   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2008                            false, false, 0);
2009   return SDValue(OutRetAddr.getNode(), 1);
2010 }
2011
2012 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2013 /// optimization is performed and it is required (FPDiff!=0).
2014 static SDValue
2015 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2016                          SDValue Chain, SDValue RetAddrFrIdx,
2017                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2018   // Store the return address to the appropriate stack slot.
2019   if (!FPDiff) return Chain;
2020   // Calculate the new stack slot for the return address.
2021   int SlotSize = Is64Bit ? 8 : 4;
2022   int NewReturnAddrFI =
2023     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2024   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2025   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2026   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2027                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2028                        false, false, 0);
2029   return Chain;
2030 }
2031
2032 SDValue
2033 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2034                              CallingConv::ID CallConv, bool isVarArg,
2035                              bool &isTailCall,
2036                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2037                              const SmallVectorImpl<SDValue> &OutVals,
2038                              const SmallVectorImpl<ISD::InputArg> &Ins,
2039                              DebugLoc dl, SelectionDAG &DAG,
2040                              SmallVectorImpl<SDValue> &InVals) const {
2041   MachineFunction &MF = DAG.getMachineFunction();
2042   bool Is64Bit        = Subtarget->is64Bit();
2043   bool IsWin64        = Subtarget->isTargetWin64();
2044   bool IsStructRet    = CallIsStructReturn(Outs);
2045   bool IsSibcall      = false;
2046
2047   if (isTailCall) {
2048     // Check if it's really possible to do a tail call.
2049     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2050                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2051                                                    Outs, OutVals, Ins, DAG);
2052
2053     // Sibcalls are automatically detected tailcalls which do not require
2054     // ABI changes.
2055     if (!GuaranteedTailCallOpt && isTailCall)
2056       IsSibcall = true;
2057
2058     if (isTailCall)
2059       ++NumTailCalls;
2060   }
2061
2062   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2063          "Var args not supported with calling convention fastcc or ghc");
2064
2065   // Analyze operands of the call, assigning locations to each operand.
2066   SmallVector<CCValAssign, 16> ArgLocs;
2067   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2068                  ArgLocs, *DAG.getContext());
2069
2070   // Allocate shadow area for Win64
2071   if (IsWin64) {
2072     CCInfo.AllocateStack(32, 8);
2073   }
2074
2075   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2076
2077   // Get a count of how many bytes are to be pushed on the stack.
2078   unsigned NumBytes = CCInfo.getNextStackOffset();
2079   if (IsSibcall)
2080     // This is a sibcall. The memory operands are available in caller's
2081     // own caller's stack.
2082     NumBytes = 0;
2083   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2084     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2085
2086   int FPDiff = 0;
2087   if (isTailCall && !IsSibcall) {
2088     // Lower arguments at fp - stackoffset + fpdiff.
2089     unsigned NumBytesCallerPushed =
2090       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2091     FPDiff = NumBytesCallerPushed - NumBytes;
2092
2093     // Set the delta of movement of the returnaddr stackslot.
2094     // But only set if delta is greater than previous delta.
2095     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2096       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2097   }
2098
2099   if (!IsSibcall)
2100     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2101
2102   SDValue RetAddrFrIdx;
2103   // Load return address for tail calls.
2104   if (isTailCall && FPDiff)
2105     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2106                                     Is64Bit, FPDiff, dl);
2107
2108   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2109   SmallVector<SDValue, 8> MemOpChains;
2110   SDValue StackPtr;
2111
2112   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2113   // of tail call optimization arguments are handle later.
2114   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2115     CCValAssign &VA = ArgLocs[i];
2116     EVT RegVT = VA.getLocVT();
2117     SDValue Arg = OutVals[i];
2118     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2119     bool isByVal = Flags.isByVal();
2120
2121     // Promote the value if needed.
2122     switch (VA.getLocInfo()) {
2123     default: llvm_unreachable("Unknown loc info!");
2124     case CCValAssign::Full: break;
2125     case CCValAssign::SExt:
2126       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2127       break;
2128     case CCValAssign::ZExt:
2129       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2130       break;
2131     case CCValAssign::AExt:
2132       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2133         // Special case: passing MMX values in XMM registers.
2134         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2135         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2136         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2137       } else
2138         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2139       break;
2140     case CCValAssign::BCvt:
2141       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2142       break;
2143     case CCValAssign::Indirect: {
2144       // Store the argument.
2145       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2146       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2147       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2148                            MachinePointerInfo::getFixedStack(FI),
2149                            false, false, 0);
2150       Arg = SpillSlot;
2151       break;
2152     }
2153     }
2154
2155     if (VA.isRegLoc()) {
2156       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2157       if (isVarArg && IsWin64) {
2158         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2159         // shadow reg if callee is a varargs function.
2160         unsigned ShadowReg = 0;
2161         switch (VA.getLocReg()) {
2162         case X86::XMM0: ShadowReg = X86::RCX; break;
2163         case X86::XMM1: ShadowReg = X86::RDX; break;
2164         case X86::XMM2: ShadowReg = X86::R8; break;
2165         case X86::XMM3: ShadowReg = X86::R9; break;
2166         }
2167         if (ShadowReg)
2168           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2169       }
2170     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2171       assert(VA.isMemLoc());
2172       if (StackPtr.getNode() == 0)
2173         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2174       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2175                                              dl, DAG, VA, Flags));
2176     }
2177   }
2178
2179   if (!MemOpChains.empty())
2180     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2181                         &MemOpChains[0], MemOpChains.size());
2182
2183   // Build a sequence of copy-to-reg nodes chained together with token chain
2184   // and flag operands which copy the outgoing args into registers.
2185   SDValue InFlag;
2186   // Tail call byval lowering might overwrite argument registers so in case of
2187   // tail call optimization the copies to registers are lowered later.
2188   if (!isTailCall)
2189     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2190       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2191                                RegsToPass[i].second, InFlag);
2192       InFlag = Chain.getValue(1);
2193     }
2194
2195   if (Subtarget->isPICStyleGOT()) {
2196     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2197     // GOT pointer.
2198     if (!isTailCall) {
2199       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2200                                DAG.getNode(X86ISD::GlobalBaseReg,
2201                                            DebugLoc(), getPointerTy()),
2202                                InFlag);
2203       InFlag = Chain.getValue(1);
2204     } else {
2205       // If we are tail calling and generating PIC/GOT style code load the
2206       // address of the callee into ECX. The value in ecx is used as target of
2207       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2208       // for tail calls on PIC/GOT architectures. Normally we would just put the
2209       // address of GOT into ebx and then call target@PLT. But for tail calls
2210       // ebx would be restored (since ebx is callee saved) before jumping to the
2211       // target@PLT.
2212
2213       // Note: The actual moving to ECX is done further down.
2214       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2215       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2216           !G->getGlobal()->hasProtectedVisibility())
2217         Callee = LowerGlobalAddress(Callee, DAG);
2218       else if (isa<ExternalSymbolSDNode>(Callee))
2219         Callee = LowerExternalSymbol(Callee, DAG);
2220     }
2221   }
2222
2223   if (Is64Bit && isVarArg && !IsWin64) {
2224     // From AMD64 ABI document:
2225     // For calls that may call functions that use varargs or stdargs
2226     // (prototype-less calls or calls to functions containing ellipsis (...) in
2227     // the declaration) %al is used as hidden argument to specify the number
2228     // of SSE registers used. The contents of %al do not need to match exactly
2229     // the number of registers, but must be an ubound on the number of SSE
2230     // registers used and is in the range 0 - 8 inclusive.
2231
2232     // Count the number of XMM registers allocated.
2233     static const unsigned XMMArgRegs[] = {
2234       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2235       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2236     };
2237     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2238     assert((Subtarget->hasXMM() || !NumXMMRegs)
2239            && "SSE registers cannot be used when SSE is disabled");
2240
2241     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2242                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2243     InFlag = Chain.getValue(1);
2244   }
2245
2246
2247   // For tail calls lower the arguments to the 'real' stack slot.
2248   if (isTailCall) {
2249     // Force all the incoming stack arguments to be loaded from the stack
2250     // before any new outgoing arguments are stored to the stack, because the
2251     // outgoing stack slots may alias the incoming argument stack slots, and
2252     // the alias isn't otherwise explicit. This is slightly more conservative
2253     // than necessary, because it means that each store effectively depends
2254     // on every argument instead of just those arguments it would clobber.
2255     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2256
2257     SmallVector<SDValue, 8> MemOpChains2;
2258     SDValue FIN;
2259     int FI = 0;
2260     // Do not flag preceding copytoreg stuff together with the following stuff.
2261     InFlag = SDValue();
2262     if (GuaranteedTailCallOpt) {
2263       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2264         CCValAssign &VA = ArgLocs[i];
2265         if (VA.isRegLoc())
2266           continue;
2267         assert(VA.isMemLoc());
2268         SDValue Arg = OutVals[i];
2269         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2270         // Create frame index.
2271         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2272         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2273         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2274         FIN = DAG.getFrameIndex(FI, getPointerTy());
2275
2276         if (Flags.isByVal()) {
2277           // Copy relative to framepointer.
2278           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2279           if (StackPtr.getNode() == 0)
2280             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2281                                           getPointerTy());
2282           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2283
2284           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2285                                                            ArgChain,
2286                                                            Flags, DAG, dl));
2287         } else {
2288           // Store relative to framepointer.
2289           MemOpChains2.push_back(
2290             DAG.getStore(ArgChain, dl, Arg, FIN,
2291                          MachinePointerInfo::getFixedStack(FI),
2292                          false, false, 0));
2293         }
2294       }
2295     }
2296
2297     if (!MemOpChains2.empty())
2298       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2299                           &MemOpChains2[0], MemOpChains2.size());
2300
2301     // Copy arguments to their registers.
2302     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2303       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2304                                RegsToPass[i].second, InFlag);
2305       InFlag = Chain.getValue(1);
2306     }
2307     InFlag =SDValue();
2308
2309     // Store the return address to the appropriate stack slot.
2310     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2311                                      FPDiff, dl);
2312   }
2313
2314   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2315     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2316     // In the 64-bit large code model, we have to make all calls
2317     // through a register, since the call instruction's 32-bit
2318     // pc-relative offset may not be large enough to hold the whole
2319     // address.
2320   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2321     // If the callee is a GlobalAddress node (quite common, every direct call
2322     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2323     // it.
2324
2325     // We should use extra load for direct calls to dllimported functions in
2326     // non-JIT mode.
2327     const GlobalValue *GV = G->getGlobal();
2328     if (!GV->hasDLLImportLinkage()) {
2329       unsigned char OpFlags = 0;
2330       bool ExtraLoad = false;
2331       unsigned WrapperKind = ISD::DELETED_NODE;
2332
2333       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2334       // external symbols most go through the PLT in PIC mode.  If the symbol
2335       // has hidden or protected visibility, or if it is static or local, then
2336       // we don't need to use the PLT - we can directly call it.
2337       if (Subtarget->isTargetELF() &&
2338           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2339           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2340         OpFlags = X86II::MO_PLT;
2341       } else if (Subtarget->isPICStyleStubAny() &&
2342                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2343                  (!Subtarget->getTargetTriple().isMacOSX() ||
2344                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2345         // PC-relative references to external symbols should go through $stub,
2346         // unless we're building with the leopard linker or later, which
2347         // automatically synthesizes these stubs.
2348         OpFlags = X86II::MO_DARWIN_STUB;
2349       } else if (Subtarget->isPICStyleRIPRel() &&
2350                  isa<Function>(GV) &&
2351                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2352         // If the function is marked as non-lazy, generate an indirect call
2353         // which loads from the GOT directly. This avoids runtime overhead
2354         // at the cost of eager binding (and one extra byte of encoding).
2355         OpFlags = X86II::MO_GOTPCREL;
2356         WrapperKind = X86ISD::WrapperRIP;
2357         ExtraLoad = true;
2358       }
2359
2360       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2361                                           G->getOffset(), OpFlags);
2362
2363       // Add a wrapper if needed.
2364       if (WrapperKind != ISD::DELETED_NODE)
2365         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2366       // Add extra indirection if needed.
2367       if (ExtraLoad)
2368         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2369                              MachinePointerInfo::getGOT(),
2370                              false, false, 0);
2371     }
2372   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2373     unsigned char OpFlags = 0;
2374
2375     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2376     // external symbols should go through the PLT.
2377     if (Subtarget->isTargetELF() &&
2378         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2379       OpFlags = X86II::MO_PLT;
2380     } else if (Subtarget->isPICStyleStubAny() &&
2381                (!Subtarget->getTargetTriple().isMacOSX() ||
2382                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2383       // PC-relative references to external symbols should go through $stub,
2384       // unless we're building with the leopard linker or later, which
2385       // automatically synthesizes these stubs.
2386       OpFlags = X86II::MO_DARWIN_STUB;
2387     }
2388
2389     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2390                                          OpFlags);
2391   }
2392
2393   // Returns a chain & a flag for retval copy to use.
2394   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2395   SmallVector<SDValue, 8> Ops;
2396
2397   if (!IsSibcall && isTailCall) {
2398     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2399                            DAG.getIntPtrConstant(0, true), InFlag);
2400     InFlag = Chain.getValue(1);
2401   }
2402
2403   Ops.push_back(Chain);
2404   Ops.push_back(Callee);
2405
2406   if (isTailCall)
2407     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2408
2409   // Add argument registers to the end of the list so that they are known live
2410   // into the call.
2411   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2412     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2413                                   RegsToPass[i].second.getValueType()));
2414
2415   // Add an implicit use GOT pointer in EBX.
2416   if (!isTailCall && Subtarget->isPICStyleGOT())
2417     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2418
2419   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2420   if (Is64Bit && isVarArg && !IsWin64)
2421     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2422
2423   if (InFlag.getNode())
2424     Ops.push_back(InFlag);
2425
2426   if (isTailCall) {
2427     // We used to do:
2428     //// If this is the first return lowered for this function, add the regs
2429     //// to the liveout set for the function.
2430     // This isn't right, although it's probably harmless on x86; liveouts
2431     // should be computed from returns not tail calls.  Consider a void
2432     // function making a tail call to a function returning int.
2433     return DAG.getNode(X86ISD::TC_RETURN, dl,
2434                        NodeTys, &Ops[0], Ops.size());
2435   }
2436
2437   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2438   InFlag = Chain.getValue(1);
2439
2440   // Create the CALLSEQ_END node.
2441   unsigned NumBytesForCalleeToPush;
2442   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2443     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2444   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2445     // If this is a call to a struct-return function, the callee
2446     // pops the hidden struct pointer, so we have to push it back.
2447     // This is common for Darwin/X86, Linux & Mingw32 targets.
2448     NumBytesForCalleeToPush = 4;
2449   else
2450     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2451
2452   // Returns a flag for retval copy to use.
2453   if (!IsSibcall) {
2454     Chain = DAG.getCALLSEQ_END(Chain,
2455                                DAG.getIntPtrConstant(NumBytes, true),
2456                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2457                                                      true),
2458                                InFlag);
2459     InFlag = Chain.getValue(1);
2460   }
2461
2462   // Handle result values, copying them out of physregs into vregs that we
2463   // return.
2464   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2465                          Ins, dl, DAG, InVals);
2466 }
2467
2468
2469 //===----------------------------------------------------------------------===//
2470 //                Fast Calling Convention (tail call) implementation
2471 //===----------------------------------------------------------------------===//
2472
2473 //  Like std call, callee cleans arguments, convention except that ECX is
2474 //  reserved for storing the tail called function address. Only 2 registers are
2475 //  free for argument passing (inreg). Tail call optimization is performed
2476 //  provided:
2477 //                * tailcallopt is enabled
2478 //                * caller/callee are fastcc
2479 //  On X86_64 architecture with GOT-style position independent code only local
2480 //  (within module) calls are supported at the moment.
2481 //  To keep the stack aligned according to platform abi the function
2482 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2483 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2484 //  If a tail called function callee has more arguments than the caller the
2485 //  caller needs to make sure that there is room to move the RETADDR to. This is
2486 //  achieved by reserving an area the size of the argument delta right after the
2487 //  original REtADDR, but before the saved framepointer or the spilled registers
2488 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2489 //  stack layout:
2490 //    arg1
2491 //    arg2
2492 //    RETADDR
2493 //    [ new RETADDR
2494 //      move area ]
2495 //    (possible EBP)
2496 //    ESI
2497 //    EDI
2498 //    local1 ..
2499
2500 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2501 /// for a 16 byte align requirement.
2502 unsigned
2503 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2504                                                SelectionDAG& DAG) const {
2505   MachineFunction &MF = DAG.getMachineFunction();
2506   const TargetMachine &TM = MF.getTarget();
2507   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2508   unsigned StackAlignment = TFI.getStackAlignment();
2509   uint64_t AlignMask = StackAlignment - 1;
2510   int64_t Offset = StackSize;
2511   uint64_t SlotSize = TD->getPointerSize();
2512   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2513     // Number smaller than 12 so just add the difference.
2514     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2515   } else {
2516     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2517     Offset = ((~AlignMask) & Offset) + StackAlignment +
2518       (StackAlignment-SlotSize);
2519   }
2520   return Offset;
2521 }
2522
2523 /// MatchingStackOffset - Return true if the given stack call argument is
2524 /// already available in the same position (relatively) of the caller's
2525 /// incoming argument stack.
2526 static
2527 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2528                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2529                          const X86InstrInfo *TII) {
2530   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2531   int FI = INT_MAX;
2532   if (Arg.getOpcode() == ISD::CopyFromReg) {
2533     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2534     if (!TargetRegisterInfo::isVirtualRegister(VR))
2535       return false;
2536     MachineInstr *Def = MRI->getVRegDef(VR);
2537     if (!Def)
2538       return false;
2539     if (!Flags.isByVal()) {
2540       if (!TII->isLoadFromStackSlot(Def, FI))
2541         return false;
2542     } else {
2543       unsigned Opcode = Def->getOpcode();
2544       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2545           Def->getOperand(1).isFI()) {
2546         FI = Def->getOperand(1).getIndex();
2547         Bytes = Flags.getByValSize();
2548       } else
2549         return false;
2550     }
2551   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2552     if (Flags.isByVal())
2553       // ByVal argument is passed in as a pointer but it's now being
2554       // dereferenced. e.g.
2555       // define @foo(%struct.X* %A) {
2556       //   tail call @bar(%struct.X* byval %A)
2557       // }
2558       return false;
2559     SDValue Ptr = Ld->getBasePtr();
2560     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2561     if (!FINode)
2562       return false;
2563     FI = FINode->getIndex();
2564   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2565     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2566     FI = FINode->getIndex();
2567     Bytes = Flags.getByValSize();
2568   } else
2569     return false;
2570
2571   assert(FI != INT_MAX);
2572   if (!MFI->isFixedObjectIndex(FI))
2573     return false;
2574   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2575 }
2576
2577 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2578 /// for tail call optimization. Targets which want to do tail call
2579 /// optimization should implement this function.
2580 bool
2581 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2582                                                      CallingConv::ID CalleeCC,
2583                                                      bool isVarArg,
2584                                                      bool isCalleeStructRet,
2585                                                      bool isCallerStructRet,
2586                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2587                                     const SmallVectorImpl<SDValue> &OutVals,
2588                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2589                                                      SelectionDAG& DAG) const {
2590   if (!IsTailCallConvention(CalleeCC) &&
2591       CalleeCC != CallingConv::C)
2592     return false;
2593
2594   // If -tailcallopt is specified, make fastcc functions tail-callable.
2595   const MachineFunction &MF = DAG.getMachineFunction();
2596   const Function *CallerF = DAG.getMachineFunction().getFunction();
2597   CallingConv::ID CallerCC = CallerF->getCallingConv();
2598   bool CCMatch = CallerCC == CalleeCC;
2599
2600   if (GuaranteedTailCallOpt) {
2601     if (IsTailCallConvention(CalleeCC) && CCMatch)
2602       return true;
2603     return false;
2604   }
2605
2606   // Look for obvious safe cases to perform tail call optimization that do not
2607   // require ABI changes. This is what gcc calls sibcall.
2608
2609   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2610   // emit a special epilogue.
2611   if (RegInfo->needsStackRealignment(MF))
2612     return false;
2613
2614   // Also avoid sibcall optimization if either caller or callee uses struct
2615   // return semantics.
2616   if (isCalleeStructRet || isCallerStructRet)
2617     return false;
2618
2619   // An stdcall caller is expected to clean up its arguments; the callee
2620   // isn't going to do that.
2621   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2622     return false;
2623
2624   // Do not sibcall optimize vararg calls unless all arguments are passed via
2625   // registers.
2626   if (isVarArg && !Outs.empty()) {
2627
2628     // Optimizing for varargs on Win64 is unlikely to be safe without
2629     // additional testing.
2630     if (Subtarget->isTargetWin64())
2631       return false;
2632
2633     SmallVector<CCValAssign, 16> ArgLocs;
2634     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2635                    getTargetMachine(), ArgLocs, *DAG.getContext());
2636
2637     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2638     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2639       if (!ArgLocs[i].isRegLoc())
2640         return false;
2641   }
2642
2643   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2644   // Therefore if it's not used by the call it is not safe to optimize this into
2645   // a sibcall.
2646   bool Unused = false;
2647   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2648     if (!Ins[i].Used) {
2649       Unused = true;
2650       break;
2651     }
2652   }
2653   if (Unused) {
2654     SmallVector<CCValAssign, 16> RVLocs;
2655     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2656                    getTargetMachine(), RVLocs, *DAG.getContext());
2657     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2658     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2659       CCValAssign &VA = RVLocs[i];
2660       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2661         return false;
2662     }
2663   }
2664
2665   // If the calling conventions do not match, then we'd better make sure the
2666   // results are returned in the same way as what the caller expects.
2667   if (!CCMatch) {
2668     SmallVector<CCValAssign, 16> RVLocs1;
2669     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2670                     getTargetMachine(), RVLocs1, *DAG.getContext());
2671     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2672
2673     SmallVector<CCValAssign, 16> RVLocs2;
2674     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2675                     getTargetMachine(), RVLocs2, *DAG.getContext());
2676     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2677
2678     if (RVLocs1.size() != RVLocs2.size())
2679       return false;
2680     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2681       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2682         return false;
2683       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2684         return false;
2685       if (RVLocs1[i].isRegLoc()) {
2686         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2687           return false;
2688       } else {
2689         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2690           return false;
2691       }
2692     }
2693   }
2694
2695   // If the callee takes no arguments then go on to check the results of the
2696   // call.
2697   if (!Outs.empty()) {
2698     // Check if stack adjustment is needed. For now, do not do this if any
2699     // argument is passed on the stack.
2700     SmallVector<CCValAssign, 16> ArgLocs;
2701     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2702                    getTargetMachine(), ArgLocs, *DAG.getContext());
2703
2704     // Allocate shadow area for Win64
2705     if (Subtarget->isTargetWin64()) {
2706       CCInfo.AllocateStack(32, 8);
2707     }
2708
2709     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2710     if (CCInfo.getNextStackOffset()) {
2711       MachineFunction &MF = DAG.getMachineFunction();
2712       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2713         return false;
2714
2715       // Check if the arguments are already laid out in the right way as
2716       // the caller's fixed stack objects.
2717       MachineFrameInfo *MFI = MF.getFrameInfo();
2718       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2719       const X86InstrInfo *TII =
2720         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2721       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2722         CCValAssign &VA = ArgLocs[i];
2723         SDValue Arg = OutVals[i];
2724         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2725         if (VA.getLocInfo() == CCValAssign::Indirect)
2726           return false;
2727         if (!VA.isRegLoc()) {
2728           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2729                                    MFI, MRI, TII))
2730             return false;
2731         }
2732       }
2733     }
2734
2735     // If the tailcall address may be in a register, then make sure it's
2736     // possible to register allocate for it. In 32-bit, the call address can
2737     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2738     // callee-saved registers are restored. These happen to be the same
2739     // registers used to pass 'inreg' arguments so watch out for those.
2740     if (!Subtarget->is64Bit() &&
2741         !isa<GlobalAddressSDNode>(Callee) &&
2742         !isa<ExternalSymbolSDNode>(Callee)) {
2743       unsigned NumInRegs = 0;
2744       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2745         CCValAssign &VA = ArgLocs[i];
2746         if (!VA.isRegLoc())
2747           continue;
2748         unsigned Reg = VA.getLocReg();
2749         switch (Reg) {
2750         default: break;
2751         case X86::EAX: case X86::EDX: case X86::ECX:
2752           if (++NumInRegs == 3)
2753             return false;
2754           break;
2755         }
2756       }
2757     }
2758   }
2759
2760   return true;
2761 }
2762
2763 FastISel *
2764 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2765   return X86::createFastISel(funcInfo);
2766 }
2767
2768
2769 //===----------------------------------------------------------------------===//
2770 //                           Other Lowering Hooks
2771 //===----------------------------------------------------------------------===//
2772
2773 static bool MayFoldLoad(SDValue Op) {
2774   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2775 }
2776
2777 static bool MayFoldIntoStore(SDValue Op) {
2778   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2779 }
2780
2781 static bool isTargetShuffle(unsigned Opcode) {
2782   switch(Opcode) {
2783   default: return false;
2784   case X86ISD::PSHUFD:
2785   case X86ISD::PSHUFHW:
2786   case X86ISD::PSHUFLW:
2787   case X86ISD::SHUFPD:
2788   case X86ISD::PALIGN:
2789   case X86ISD::SHUFPS:
2790   case X86ISD::MOVLHPS:
2791   case X86ISD::MOVLHPD:
2792   case X86ISD::MOVHLPS:
2793   case X86ISD::MOVLPS:
2794   case X86ISD::MOVLPD:
2795   case X86ISD::MOVSHDUP:
2796   case X86ISD::MOVSLDUP:
2797   case X86ISD::MOVDDUP:
2798   case X86ISD::MOVSS:
2799   case X86ISD::MOVSD:
2800   case X86ISD::UNPCKLPS:
2801   case X86ISD::UNPCKLPD:
2802   case X86ISD::VUNPCKLPSY:
2803   case X86ISD::VUNPCKLPDY:
2804   case X86ISD::PUNPCKLWD:
2805   case X86ISD::PUNPCKLBW:
2806   case X86ISD::PUNPCKLDQ:
2807   case X86ISD::PUNPCKLQDQ:
2808   case X86ISD::UNPCKHPS:
2809   case X86ISD::UNPCKHPD:
2810   case X86ISD::VUNPCKHPSY:
2811   case X86ISD::VUNPCKHPDY:
2812   case X86ISD::PUNPCKHWD:
2813   case X86ISD::PUNPCKHBW:
2814   case X86ISD::PUNPCKHDQ:
2815   case X86ISD::PUNPCKHQDQ:
2816   case X86ISD::VPERMILPS:
2817   case X86ISD::VPERMILPSY:
2818   case X86ISD::VPERMILPD:
2819   case X86ISD::VPERMILPDY:
2820   case X86ISD::VPERM2F128:
2821     return true;
2822   }
2823   return false;
2824 }
2825
2826 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2827                                                SDValue V1, SelectionDAG &DAG) {
2828   switch(Opc) {
2829   default: llvm_unreachable("Unknown x86 shuffle node");
2830   case X86ISD::MOVSHDUP:
2831   case X86ISD::MOVSLDUP:
2832   case X86ISD::MOVDDUP:
2833     return DAG.getNode(Opc, dl, VT, V1);
2834   }
2835
2836   return SDValue();
2837 }
2838
2839 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2840                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2841   switch(Opc) {
2842   default: llvm_unreachable("Unknown x86 shuffle node");
2843   case X86ISD::PSHUFD:
2844   case X86ISD::PSHUFHW:
2845   case X86ISD::PSHUFLW:
2846   case X86ISD::VPERMILPS:
2847   case X86ISD::VPERMILPSY:
2848   case X86ISD::VPERMILPD:
2849   case X86ISD::VPERMILPDY:
2850     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2851   }
2852
2853   return SDValue();
2854 }
2855
2856 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2857                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2858   switch(Opc) {
2859   default: llvm_unreachable("Unknown x86 shuffle node");
2860   case X86ISD::PALIGN:
2861   case X86ISD::SHUFPD:
2862   case X86ISD::SHUFPS:
2863   case X86ISD::VPERM2F128:
2864     return DAG.getNode(Opc, dl, VT, V1, V2,
2865                        DAG.getConstant(TargetMask, MVT::i8));
2866   }
2867   return SDValue();
2868 }
2869
2870 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2871                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2872   switch(Opc) {
2873   default: llvm_unreachable("Unknown x86 shuffle node");
2874   case X86ISD::MOVLHPS:
2875   case X86ISD::MOVLHPD:
2876   case X86ISD::MOVHLPS:
2877   case X86ISD::MOVLPS:
2878   case X86ISD::MOVLPD:
2879   case X86ISD::MOVSS:
2880   case X86ISD::MOVSD:
2881   case X86ISD::UNPCKLPS:
2882   case X86ISD::UNPCKLPD:
2883   case X86ISD::VUNPCKLPSY:
2884   case X86ISD::VUNPCKLPDY:
2885   case X86ISD::PUNPCKLWD:
2886   case X86ISD::PUNPCKLBW:
2887   case X86ISD::PUNPCKLDQ:
2888   case X86ISD::PUNPCKLQDQ:
2889   case X86ISD::UNPCKHPS:
2890   case X86ISD::UNPCKHPD:
2891   case X86ISD::VUNPCKHPSY:
2892   case X86ISD::VUNPCKHPDY:
2893   case X86ISD::PUNPCKHWD:
2894   case X86ISD::PUNPCKHBW:
2895   case X86ISD::PUNPCKHDQ:
2896   case X86ISD::PUNPCKHQDQ:
2897     return DAG.getNode(Opc, dl, VT, V1, V2);
2898   }
2899   return SDValue();
2900 }
2901
2902 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2903   MachineFunction &MF = DAG.getMachineFunction();
2904   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2905   int ReturnAddrIndex = FuncInfo->getRAIndex();
2906
2907   if (ReturnAddrIndex == 0) {
2908     // Set up a frame object for the return address.
2909     uint64_t SlotSize = TD->getPointerSize();
2910     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2911                                                            false);
2912     FuncInfo->setRAIndex(ReturnAddrIndex);
2913   }
2914
2915   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2916 }
2917
2918
2919 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2920                                        bool hasSymbolicDisplacement) {
2921   // Offset should fit into 32 bit immediate field.
2922   if (!isInt<32>(Offset))
2923     return false;
2924
2925   // If we don't have a symbolic displacement - we don't have any extra
2926   // restrictions.
2927   if (!hasSymbolicDisplacement)
2928     return true;
2929
2930   // FIXME: Some tweaks might be needed for medium code model.
2931   if (M != CodeModel::Small && M != CodeModel::Kernel)
2932     return false;
2933
2934   // For small code model we assume that latest object is 16MB before end of 31
2935   // bits boundary. We may also accept pretty large negative constants knowing
2936   // that all objects are in the positive half of address space.
2937   if (M == CodeModel::Small && Offset < 16*1024*1024)
2938     return true;
2939
2940   // For kernel code model we know that all object resist in the negative half
2941   // of 32bits address space. We may not accept negative offsets, since they may
2942   // be just off and we may accept pretty large positive ones.
2943   if (M == CodeModel::Kernel && Offset > 0)
2944     return true;
2945
2946   return false;
2947 }
2948
2949 /// isCalleePop - Determines whether the callee is required to pop its
2950 /// own arguments. Callee pop is necessary to support tail calls.
2951 bool X86::isCalleePop(CallingConv::ID CallingConv,
2952                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
2953   if (IsVarArg)
2954     return false;
2955
2956   switch (CallingConv) {
2957   default:
2958     return false;
2959   case CallingConv::X86_StdCall:
2960     return !is64Bit;
2961   case CallingConv::X86_FastCall:
2962     return !is64Bit;
2963   case CallingConv::X86_ThisCall:
2964     return !is64Bit;
2965   case CallingConv::Fast:
2966     return TailCallOpt;
2967   case CallingConv::GHC:
2968     return TailCallOpt;
2969   }
2970 }
2971
2972 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2973 /// specific condition code, returning the condition code and the LHS/RHS of the
2974 /// comparison to make.
2975 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2976                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2977   if (!isFP) {
2978     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2979       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2980         // X > -1   -> X == 0, jump !sign.
2981         RHS = DAG.getConstant(0, RHS.getValueType());
2982         return X86::COND_NS;
2983       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2984         // X < 0   -> X == 0, jump on sign.
2985         return X86::COND_S;
2986       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2987         // X < 1   -> X <= 0
2988         RHS = DAG.getConstant(0, RHS.getValueType());
2989         return X86::COND_LE;
2990       }
2991     }
2992
2993     switch (SetCCOpcode) {
2994     default: llvm_unreachable("Invalid integer condition!");
2995     case ISD::SETEQ:  return X86::COND_E;
2996     case ISD::SETGT:  return X86::COND_G;
2997     case ISD::SETGE:  return X86::COND_GE;
2998     case ISD::SETLT:  return X86::COND_L;
2999     case ISD::SETLE:  return X86::COND_LE;
3000     case ISD::SETNE:  return X86::COND_NE;
3001     case ISD::SETULT: return X86::COND_B;
3002     case ISD::SETUGT: return X86::COND_A;
3003     case ISD::SETULE: return X86::COND_BE;
3004     case ISD::SETUGE: return X86::COND_AE;
3005     }
3006   }
3007
3008   // First determine if it is required or is profitable to flip the operands.
3009
3010   // If LHS is a foldable load, but RHS is not, flip the condition.
3011   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3012       !ISD::isNON_EXTLoad(RHS.getNode())) {
3013     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3014     std::swap(LHS, RHS);
3015   }
3016
3017   switch (SetCCOpcode) {
3018   default: break;
3019   case ISD::SETOLT:
3020   case ISD::SETOLE:
3021   case ISD::SETUGT:
3022   case ISD::SETUGE:
3023     std::swap(LHS, RHS);
3024     break;
3025   }
3026
3027   // On a floating point condition, the flags are set as follows:
3028   // ZF  PF  CF   op
3029   //  0 | 0 | 0 | X > Y
3030   //  0 | 0 | 1 | X < Y
3031   //  1 | 0 | 0 | X == Y
3032   //  1 | 1 | 1 | unordered
3033   switch (SetCCOpcode) {
3034   default: llvm_unreachable("Condcode should be pre-legalized away");
3035   case ISD::SETUEQ:
3036   case ISD::SETEQ:   return X86::COND_E;
3037   case ISD::SETOLT:              // flipped
3038   case ISD::SETOGT:
3039   case ISD::SETGT:   return X86::COND_A;
3040   case ISD::SETOLE:              // flipped
3041   case ISD::SETOGE:
3042   case ISD::SETGE:   return X86::COND_AE;
3043   case ISD::SETUGT:              // flipped
3044   case ISD::SETULT:
3045   case ISD::SETLT:   return X86::COND_B;
3046   case ISD::SETUGE:              // flipped
3047   case ISD::SETULE:
3048   case ISD::SETLE:   return X86::COND_BE;
3049   case ISD::SETONE:
3050   case ISD::SETNE:   return X86::COND_NE;
3051   case ISD::SETUO:   return X86::COND_P;
3052   case ISD::SETO:    return X86::COND_NP;
3053   case ISD::SETOEQ:
3054   case ISD::SETUNE:  return X86::COND_INVALID;
3055   }
3056 }
3057
3058 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3059 /// code. Current x86 isa includes the following FP cmov instructions:
3060 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3061 static bool hasFPCMov(unsigned X86CC) {
3062   switch (X86CC) {
3063   default:
3064     return false;
3065   case X86::COND_B:
3066   case X86::COND_BE:
3067   case X86::COND_E:
3068   case X86::COND_P:
3069   case X86::COND_A:
3070   case X86::COND_AE:
3071   case X86::COND_NE:
3072   case X86::COND_NP:
3073     return true;
3074   }
3075 }
3076
3077 /// isFPImmLegal - Returns true if the target can instruction select the
3078 /// specified FP immediate natively. If false, the legalizer will
3079 /// materialize the FP immediate as a load from a constant pool.
3080 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3081   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3082     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3083       return true;
3084   }
3085   return false;
3086 }
3087
3088 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3089 /// the specified range (L, H].
3090 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3091   return (Val < 0) || (Val >= Low && Val < Hi);
3092 }
3093
3094 /// isUndefOrInRange - Return true if every element in Mask, begining
3095 /// from position Pos and ending in Pos+Size, falls within the specified
3096 /// range (L, L+Pos]. or is undef.
3097 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3098                              int Pos, int Size, int Low, int Hi) {
3099   for (int i = Pos, e = Pos+Size; i != e; ++i)
3100     if (!isUndefOrInRange(Mask[i], Low, Hi))
3101       return false;
3102   return true;
3103 }
3104
3105 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3106 /// specified value.
3107 static bool isUndefOrEqual(int Val, int CmpVal) {
3108   if (Val < 0 || Val == CmpVal)
3109     return true;
3110   return false;
3111 }
3112
3113 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3114 /// from position Pos and ending in Pos+Size, falls within the specified
3115 /// sequential range (L, L+Pos]. or is undef.
3116 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3117                                        int Pos, int Size, int Low) {
3118   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3119     if (!isUndefOrEqual(Mask[i], Low))
3120       return false;
3121   return true;
3122 }
3123
3124 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3125 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3126 /// the second operand.
3127 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3128   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3129     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3130   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3131     return (Mask[0] < 2 && Mask[1] < 2);
3132   return false;
3133 }
3134
3135 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3136   SmallVector<int, 8> M;
3137   N->getMask(M);
3138   return ::isPSHUFDMask(M, N->getValueType(0));
3139 }
3140
3141 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3142 /// is suitable for input to PSHUFHW.
3143 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3144   if (VT != MVT::v8i16)
3145     return false;
3146
3147   // Lower quadword copied in order or undef.
3148   for (int i = 0; i != 4; ++i)
3149     if (Mask[i] >= 0 && Mask[i] != i)
3150       return false;
3151
3152   // Upper quadword shuffled.
3153   for (int i = 4; i != 8; ++i)
3154     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3155       return false;
3156
3157   return true;
3158 }
3159
3160 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3161   SmallVector<int, 8> M;
3162   N->getMask(M);
3163   return ::isPSHUFHWMask(M, N->getValueType(0));
3164 }
3165
3166 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3167 /// is suitable for input to PSHUFLW.
3168 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3169   if (VT != MVT::v8i16)
3170     return false;
3171
3172   // Upper quadword copied in order.
3173   for (int i = 4; i != 8; ++i)
3174     if (Mask[i] >= 0 && Mask[i] != i)
3175       return false;
3176
3177   // Lower quadword shuffled.
3178   for (int i = 0; i != 4; ++i)
3179     if (Mask[i] >= 4)
3180       return false;
3181
3182   return true;
3183 }
3184
3185 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3186   SmallVector<int, 8> M;
3187   N->getMask(M);
3188   return ::isPSHUFLWMask(M, N->getValueType(0));
3189 }
3190
3191 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3192 /// is suitable for input to PALIGNR.
3193 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3194                           bool hasSSSE3OrAVX) {
3195   int i, e = VT.getVectorNumElements();
3196   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3197     return false;
3198
3199   // Do not handle v2i64 / v2f64 shuffles with palignr.
3200   if (e < 4 || !hasSSSE3OrAVX)
3201     return false;
3202
3203   for (i = 0; i != e; ++i)
3204     if (Mask[i] >= 0)
3205       break;
3206
3207   // All undef, not a palignr.
3208   if (i == e)
3209     return false;
3210
3211   // Make sure we're shifting in the right direction.
3212   if (Mask[i] <= i)
3213     return false;
3214
3215   int s = Mask[i] - i;
3216
3217   // Check the rest of the elements to see if they are consecutive.
3218   for (++i; i != e; ++i) {
3219     int m = Mask[i];
3220     if (m >= 0 && m != s+i)
3221       return false;
3222   }
3223   return true;
3224 }
3225
3226 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3227 /// specifies a shuffle of elements that is suitable for input to 256-bit
3228 /// VSHUFPSY.
3229 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3230                           const X86Subtarget *Subtarget) {
3231   int NumElems = VT.getVectorNumElements();
3232
3233   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3234     return false;
3235
3236   if (NumElems != 8)
3237     return false;
3238
3239   // VSHUFPSY divides the resulting vector into 4 chunks.
3240   // The sources are also splitted into 4 chunks, and each destination
3241   // chunk must come from a different source chunk.
3242   //
3243   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3244   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3245   //
3246   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3247   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3248   //
3249   int QuarterSize = NumElems/4;
3250   int HalfSize = QuarterSize*2;
3251   for (int i = 0; i < QuarterSize; ++i)
3252     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3253       return false;
3254   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3255     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3256       return false;
3257
3258   // The mask of the second half must be the same as the first but with
3259   // the appropriate offsets. This works in the same way as VPERMILPS
3260   // works with masks.
3261   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3262     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3263       return false;
3264     int FstHalfIdx = i-HalfSize;
3265     if (Mask[FstHalfIdx] < 0)
3266       continue;
3267     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3268       return false;
3269   }
3270   for (int i = QuarterSize*3; i < NumElems; ++i) {
3271     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3272       return false;
3273     int FstHalfIdx = i-HalfSize;
3274     if (Mask[FstHalfIdx] < 0)
3275       continue;
3276     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3277       return false;
3278
3279   }
3280
3281   return true;
3282 }
3283
3284 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3285 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3286 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3287   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3288   EVT VT = SVOp->getValueType(0);
3289   int NumElems = VT.getVectorNumElements();
3290
3291   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3292          "Only supports v8i32 and v8f32 types");
3293
3294   int HalfSize = NumElems/2;
3295   unsigned Mask = 0;
3296   for (int i = 0; i != NumElems ; ++i) {
3297     if (SVOp->getMaskElt(i) < 0)
3298       continue;
3299     // The mask of the first half must be equal to the second one.
3300     unsigned Shamt = (i%HalfSize)*2;
3301     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3302     Mask |= Elt << Shamt;
3303   }
3304
3305   return Mask;
3306 }
3307
3308 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3309 /// specifies a shuffle of elements that is suitable for input to 256-bit
3310 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3311 /// version and the mask of the second half isn't binded with the first
3312 /// one.
3313 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3314                            const X86Subtarget *Subtarget) {
3315   int NumElems = VT.getVectorNumElements();
3316
3317   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3318     return false;
3319
3320   if (NumElems != 4)
3321     return false;
3322
3323   // VSHUFPSY divides the resulting vector into 4 chunks.
3324   // The sources are also splitted into 4 chunks, and each destination
3325   // chunk must come from a different source chunk.
3326   //
3327   //  SRC1 =>      X3       X2       X1       X0
3328   //  SRC2 =>      Y3       Y2       Y1       Y0
3329   //
3330   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3331   //
3332   int QuarterSize = NumElems/4;
3333   int HalfSize = QuarterSize*2;
3334   for (int i = 0; i < QuarterSize; ++i)
3335     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3336       return false;
3337   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3338     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3339       return false;
3340   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3341     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3342       return false;
3343   for (int i = QuarterSize*3; i < NumElems; ++i)
3344     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3345       return false;
3346
3347   return true;
3348 }
3349
3350 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3351 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3352 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3353   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3354   EVT VT = SVOp->getValueType(0);
3355   int NumElems = VT.getVectorNumElements();
3356
3357   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3358          "Only supports v4i64 and v4f64 types");
3359
3360   int HalfSize = NumElems/2;
3361   unsigned Mask = 0;
3362   for (int i = 0; i != NumElems ; ++i) {
3363     if (SVOp->getMaskElt(i) < 0)
3364       continue;
3365     int Elt = SVOp->getMaskElt(i) % HalfSize;
3366     Mask |= Elt << i;
3367   }
3368
3369   return Mask;
3370 }
3371
3372 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3373 /// specifies a shuffle of elements that is suitable for input to 128-bit
3374 /// SHUFPS and SHUFPD.
3375 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3376   int NumElems = VT.getVectorNumElements();
3377
3378   if (VT.getSizeInBits() != 128)
3379     return false;
3380
3381   if (NumElems != 2 && NumElems != 4)
3382     return false;
3383
3384   int Half = NumElems / 2;
3385   for (int i = 0; i < Half; ++i)
3386     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3387       return false;
3388   for (int i = Half; i < NumElems; ++i)
3389     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3390       return false;
3391
3392   return true;
3393 }
3394
3395 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3396   SmallVector<int, 8> M;
3397   N->getMask(M);
3398   return ::isSHUFPMask(M, N->getValueType(0));
3399 }
3400
3401 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3402 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3403 /// half elements to come from vector 1 (which would equal the dest.) and
3404 /// the upper half to come from vector 2.
3405 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3406   int NumElems = VT.getVectorNumElements();
3407
3408   if (NumElems != 2 && NumElems != 4)
3409     return false;
3410
3411   int Half = NumElems / 2;
3412   for (int i = 0; i < Half; ++i)
3413     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3414       return false;
3415   for (int i = Half; i < NumElems; ++i)
3416     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3417       return false;
3418   return true;
3419 }
3420
3421 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3422   SmallVector<int, 8> M;
3423   N->getMask(M);
3424   return isCommutedSHUFPMask(M, N->getValueType(0));
3425 }
3426
3427 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3428 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3429 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3430   EVT VT = N->getValueType(0);
3431   unsigned NumElems = VT.getVectorNumElements();
3432
3433   if (VT.getSizeInBits() != 128)
3434     return false;
3435
3436   if (NumElems != 4)
3437     return false;
3438
3439   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3440   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3441          isUndefOrEqual(N->getMaskElt(1), 7) &&
3442          isUndefOrEqual(N->getMaskElt(2), 2) &&
3443          isUndefOrEqual(N->getMaskElt(3), 3);
3444 }
3445
3446 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3447 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3448 /// <2, 3, 2, 3>
3449 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3450   EVT VT = N->getValueType(0);
3451   unsigned NumElems = VT.getVectorNumElements();
3452
3453   if (VT.getSizeInBits() != 128)
3454     return false;
3455
3456   if (NumElems != 4)
3457     return false;
3458
3459   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3460          isUndefOrEqual(N->getMaskElt(1), 3) &&
3461          isUndefOrEqual(N->getMaskElt(2), 2) &&
3462          isUndefOrEqual(N->getMaskElt(3), 3);
3463 }
3464
3465 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3466 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3467 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3468   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3469
3470   if (NumElems != 2 && NumElems != 4)
3471     return false;
3472
3473   for (unsigned i = 0; i < NumElems/2; ++i)
3474     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3475       return false;
3476
3477   for (unsigned i = NumElems/2; i < NumElems; ++i)
3478     if (!isUndefOrEqual(N->getMaskElt(i), i))
3479       return false;
3480
3481   return true;
3482 }
3483
3484 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3485 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3486 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3487   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3488
3489   if ((NumElems != 2 && NumElems != 4)
3490       || N->getValueType(0).getSizeInBits() > 128)
3491     return false;
3492
3493   for (unsigned i = 0; i < NumElems/2; ++i)
3494     if (!isUndefOrEqual(N->getMaskElt(i), i))
3495       return false;
3496
3497   for (unsigned i = 0; i < NumElems/2; ++i)
3498     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3499       return false;
3500
3501   return true;
3502 }
3503
3504 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3505 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3506 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3507                          bool V2IsSplat = false) {
3508   int NumElts = VT.getVectorNumElements();
3509
3510   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3511          "Unsupported vector type for unpckh");
3512
3513   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3514     return false;
3515
3516   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3517   // independently on 128-bit lanes.
3518   unsigned NumLanes = VT.getSizeInBits()/128;
3519   unsigned NumLaneElts = NumElts/NumLanes;
3520
3521   unsigned Start = 0;
3522   unsigned End = NumLaneElts;
3523   for (unsigned s = 0; s < NumLanes; ++s) {
3524     for (unsigned i = Start, j = s * NumLaneElts;
3525          i != End;
3526          i += 2, ++j) {
3527       int BitI  = Mask[i];
3528       int BitI1 = Mask[i+1];
3529       if (!isUndefOrEqual(BitI, j))
3530         return false;
3531       if (V2IsSplat) {
3532         if (!isUndefOrEqual(BitI1, NumElts))
3533           return false;
3534       } else {
3535         if (!isUndefOrEqual(BitI1, j + NumElts))
3536           return false;
3537       }
3538     }
3539     // Process the next 128 bits.
3540     Start += NumLaneElts;
3541     End += NumLaneElts;
3542   }
3543
3544   return true;
3545 }
3546
3547 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3548   SmallVector<int, 8> M;
3549   N->getMask(M);
3550   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3551 }
3552
3553 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3554 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3555 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3556                          bool V2IsSplat = false) {
3557   int NumElts = VT.getVectorNumElements();
3558
3559   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3560          "Unsupported vector type for unpckh");
3561
3562   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8)
3563     return false;
3564
3565   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3566   // independently on 128-bit lanes.
3567   unsigned NumLanes = VT.getSizeInBits()/128;
3568   unsigned NumLaneElts = NumElts/NumLanes;
3569
3570   unsigned Start = 0;
3571   unsigned End = NumLaneElts;
3572   for (unsigned l = 0; l != NumLanes; ++l) {
3573     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3574                              i != End; i += 2, ++j) {
3575       int BitI  = Mask[i];
3576       int BitI1 = Mask[i+1];
3577       if (!isUndefOrEqual(BitI, j))
3578         return false;
3579       if (V2IsSplat) {
3580         if (isUndefOrEqual(BitI1, NumElts))
3581           return false;
3582       } else {
3583         if (!isUndefOrEqual(BitI1, j+NumElts))
3584           return false;
3585       }
3586     }
3587     // Process the next 128 bits.
3588     Start += NumLaneElts;
3589     End += NumLaneElts;
3590   }
3591   return true;
3592 }
3593
3594 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3595   SmallVector<int, 8> M;
3596   N->getMask(M);
3597   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3598 }
3599
3600 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3601 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3602 /// <0, 0, 1, 1>
3603 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3604   int NumElems = VT.getVectorNumElements();
3605   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3606     return false;
3607
3608   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3609   // FIXME: Need a better way to get rid of this, there's no latency difference
3610   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3611   // the former later. We should also remove the "_undef" special mask.
3612   if (NumElems == 4 && VT.getSizeInBits() == 256)
3613     return false;
3614
3615   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3616   // independently on 128-bit lanes.
3617   unsigned NumLanes = VT.getSizeInBits() / 128;
3618   unsigned NumLaneElts = NumElems / NumLanes;
3619
3620   for (unsigned s = 0; s < NumLanes; ++s) {
3621     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3622          i != NumLaneElts * (s + 1);
3623          i += 2, ++j) {
3624       int BitI  = Mask[i];
3625       int BitI1 = Mask[i+1];
3626
3627       if (!isUndefOrEqual(BitI, j))
3628         return false;
3629       if (!isUndefOrEqual(BitI1, j))
3630         return false;
3631     }
3632   }
3633
3634   return true;
3635 }
3636
3637 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3638   SmallVector<int, 8> M;
3639   N->getMask(M);
3640   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3641 }
3642
3643 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3644 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3645 /// <2, 2, 3, 3>
3646 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3647   int NumElems = VT.getVectorNumElements();
3648   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3649     return false;
3650
3651   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3652     int BitI  = Mask[i];
3653     int BitI1 = Mask[i+1];
3654     if (!isUndefOrEqual(BitI, j))
3655       return false;
3656     if (!isUndefOrEqual(BitI1, j))
3657       return false;
3658   }
3659   return true;
3660 }
3661
3662 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3663   SmallVector<int, 8> M;
3664   N->getMask(M);
3665   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3666 }
3667
3668 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3669 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3670 /// MOVSD, and MOVD, i.e. setting the lowest element.
3671 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3672   if (VT.getVectorElementType().getSizeInBits() < 32)
3673     return false;
3674
3675   int NumElts = VT.getVectorNumElements();
3676
3677   if (!isUndefOrEqual(Mask[0], NumElts))
3678     return false;
3679
3680   for (int i = 1; i < NumElts; ++i)
3681     if (!isUndefOrEqual(Mask[i], i))
3682       return false;
3683
3684   return true;
3685 }
3686
3687 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3688   SmallVector<int, 8> M;
3689   N->getMask(M);
3690   return ::isMOVLMask(M, N->getValueType(0));
3691 }
3692
3693 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3694 /// as permutations between 128-bit chunks or halves. As an example: this
3695 /// shuffle bellow:
3696 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3697 /// The first half comes from the second half of V1 and the second half from the
3698 /// the second half of V2.
3699 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3700                              const X86Subtarget *Subtarget) {
3701   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3702     return false;
3703
3704   // The shuffle result is divided into half A and half B. In total the two
3705   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3706   // B must come from C, D, E or F.
3707   int HalfSize = VT.getVectorNumElements()/2;
3708   bool MatchA = false, MatchB = false;
3709
3710   // Check if A comes from one of C, D, E, F.
3711   for (int Half = 0; Half < 4; ++Half) {
3712     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3713       MatchA = true;
3714       break;
3715     }
3716   }
3717
3718   // Check if B comes from one of C, D, E, F.
3719   for (int Half = 0; Half < 4; ++Half) {
3720     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3721       MatchB = true;
3722       break;
3723     }
3724   }
3725
3726   return MatchA && MatchB;
3727 }
3728
3729 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3730 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3731 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3732   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3733   EVT VT = SVOp->getValueType(0);
3734
3735   int HalfSize = VT.getVectorNumElements()/2;
3736
3737   int FstHalf = 0, SndHalf = 0;
3738   for (int i = 0; i < HalfSize; ++i) {
3739     if (SVOp->getMaskElt(i) > 0) {
3740       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3741       break;
3742     }
3743   }
3744   for (int i = HalfSize; i < HalfSize*2; ++i) {
3745     if (SVOp->getMaskElt(i) > 0) {
3746       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3747       break;
3748     }
3749   }
3750
3751   return (FstHalf | (SndHalf << 4));
3752 }
3753
3754 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3755 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3756 /// Note that VPERMIL mask matching is different depending whether theunderlying
3757 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3758 /// to the same elements of the low, but to the higher half of the source.
3759 /// In VPERMILPD the two lanes could be shuffled independently of each other
3760 /// with the same restriction that lanes can't be crossed.
3761 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3762                             const X86Subtarget *Subtarget) {
3763   int NumElts = VT.getVectorNumElements();
3764   int NumLanes = VT.getSizeInBits()/128;
3765
3766   if (!Subtarget->hasAVX())
3767     return false;
3768
3769   // Only match 256-bit with 64-bit types
3770   if (VT.getSizeInBits() != 256 || NumElts != 4)
3771     return false;
3772
3773   // The mask on the high lane is independent of the low. Both can match
3774   // any element in inside its own lane, but can't cross.
3775   int LaneSize = NumElts/NumLanes;
3776   for (int l = 0; l < NumLanes; ++l)
3777     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3778       int LaneStart = l*LaneSize;
3779       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3780         return false;
3781     }
3782
3783   return true;
3784 }
3785
3786 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3787 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3788 /// Note that VPERMIL mask matching is different depending whether theunderlying
3789 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3790 /// to the same elements of the low, but to the higher half of the source.
3791 /// In VPERMILPD the two lanes could be shuffled independently of each other
3792 /// with the same restriction that lanes can't be crossed.
3793 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3794                             const X86Subtarget *Subtarget) {
3795   unsigned NumElts = VT.getVectorNumElements();
3796   unsigned NumLanes = VT.getSizeInBits()/128;
3797
3798   if (!Subtarget->hasAVX())
3799     return false;
3800
3801   // Only match 256-bit with 32-bit types
3802   if (VT.getSizeInBits() != 256 || NumElts != 8)
3803     return false;
3804
3805   // The mask on the high lane should be the same as the low. Actually,
3806   // they can differ if any of the corresponding index in a lane is undef
3807   // and the other stays in range.
3808   int LaneSize = NumElts/NumLanes;
3809   for (int i = 0; i < LaneSize; ++i) {
3810     int HighElt = i+LaneSize;
3811     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3812     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3813
3814     if (!HighValid || !LowValid)
3815       return false;
3816     if (Mask[i] < 0 || Mask[HighElt] < 0)
3817       continue;
3818     if (Mask[HighElt]-Mask[i] != LaneSize)
3819       return false;
3820   }
3821
3822   return true;
3823 }
3824
3825 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3826 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3827 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3828   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3829   EVT VT = SVOp->getValueType(0);
3830
3831   int NumElts = VT.getVectorNumElements();
3832   int NumLanes = VT.getSizeInBits()/128;
3833   int LaneSize = NumElts/NumLanes;
3834
3835   // Although the mask is equal for both lanes do it twice to get the cases
3836   // where a mask will match because the same mask element is undef on the
3837   // first half but valid on the second. This would get pathological cases
3838   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3839   unsigned Mask = 0;
3840   for (int l = 0; l < NumLanes; ++l) {
3841     for (int i = 0; i < LaneSize; ++i) {
3842       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3843       if (MaskElt < 0)
3844         continue;
3845       if (MaskElt >= LaneSize)
3846         MaskElt -= LaneSize;
3847       Mask |= MaskElt << (i*2);
3848     }
3849   }
3850
3851   return Mask;
3852 }
3853
3854 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3855 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3856 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3857   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3858   EVT VT = SVOp->getValueType(0);
3859
3860   int NumElts = VT.getVectorNumElements();
3861   int NumLanes = VT.getSizeInBits()/128;
3862
3863   unsigned Mask = 0;
3864   int LaneSize = NumElts/NumLanes;
3865   for (int l = 0; l < NumLanes; ++l)
3866     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3867       int MaskElt = SVOp->getMaskElt(i);
3868       if (MaskElt < 0)
3869         continue;
3870       Mask |= (MaskElt-l*LaneSize) << i;
3871     }
3872
3873   return Mask;
3874 }
3875
3876 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3877 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3878 /// element of vector 2 and the other elements to come from vector 1 in order.
3879 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3880                                bool V2IsSplat = false, bool V2IsUndef = false) {
3881   int NumOps = VT.getVectorNumElements();
3882   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3883     return false;
3884
3885   if (!isUndefOrEqual(Mask[0], 0))
3886     return false;
3887
3888   for (int i = 1; i < NumOps; ++i)
3889     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3890           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3891           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3892       return false;
3893
3894   return true;
3895 }
3896
3897 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3898                            bool V2IsUndef = false) {
3899   SmallVector<int, 8> M;
3900   N->getMask(M);
3901   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3902 }
3903
3904 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3905 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3906 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3907 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3908                          const X86Subtarget *Subtarget) {
3909   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3910     return false;
3911
3912   // The second vector must be undef
3913   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3914     return false;
3915
3916   EVT VT = N->getValueType(0);
3917   unsigned NumElems = VT.getVectorNumElements();
3918
3919   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3920       (VT.getSizeInBits() == 256 && NumElems != 8))
3921     return false;
3922
3923   // "i+1" is the value the indexed mask element must have
3924   for (unsigned i = 0; i < NumElems; i += 2)
3925     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3926         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3927       return false;
3928
3929   return true;
3930 }
3931
3932 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3934 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3935 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
3936                          const X86Subtarget *Subtarget) {
3937   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3938     return false;
3939
3940   // The second vector must be undef
3941   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3942     return false;
3943
3944   EVT VT = N->getValueType(0);
3945   unsigned NumElems = VT.getVectorNumElements();
3946
3947   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3948       (VT.getSizeInBits() == 256 && NumElems != 8))
3949     return false;
3950
3951   // "i" is the value the indexed mask element must have
3952   for (unsigned i = 0; i < NumElems; i += 2)
3953     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
3954         !isUndefOrEqual(N->getMaskElt(i+1), i))
3955       return false;
3956
3957   return true;
3958 }
3959
3960 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3961 /// specifies a shuffle of elements that is suitable for input to 256-bit
3962 /// version of MOVDDUP.
3963 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
3964                            const X86Subtarget *Subtarget) {
3965   EVT VT = N->getValueType(0);
3966   int NumElts = VT.getVectorNumElements();
3967   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
3968
3969   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
3970       !V2IsUndef || NumElts != 4)
3971     return false;
3972
3973   for (int i = 0; i != NumElts/2; ++i)
3974     if (!isUndefOrEqual(N->getMaskElt(i), 0))
3975       return false;
3976   for (int i = NumElts/2; i != NumElts; ++i)
3977     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
3978       return false;
3979   return true;
3980 }
3981
3982 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3983 /// specifies a shuffle of elements that is suitable for input to 128-bit
3984 /// version of MOVDDUP.
3985 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3986   EVT VT = N->getValueType(0);
3987
3988   if (VT.getSizeInBits() != 128)
3989     return false;
3990
3991   int e = VT.getVectorNumElements() / 2;
3992   for (int i = 0; i < e; ++i)
3993     if (!isUndefOrEqual(N->getMaskElt(i), i))
3994       return false;
3995   for (int i = 0; i < e; ++i)
3996     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3997       return false;
3998   return true;
3999 }
4000
4001 /// isVEXTRACTF128Index - Return true if the specified
4002 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4003 /// suitable for input to VEXTRACTF128.
4004 bool X86::isVEXTRACTF128Index(SDNode *N) {
4005   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4006     return false;
4007
4008   // The index should be aligned on a 128-bit boundary.
4009   uint64_t Index =
4010     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4011
4012   unsigned VL = N->getValueType(0).getVectorNumElements();
4013   unsigned VBits = N->getValueType(0).getSizeInBits();
4014   unsigned ElSize = VBits / VL;
4015   bool Result = (Index * ElSize) % 128 == 0;
4016
4017   return Result;
4018 }
4019
4020 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4021 /// operand specifies a subvector insert that is suitable for input to
4022 /// VINSERTF128.
4023 bool X86::isVINSERTF128Index(SDNode *N) {
4024   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4025     return false;
4026
4027   // The index should be aligned on a 128-bit boundary.
4028   uint64_t Index =
4029     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4030
4031   unsigned VL = N->getValueType(0).getVectorNumElements();
4032   unsigned VBits = N->getValueType(0).getSizeInBits();
4033   unsigned ElSize = VBits / VL;
4034   bool Result = (Index * ElSize) % 128 == 0;
4035
4036   return Result;
4037 }
4038
4039 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4040 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4041 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4042   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4043   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4044
4045   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4046   unsigned Mask = 0;
4047   for (int i = 0; i < NumOperands; ++i) {
4048     int Val = SVOp->getMaskElt(NumOperands-i-1);
4049     if (Val < 0) Val = 0;
4050     if (Val >= NumOperands) Val -= NumOperands;
4051     Mask |= Val;
4052     if (i != NumOperands - 1)
4053       Mask <<= Shift;
4054   }
4055   return Mask;
4056 }
4057
4058 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4059 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4060 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4061   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4062   unsigned Mask = 0;
4063   // 8 nodes, but we only care about the last 4.
4064   for (unsigned i = 7; i >= 4; --i) {
4065     int Val = SVOp->getMaskElt(i);
4066     if (Val >= 0)
4067       Mask |= (Val - 4);
4068     if (i != 4)
4069       Mask <<= 2;
4070   }
4071   return Mask;
4072 }
4073
4074 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4075 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4076 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4077   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4078   unsigned Mask = 0;
4079   // 8 nodes, but we only care about the first 4.
4080   for (int i = 3; i >= 0; --i) {
4081     int Val = SVOp->getMaskElt(i);
4082     if (Val >= 0)
4083       Mask |= Val;
4084     if (i != 0)
4085       Mask <<= 2;
4086   }
4087   return Mask;
4088 }
4089
4090 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4091 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4092 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4093   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4094   EVT VVT = N->getValueType(0);
4095   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4096   int Val = 0;
4097
4098   unsigned i, e;
4099   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4100     Val = SVOp->getMaskElt(i);
4101     if (Val >= 0)
4102       break;
4103   }
4104   assert(Val - i > 0 && "PALIGNR imm should be positive");
4105   return (Val - i) * EltSize;
4106 }
4107
4108 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4109 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4110 /// instructions.
4111 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4112   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4113     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4114
4115   uint64_t Index =
4116     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4117
4118   EVT VecVT = N->getOperand(0).getValueType();
4119   EVT ElVT = VecVT.getVectorElementType();
4120
4121   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4122   return Index / NumElemsPerChunk;
4123 }
4124
4125 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4126 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4127 /// instructions.
4128 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4129   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4130     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4131
4132   uint64_t Index =
4133     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4134
4135   EVT VecVT = N->getValueType(0);
4136   EVT ElVT = VecVT.getVectorElementType();
4137
4138   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4139   return Index / NumElemsPerChunk;
4140 }
4141
4142 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4143 /// constant +0.0.
4144 bool X86::isZeroNode(SDValue Elt) {
4145   return ((isa<ConstantSDNode>(Elt) &&
4146            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4147           (isa<ConstantFPSDNode>(Elt) &&
4148            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4149 }
4150
4151 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4152 /// their permute mask.
4153 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4154                                     SelectionDAG &DAG) {
4155   EVT VT = SVOp->getValueType(0);
4156   unsigned NumElems = VT.getVectorNumElements();
4157   SmallVector<int, 8> MaskVec;
4158
4159   for (unsigned i = 0; i != NumElems; ++i) {
4160     int idx = SVOp->getMaskElt(i);
4161     if (idx < 0)
4162       MaskVec.push_back(idx);
4163     else if (idx < (int)NumElems)
4164       MaskVec.push_back(idx + NumElems);
4165     else
4166       MaskVec.push_back(idx - NumElems);
4167   }
4168   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4169                               SVOp->getOperand(0), &MaskVec[0]);
4170 }
4171
4172 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4173 /// the two vector operands have swapped position.
4174 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4175   unsigned NumElems = VT.getVectorNumElements();
4176   for (unsigned i = 0; i != NumElems; ++i) {
4177     int idx = Mask[i];
4178     if (idx < 0)
4179       continue;
4180     else if (idx < (int)NumElems)
4181       Mask[i] = idx + NumElems;
4182     else
4183       Mask[i] = idx - NumElems;
4184   }
4185 }
4186
4187 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4188 /// match movhlps. The lower half elements should come from upper half of
4189 /// V1 (and in order), and the upper half elements should come from the upper
4190 /// half of V2 (and in order).
4191 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4192   EVT VT = Op->getValueType(0);
4193   if (VT.getSizeInBits() != 128)
4194     return false;
4195   if (VT.getVectorNumElements() != 4)
4196     return false;
4197   for (unsigned i = 0, e = 2; i != e; ++i)
4198     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4199       return false;
4200   for (unsigned i = 2; i != 4; ++i)
4201     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4202       return false;
4203   return true;
4204 }
4205
4206 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4207 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4208 /// required.
4209 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4210   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4211     return false;
4212   N = N->getOperand(0).getNode();
4213   if (!ISD::isNON_EXTLoad(N))
4214     return false;
4215   if (LD)
4216     *LD = cast<LoadSDNode>(N);
4217   return true;
4218 }
4219
4220 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4221 /// match movlp{s|d}. The lower half elements should come from lower half of
4222 /// V1 (and in order), and the upper half elements should come from the upper
4223 /// half of V2 (and in order). And since V1 will become the source of the
4224 /// MOVLP, it must be either a vector load or a scalar load to vector.
4225 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4226                                ShuffleVectorSDNode *Op) {
4227   EVT VT = Op->getValueType(0);
4228   if (VT.getSizeInBits() != 128)
4229     return false;
4230
4231   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4232     return false;
4233   // Is V2 is a vector load, don't do this transformation. We will try to use
4234   // load folding shufps op.
4235   if (ISD::isNON_EXTLoad(V2))
4236     return false;
4237
4238   unsigned NumElems = VT.getVectorNumElements();
4239
4240   if (NumElems != 2 && NumElems != 4)
4241     return false;
4242   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4243     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4244       return false;
4245   for (unsigned i = NumElems/2; i != NumElems; ++i)
4246     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4247       return false;
4248   return true;
4249 }
4250
4251 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4252 /// all the same.
4253 static bool isSplatVector(SDNode *N) {
4254   if (N->getOpcode() != ISD::BUILD_VECTOR)
4255     return false;
4256
4257   SDValue SplatValue = N->getOperand(0);
4258   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4259     if (N->getOperand(i) != SplatValue)
4260       return false;
4261   return true;
4262 }
4263
4264 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4265 /// to an zero vector.
4266 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4267 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4268   SDValue V1 = N->getOperand(0);
4269   SDValue V2 = N->getOperand(1);
4270   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4271   for (unsigned i = 0; i != NumElems; ++i) {
4272     int Idx = N->getMaskElt(i);
4273     if (Idx >= (int)NumElems) {
4274       unsigned Opc = V2.getOpcode();
4275       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4276         continue;
4277       if (Opc != ISD::BUILD_VECTOR ||
4278           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4279         return false;
4280     } else if (Idx >= 0) {
4281       unsigned Opc = V1.getOpcode();
4282       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4283         continue;
4284       if (Opc != ISD::BUILD_VECTOR ||
4285           !X86::isZeroNode(V1.getOperand(Idx)))
4286         return false;
4287     }
4288   }
4289   return true;
4290 }
4291
4292 /// getZeroVector - Returns a vector of specified type with all zero elements.
4293 ///
4294 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4295                              DebugLoc dl) {
4296   assert(VT.isVector() && "Expected a vector type");
4297
4298   // Always build SSE zero vectors as <4 x i32> bitcasted
4299   // to their dest type. This ensures they get CSE'd.
4300   SDValue Vec;
4301   if (VT.getSizeInBits() == 128) {  // SSE
4302     if (HasXMMInt) {  // SSE2
4303       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4304       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4305     } else { // SSE1
4306       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4307       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4308     }
4309   } else if (VT.getSizeInBits() == 256) { // AVX
4310     // 256-bit logic and arithmetic instructions in AVX are
4311     // all floating-point, no support for integer ops. Default
4312     // to emitting fp zeroed vectors then.
4313     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4314     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4315     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4316   }
4317   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4318 }
4319
4320 /// getOnesVector - Returns a vector of specified type with all bits set.
4321 /// Always build ones vectors as <4 x i32>. For 256-bit types, use two
4322 /// <4 x i32> inserted in a <8 x i32> appropriately. Then bitcast to their
4323 /// original type, ensuring they get CSE'd.
4324 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4325   assert(VT.isVector() && "Expected a vector type");
4326   assert((VT.is128BitVector() || VT.is256BitVector())
4327          && "Expected a 128-bit or 256-bit vector type");
4328
4329   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4330   SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4331                             Cst, Cst, Cst, Cst);
4332
4333   if (VT.is256BitVector()) {
4334     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4335                               Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4336     Vec = Insert128BitVector(InsV, Vec,
4337                   DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4338   }
4339
4340   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4341 }
4342
4343 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4344 /// that point to V2 points to its first element.
4345 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4346   EVT VT = SVOp->getValueType(0);
4347   unsigned NumElems = VT.getVectorNumElements();
4348
4349   bool Changed = false;
4350   SmallVector<int, 8> MaskVec;
4351   SVOp->getMask(MaskVec);
4352
4353   for (unsigned i = 0; i != NumElems; ++i) {
4354     if (MaskVec[i] > (int)NumElems) {
4355       MaskVec[i] = NumElems;
4356       Changed = true;
4357     }
4358   }
4359   if (Changed)
4360     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4361                                 SVOp->getOperand(1), &MaskVec[0]);
4362   return SDValue(SVOp, 0);
4363 }
4364
4365 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4366 /// operation of specified width.
4367 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4368                        SDValue V2) {
4369   unsigned NumElems = VT.getVectorNumElements();
4370   SmallVector<int, 8> Mask;
4371   Mask.push_back(NumElems);
4372   for (unsigned i = 1; i != NumElems; ++i)
4373     Mask.push_back(i);
4374   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4375 }
4376
4377 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4378 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4379                           SDValue V2) {
4380   unsigned NumElems = VT.getVectorNumElements();
4381   SmallVector<int, 8> Mask;
4382   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4383     Mask.push_back(i);
4384     Mask.push_back(i + NumElems);
4385   }
4386   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4387 }
4388
4389 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4390 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4391                           SDValue V2) {
4392   unsigned NumElems = VT.getVectorNumElements();
4393   unsigned Half = NumElems/2;
4394   SmallVector<int, 8> Mask;
4395   for (unsigned i = 0; i != Half; ++i) {
4396     Mask.push_back(i + Half);
4397     Mask.push_back(i + NumElems + Half);
4398   }
4399   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4400 }
4401
4402 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4403 // a generic shuffle instruction because the target has no such instructions.
4404 // Generate shuffles which repeat i16 and i8 several times until they can be
4405 // represented by v4f32 and then be manipulated by target suported shuffles.
4406 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4407   EVT VT = V.getValueType();
4408   int NumElems = VT.getVectorNumElements();
4409   DebugLoc dl = V.getDebugLoc();
4410
4411   while (NumElems > 4) {
4412     if (EltNo < NumElems/2) {
4413       V = getUnpackl(DAG, dl, VT, V, V);
4414     } else {
4415       V = getUnpackh(DAG, dl, VT, V, V);
4416       EltNo -= NumElems/2;
4417     }
4418     NumElems >>= 1;
4419   }
4420   return V;
4421 }
4422
4423 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4424 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4425   EVT VT = V.getValueType();
4426   DebugLoc dl = V.getDebugLoc();
4427   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4428          && "Vector size not supported");
4429
4430   if (VT.getSizeInBits() == 128) {
4431     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4432     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4433     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4434                              &SplatMask[0]);
4435   } else {
4436     // To use VPERMILPS to splat scalars, the second half of indicies must
4437     // refer to the higher part, which is a duplication of the lower one,
4438     // because VPERMILPS can only handle in-lane permutations.
4439     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4440                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4441
4442     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4443     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4444                              &SplatMask[0]);
4445   }
4446
4447   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4448 }
4449
4450 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4451 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4452   EVT SrcVT = SV->getValueType(0);
4453   SDValue V1 = SV->getOperand(0);
4454   DebugLoc dl = SV->getDebugLoc();
4455
4456   int EltNo = SV->getSplatIndex();
4457   int NumElems = SrcVT.getVectorNumElements();
4458   unsigned Size = SrcVT.getSizeInBits();
4459
4460   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4461           "Unknown how to promote splat for type");
4462
4463   // Extract the 128-bit part containing the splat element and update
4464   // the splat element index when it refers to the higher register.
4465   if (Size == 256) {
4466     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4467     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4468     if (Idx > 0)
4469       EltNo -= NumElems/2;
4470   }
4471
4472   // All i16 and i8 vector types can't be used directly by a generic shuffle
4473   // instruction because the target has no such instruction. Generate shuffles
4474   // which repeat i16 and i8 several times until they fit in i32, and then can
4475   // be manipulated by target suported shuffles.
4476   EVT EltVT = SrcVT.getVectorElementType();
4477   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4478     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4479
4480   // Recreate the 256-bit vector and place the same 128-bit vector
4481   // into the low and high part. This is necessary because we want
4482   // to use VPERM* to shuffle the vectors
4483   if (Size == 256) {
4484     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4485                          DAG.getConstant(0, MVT::i32), DAG, dl);
4486     V1 = Insert128BitVector(InsV, V1,
4487                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4488   }
4489
4490   return getLegalSplat(DAG, V1, EltNo);
4491 }
4492
4493 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4494 /// vector of zero or undef vector.  This produces a shuffle where the low
4495 /// element of V2 is swizzled into the zero/undef vector, landing at element
4496 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4497 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4498                                            bool isZero, bool HasXMMInt,
4499                                            SelectionDAG &DAG) {
4500   EVT VT = V2.getValueType();
4501   SDValue V1 = isZero
4502     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4503   unsigned NumElems = VT.getVectorNumElements();
4504   SmallVector<int, 16> MaskVec;
4505   for (unsigned i = 0; i != NumElems; ++i)
4506     // If this is the insertion idx, put the low elt of V2 here.
4507     MaskVec.push_back(i == Idx ? NumElems : i);
4508   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4509 }
4510
4511 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4512 /// element of the result of the vector shuffle.
4513 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4514                                    unsigned Depth) {
4515   if (Depth == 6)
4516     return SDValue();  // Limit search depth.
4517
4518   SDValue V = SDValue(N, 0);
4519   EVT VT = V.getValueType();
4520   unsigned Opcode = V.getOpcode();
4521
4522   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4523   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4524     Index = SV->getMaskElt(Index);
4525
4526     if (Index < 0)
4527       return DAG.getUNDEF(VT.getVectorElementType());
4528
4529     int NumElems = VT.getVectorNumElements();
4530     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4531     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4532   }
4533
4534   // Recurse into target specific vector shuffles to find scalars.
4535   if (isTargetShuffle(Opcode)) {
4536     int NumElems = VT.getVectorNumElements();
4537     SmallVector<unsigned, 16> ShuffleMask;
4538     SDValue ImmN;
4539
4540     switch(Opcode) {
4541     case X86ISD::SHUFPS:
4542     case X86ISD::SHUFPD:
4543       ImmN = N->getOperand(N->getNumOperands()-1);
4544       DecodeSHUFPSMask(NumElems,
4545                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4546                        ShuffleMask);
4547       break;
4548     case X86ISD::PUNPCKHBW:
4549     case X86ISD::PUNPCKHWD:
4550     case X86ISD::PUNPCKHDQ:
4551     case X86ISD::PUNPCKHQDQ:
4552       DecodePUNPCKHMask(NumElems, ShuffleMask);
4553       break;
4554     case X86ISD::UNPCKHPS:
4555     case X86ISD::UNPCKHPD:
4556     case X86ISD::VUNPCKHPSY:
4557     case X86ISD::VUNPCKHPDY:
4558       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4559       break;
4560     case X86ISD::PUNPCKLBW:
4561     case X86ISD::PUNPCKLWD:
4562     case X86ISD::PUNPCKLDQ:
4563     case X86ISD::PUNPCKLQDQ:
4564       DecodePUNPCKLMask(VT, ShuffleMask);
4565       break;
4566     case X86ISD::UNPCKLPS:
4567     case X86ISD::UNPCKLPD:
4568     case X86ISD::VUNPCKLPSY:
4569     case X86ISD::VUNPCKLPDY:
4570       DecodeUNPCKLPMask(VT, ShuffleMask);
4571       break;
4572     case X86ISD::MOVHLPS:
4573       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4574       break;
4575     case X86ISD::MOVLHPS:
4576       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4577       break;
4578     case X86ISD::PSHUFD:
4579       ImmN = N->getOperand(N->getNumOperands()-1);
4580       DecodePSHUFMask(NumElems,
4581                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4582                       ShuffleMask);
4583       break;
4584     case X86ISD::PSHUFHW:
4585       ImmN = N->getOperand(N->getNumOperands()-1);
4586       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4587                         ShuffleMask);
4588       break;
4589     case X86ISD::PSHUFLW:
4590       ImmN = N->getOperand(N->getNumOperands()-1);
4591       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4592                         ShuffleMask);
4593       break;
4594     case X86ISD::MOVSS:
4595     case X86ISD::MOVSD: {
4596       // The index 0 always comes from the first element of the second source,
4597       // this is why MOVSS and MOVSD are used in the first place. The other
4598       // elements come from the other positions of the first source vector.
4599       unsigned OpNum = (Index == 0) ? 1 : 0;
4600       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4601                                  Depth+1);
4602     }
4603     case X86ISD::VPERMILPS:
4604       ImmN = N->getOperand(N->getNumOperands()-1);
4605       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4606                         ShuffleMask);
4607       break;
4608     case X86ISD::VPERMILPSY:
4609       ImmN = N->getOperand(N->getNumOperands()-1);
4610       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4611                         ShuffleMask);
4612       break;
4613     case X86ISD::VPERMILPD:
4614       ImmN = N->getOperand(N->getNumOperands()-1);
4615       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4616                         ShuffleMask);
4617       break;
4618     case X86ISD::VPERMILPDY:
4619       ImmN = N->getOperand(N->getNumOperands()-1);
4620       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4621                         ShuffleMask);
4622       break;
4623     case X86ISD::VPERM2F128:
4624       ImmN = N->getOperand(N->getNumOperands()-1);
4625       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4626                            ShuffleMask);
4627       break;
4628     case X86ISD::MOVDDUP:
4629     case X86ISD::MOVLHPD:
4630     case X86ISD::MOVLPD:
4631     case X86ISD::MOVLPS:
4632     case X86ISD::MOVSHDUP:
4633     case X86ISD::MOVSLDUP:
4634     case X86ISD::PALIGN:
4635       return SDValue(); // Not yet implemented.
4636     default:
4637       assert(0 && "unknown target shuffle node");
4638       return SDValue();
4639     }
4640
4641     Index = ShuffleMask[Index];
4642     if (Index < 0)
4643       return DAG.getUNDEF(VT.getVectorElementType());
4644
4645     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4646     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4647                                Depth+1);
4648   }
4649
4650   // Actual nodes that may contain scalar elements
4651   if (Opcode == ISD::BITCAST) {
4652     V = V.getOperand(0);
4653     EVT SrcVT = V.getValueType();
4654     unsigned NumElems = VT.getVectorNumElements();
4655
4656     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4657       return SDValue();
4658   }
4659
4660   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4661     return (Index == 0) ? V.getOperand(0)
4662                           : DAG.getUNDEF(VT.getVectorElementType());
4663
4664   if (V.getOpcode() == ISD::BUILD_VECTOR)
4665     return V.getOperand(Index);
4666
4667   return SDValue();
4668 }
4669
4670 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4671 /// shuffle operation which come from a consecutively from a zero. The
4672 /// search can start in two different directions, from left or right.
4673 static
4674 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4675                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4676   int i = 0;
4677
4678   while (i < NumElems) {
4679     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4680     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4681     if (!(Elt.getNode() &&
4682          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4683       break;
4684     ++i;
4685   }
4686
4687   return i;
4688 }
4689
4690 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4691 /// MaskE correspond consecutively to elements from one of the vector operands,
4692 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4693 static
4694 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4695                               int OpIdx, int NumElems, unsigned &OpNum) {
4696   bool SeenV1 = false;
4697   bool SeenV2 = false;
4698
4699   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4700     int Idx = SVOp->getMaskElt(i);
4701     // Ignore undef indicies
4702     if (Idx < 0)
4703       continue;
4704
4705     if (Idx < NumElems)
4706       SeenV1 = true;
4707     else
4708       SeenV2 = true;
4709
4710     // Only accept consecutive elements from the same vector
4711     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4712       return false;
4713   }
4714
4715   OpNum = SeenV1 ? 0 : 1;
4716   return true;
4717 }
4718
4719 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4720 /// logical left shift of a vector.
4721 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4722                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4723   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4724   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4725               false /* check zeros from right */, DAG);
4726   unsigned OpSrc;
4727
4728   if (!NumZeros)
4729     return false;
4730
4731   // Considering the elements in the mask that are not consecutive zeros,
4732   // check if they consecutively come from only one of the source vectors.
4733   //
4734   //               V1 = {X, A, B, C}     0
4735   //                         \  \  \    /
4736   //   vector_shuffle V1, V2 <1, 2, 3, X>
4737   //
4738   if (!isShuffleMaskConsecutive(SVOp,
4739             0,                   // Mask Start Index
4740             NumElems-NumZeros-1, // Mask End Index
4741             NumZeros,            // Where to start looking in the src vector
4742             NumElems,            // Number of elements in vector
4743             OpSrc))              // Which source operand ?
4744     return false;
4745
4746   isLeft = false;
4747   ShAmt = NumZeros;
4748   ShVal = SVOp->getOperand(OpSrc);
4749   return true;
4750 }
4751
4752 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4753 /// logical left shift of a vector.
4754 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4755                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4756   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4757   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4758               true /* check zeros from left */, DAG);
4759   unsigned OpSrc;
4760
4761   if (!NumZeros)
4762     return false;
4763
4764   // Considering the elements in the mask that are not consecutive zeros,
4765   // check if they consecutively come from only one of the source vectors.
4766   //
4767   //                           0    { A, B, X, X } = V2
4768   //                          / \    /  /
4769   //   vector_shuffle V1, V2 <X, X, 4, 5>
4770   //
4771   if (!isShuffleMaskConsecutive(SVOp,
4772             NumZeros,     // Mask Start Index
4773             NumElems-1,   // Mask End Index
4774             0,            // Where to start looking in the src vector
4775             NumElems,     // Number of elements in vector
4776             OpSrc))       // Which source operand ?
4777     return false;
4778
4779   isLeft = true;
4780   ShAmt = NumZeros;
4781   ShVal = SVOp->getOperand(OpSrc);
4782   return true;
4783 }
4784
4785 /// isVectorShift - Returns true if the shuffle can be implemented as a
4786 /// logical left or right shift of a vector.
4787 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4788                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4789   // Although the logic below support any bitwidth size, there are no
4790   // shift instructions which handle more than 128-bit vectors.
4791   if (SVOp->getValueType(0).getSizeInBits() > 128)
4792     return false;
4793
4794   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4795       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4796     return true;
4797
4798   return false;
4799 }
4800
4801 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4802 ///
4803 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4804                                        unsigned NumNonZero, unsigned NumZero,
4805                                        SelectionDAG &DAG,
4806                                        const TargetLowering &TLI) {
4807   if (NumNonZero > 8)
4808     return SDValue();
4809
4810   DebugLoc dl = Op.getDebugLoc();
4811   SDValue V(0, 0);
4812   bool First = true;
4813   for (unsigned i = 0; i < 16; ++i) {
4814     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4815     if (ThisIsNonZero && First) {
4816       if (NumZero)
4817         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4818       else
4819         V = DAG.getUNDEF(MVT::v8i16);
4820       First = false;
4821     }
4822
4823     if ((i & 1) != 0) {
4824       SDValue ThisElt(0, 0), LastElt(0, 0);
4825       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4826       if (LastIsNonZero) {
4827         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4828                               MVT::i16, Op.getOperand(i-1));
4829       }
4830       if (ThisIsNonZero) {
4831         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4832         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4833                               ThisElt, DAG.getConstant(8, MVT::i8));
4834         if (LastIsNonZero)
4835           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4836       } else
4837         ThisElt = LastElt;
4838
4839       if (ThisElt.getNode())
4840         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4841                         DAG.getIntPtrConstant(i/2));
4842     }
4843   }
4844
4845   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4846 }
4847
4848 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4849 ///
4850 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4851                                      unsigned NumNonZero, unsigned NumZero,
4852                                      SelectionDAG &DAG,
4853                                      const TargetLowering &TLI) {
4854   if (NumNonZero > 4)
4855     return SDValue();
4856
4857   DebugLoc dl = Op.getDebugLoc();
4858   SDValue V(0, 0);
4859   bool First = true;
4860   for (unsigned i = 0; i < 8; ++i) {
4861     bool isNonZero = (NonZeros & (1 << i)) != 0;
4862     if (isNonZero) {
4863       if (First) {
4864         if (NumZero)
4865           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4866         else
4867           V = DAG.getUNDEF(MVT::v8i16);
4868         First = false;
4869       }
4870       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4871                       MVT::v8i16, V, Op.getOperand(i),
4872                       DAG.getIntPtrConstant(i));
4873     }
4874   }
4875
4876   return V;
4877 }
4878
4879 /// getVShift - Return a vector logical shift node.
4880 ///
4881 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4882                          unsigned NumBits, SelectionDAG &DAG,
4883                          const TargetLowering &TLI, DebugLoc dl) {
4884   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4885   EVT ShVT = MVT::v2i64;
4886   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4887   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4888   return DAG.getNode(ISD::BITCAST, dl, VT,
4889                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4890                              DAG.getConstant(NumBits,
4891                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4892 }
4893
4894 SDValue
4895 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4896                                           SelectionDAG &DAG) const {
4897
4898   // Check if the scalar load can be widened into a vector load. And if
4899   // the address is "base + cst" see if the cst can be "absorbed" into
4900   // the shuffle mask.
4901   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4902     SDValue Ptr = LD->getBasePtr();
4903     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4904       return SDValue();
4905     EVT PVT = LD->getValueType(0);
4906     if (PVT != MVT::i32 && PVT != MVT::f32)
4907       return SDValue();
4908
4909     int FI = -1;
4910     int64_t Offset = 0;
4911     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4912       FI = FINode->getIndex();
4913       Offset = 0;
4914     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4915                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4916       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4917       Offset = Ptr.getConstantOperandVal(1);
4918       Ptr = Ptr.getOperand(0);
4919     } else {
4920       return SDValue();
4921     }
4922
4923     // FIXME: 256-bit vector instructions don't require a strict alignment,
4924     // improve this code to support it better.
4925     unsigned RequiredAlign = VT.getSizeInBits()/8;
4926     SDValue Chain = LD->getChain();
4927     // Make sure the stack object alignment is at least 16 or 32.
4928     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4929     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4930       if (MFI->isFixedObjectIndex(FI)) {
4931         // Can't change the alignment. FIXME: It's possible to compute
4932         // the exact stack offset and reference FI + adjust offset instead.
4933         // If someone *really* cares about this. That's the way to implement it.
4934         return SDValue();
4935       } else {
4936         MFI->setObjectAlignment(FI, RequiredAlign);
4937       }
4938     }
4939
4940     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4941     // Ptr + (Offset & ~15).
4942     if (Offset < 0)
4943       return SDValue();
4944     if ((Offset % RequiredAlign) & 3)
4945       return SDValue();
4946     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4947     if (StartOffset)
4948       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4949                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4950
4951     int EltNo = (Offset - StartOffset) >> 2;
4952     int NumElems = VT.getVectorNumElements();
4953
4954     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
4955     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4956     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4957                              LD->getPointerInfo().getWithOffset(StartOffset),
4958                              false, false, 0);
4959
4960     // Canonicalize it to a v4i32 or v8i32 shuffle.
4961     SmallVector<int, 8> Mask;
4962     for (int i = 0; i < NumElems; ++i)
4963       Mask.push_back(EltNo);
4964
4965     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
4966     return DAG.getNode(ISD::BITCAST, dl, NVT,
4967                        DAG.getVectorShuffle(CanonVT, dl, V1,
4968                                             DAG.getUNDEF(CanonVT),&Mask[0]));
4969   }
4970
4971   return SDValue();
4972 }
4973
4974 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4975 /// vector of type 'VT', see if the elements can be replaced by a single large
4976 /// load which has the same value as a build_vector whose operands are 'elts'.
4977 ///
4978 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4979 ///
4980 /// FIXME: we'd also like to handle the case where the last elements are zero
4981 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4982 /// There's even a handy isZeroNode for that purpose.
4983 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4984                                         DebugLoc &DL, SelectionDAG &DAG) {
4985   EVT EltVT = VT.getVectorElementType();
4986   unsigned NumElems = Elts.size();
4987
4988   LoadSDNode *LDBase = NULL;
4989   unsigned LastLoadedElt = -1U;
4990
4991   // For each element in the initializer, see if we've found a load or an undef.
4992   // If we don't find an initial load element, or later load elements are
4993   // non-consecutive, bail out.
4994   for (unsigned i = 0; i < NumElems; ++i) {
4995     SDValue Elt = Elts[i];
4996
4997     if (!Elt.getNode() ||
4998         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4999       return SDValue();
5000     if (!LDBase) {
5001       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5002         return SDValue();
5003       LDBase = cast<LoadSDNode>(Elt.getNode());
5004       LastLoadedElt = i;
5005       continue;
5006     }
5007     if (Elt.getOpcode() == ISD::UNDEF)
5008       continue;
5009
5010     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5011     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5012       return SDValue();
5013     LastLoadedElt = i;
5014   }
5015
5016   // If we have found an entire vector of loads and undefs, then return a large
5017   // load of the entire vector width starting at the base pointer.  If we found
5018   // consecutive loads for the low half, generate a vzext_load node.
5019   if (LastLoadedElt == NumElems - 1) {
5020     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5021       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5022                          LDBase->getPointerInfo(),
5023                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
5024     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5025                        LDBase->getPointerInfo(),
5026                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5027                        LDBase->getAlignment());
5028   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5029              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5030     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5031     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5032     SDValue ResNode =
5033         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5034                                 LDBase->getPointerInfo(),
5035                                 LDBase->getAlignment(),
5036                                 false/*isVolatile*/, true/*ReadMem*/,
5037                                 false/*WriteMem*/);
5038     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5039   }
5040   return SDValue();
5041 }
5042
5043 SDValue
5044 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5045   DebugLoc dl = Op.getDebugLoc();
5046
5047   EVT VT = Op.getValueType();
5048   EVT ExtVT = VT.getVectorElementType();
5049   unsigned NumElems = Op.getNumOperands();
5050
5051   // Vectors containing all zeros can be matched by pxor and xorps later
5052   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5053     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5054     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5055     if (Op.getValueType() == MVT::v4i32 ||
5056         Op.getValueType() == MVT::v8i32)
5057       return Op;
5058
5059     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5060   }
5061
5062   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5063   // vectors or broken into v4i32 operations on 256-bit vectors.
5064   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5065     if (Op.getValueType() == MVT::v4i32)
5066       return Op;
5067
5068     return getOnesVector(Op.getValueType(), DAG, dl);
5069   }
5070
5071   unsigned EVTBits = ExtVT.getSizeInBits();
5072
5073   unsigned NumZero  = 0;
5074   unsigned NumNonZero = 0;
5075   unsigned NonZeros = 0;
5076   bool IsAllConstants = true;
5077   SmallSet<SDValue, 8> Values;
5078   for (unsigned i = 0; i < NumElems; ++i) {
5079     SDValue Elt = Op.getOperand(i);
5080     if (Elt.getOpcode() == ISD::UNDEF)
5081       continue;
5082     Values.insert(Elt);
5083     if (Elt.getOpcode() != ISD::Constant &&
5084         Elt.getOpcode() != ISD::ConstantFP)
5085       IsAllConstants = false;
5086     if (X86::isZeroNode(Elt))
5087       NumZero++;
5088     else {
5089       NonZeros |= (1 << i);
5090       NumNonZero++;
5091     }
5092   }
5093
5094   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5095   if (NumNonZero == 0)
5096     return DAG.getUNDEF(VT);
5097
5098   // Special case for single non-zero, non-undef, element.
5099   if (NumNonZero == 1) {
5100     unsigned Idx = CountTrailingZeros_32(NonZeros);
5101     SDValue Item = Op.getOperand(Idx);
5102
5103     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5104     // the value are obviously zero, truncate the value to i32 and do the
5105     // insertion that way.  Only do this if the value is non-constant or if the
5106     // value is a constant being inserted into element 0.  It is cheaper to do
5107     // a constant pool load than it is to do a movd + shuffle.
5108     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5109         (!IsAllConstants || Idx == 0)) {
5110       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5111         // Handle SSE only.
5112         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5113         EVT VecVT = MVT::v4i32;
5114         unsigned VecElts = 4;
5115
5116         // Truncate the value (which may itself be a constant) to i32, and
5117         // convert it to a vector with movd (S2V+shuffle to zero extend).
5118         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5119         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5120         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5121                                            Subtarget->hasXMMInt(), DAG);
5122
5123         // Now we have our 32-bit value zero extended in the low element of
5124         // a vector.  If Idx != 0, swizzle it into place.
5125         if (Idx != 0) {
5126           SmallVector<int, 4> Mask;
5127           Mask.push_back(Idx);
5128           for (unsigned i = 1; i != VecElts; ++i)
5129             Mask.push_back(i);
5130           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5131                                       DAG.getUNDEF(Item.getValueType()),
5132                                       &Mask[0]);
5133         }
5134         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5135       }
5136     }
5137
5138     // If we have a constant or non-constant insertion into the low element of
5139     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5140     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5141     // depending on what the source datatype is.
5142     if (Idx == 0) {
5143       if (NumZero == 0) {
5144         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5145       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5146           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5147         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5148         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5149         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5150                                            DAG);
5151       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5152         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5153         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5154         EVT MiddleVT = MVT::v4i32;
5155         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5156         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5157                                            Subtarget->hasXMMInt(), DAG);
5158         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5159       }
5160     }
5161
5162     // Is it a vector logical left shift?
5163     if (NumElems == 2 && Idx == 1 &&
5164         X86::isZeroNode(Op.getOperand(0)) &&
5165         !X86::isZeroNode(Op.getOperand(1))) {
5166       unsigned NumBits = VT.getSizeInBits();
5167       return getVShift(true, VT,
5168                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5169                                    VT, Op.getOperand(1)),
5170                        NumBits/2, DAG, *this, dl);
5171     }
5172
5173     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5174       return SDValue();
5175
5176     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5177     // is a non-constant being inserted into an element other than the low one,
5178     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5179     // movd/movss) to move this into the low element, then shuffle it into
5180     // place.
5181     if (EVTBits == 32) {
5182       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5183
5184       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5185       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5186                                          Subtarget->hasXMMInt(), DAG);
5187       SmallVector<int, 8> MaskVec;
5188       for (unsigned i = 0; i < NumElems; i++)
5189         MaskVec.push_back(i == Idx ? 0 : 1);
5190       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5191     }
5192   }
5193
5194   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5195   if (Values.size() == 1) {
5196     if (EVTBits == 32) {
5197       // Instead of a shuffle like this:
5198       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5199       // Check if it's possible to issue this instead.
5200       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5201       unsigned Idx = CountTrailingZeros_32(NonZeros);
5202       SDValue Item = Op.getOperand(Idx);
5203       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5204         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5205     }
5206     return SDValue();
5207   }
5208
5209   // A vector full of immediates; various special cases are already
5210   // handled, so this is best done with a single constant-pool load.
5211   if (IsAllConstants)
5212     return SDValue();
5213
5214   // For AVX-length vectors, build the individual 128-bit pieces and use
5215   // shuffles to put them in place.
5216   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5217     SmallVector<SDValue, 32> V;
5218     for (unsigned i = 0; i < NumElems; ++i)
5219       V.push_back(Op.getOperand(i));
5220
5221     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5222
5223     // Build both the lower and upper subvector.
5224     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5225     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5226                                 NumElems/2);
5227
5228     // Recreate the wider vector with the lower and upper part.
5229     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5230                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5231     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5232                               DAG, dl);
5233   }
5234
5235   // Let legalizer expand 2-wide build_vectors.
5236   if (EVTBits == 64) {
5237     if (NumNonZero == 1) {
5238       // One half is zero or undef.
5239       unsigned Idx = CountTrailingZeros_32(NonZeros);
5240       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5241                                  Op.getOperand(Idx));
5242       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5243                                          Subtarget->hasXMMInt(), DAG);
5244     }
5245     return SDValue();
5246   }
5247
5248   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5249   if (EVTBits == 8 && NumElems == 16) {
5250     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5251                                         *this);
5252     if (V.getNode()) return V;
5253   }
5254
5255   if (EVTBits == 16 && NumElems == 8) {
5256     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5257                                       *this);
5258     if (V.getNode()) return V;
5259   }
5260
5261   // If element VT is == 32 bits, turn it into a number of shuffles.
5262   SmallVector<SDValue, 8> V;
5263   V.resize(NumElems);
5264   if (NumElems == 4 && NumZero > 0) {
5265     for (unsigned i = 0; i < 4; ++i) {
5266       bool isZero = !(NonZeros & (1 << i));
5267       if (isZero)
5268         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5269       else
5270         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5271     }
5272
5273     for (unsigned i = 0; i < 2; ++i) {
5274       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5275         default: break;
5276         case 0:
5277           V[i] = V[i*2];  // Must be a zero vector.
5278           break;
5279         case 1:
5280           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5281           break;
5282         case 2:
5283           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5284           break;
5285         case 3:
5286           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5287           break;
5288       }
5289     }
5290
5291     SmallVector<int, 8> MaskVec;
5292     bool Reverse = (NonZeros & 0x3) == 2;
5293     for (unsigned i = 0; i < 2; ++i)
5294       MaskVec.push_back(Reverse ? 1-i : i);
5295     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5296     for (unsigned i = 0; i < 2; ++i)
5297       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5298     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5299   }
5300
5301   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5302     // Check for a build vector of consecutive loads.
5303     for (unsigned i = 0; i < NumElems; ++i)
5304       V[i] = Op.getOperand(i);
5305
5306     // Check for elements which are consecutive loads.
5307     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5308     if (LD.getNode())
5309       return LD;
5310
5311     // For SSE 4.1, use insertps to put the high elements into the low element.
5312     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5313       SDValue Result;
5314       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5315         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5316       else
5317         Result = DAG.getUNDEF(VT);
5318
5319       for (unsigned i = 1; i < NumElems; ++i) {
5320         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5321         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5322                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5323       }
5324       return Result;
5325     }
5326
5327     // Otherwise, expand into a number of unpckl*, start by extending each of
5328     // our (non-undef) elements to the full vector width with the element in the
5329     // bottom slot of the vector (which generates no code for SSE).
5330     for (unsigned i = 0; i < NumElems; ++i) {
5331       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5332         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5333       else
5334         V[i] = DAG.getUNDEF(VT);
5335     }
5336
5337     // Next, we iteratively mix elements, e.g. for v4f32:
5338     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5339     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5340     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5341     unsigned EltStride = NumElems >> 1;
5342     while (EltStride != 0) {
5343       for (unsigned i = 0; i < EltStride; ++i) {
5344         // If V[i+EltStride] is undef and this is the first round of mixing,
5345         // then it is safe to just drop this shuffle: V[i] is already in the
5346         // right place, the one element (since it's the first round) being
5347         // inserted as undef can be dropped.  This isn't safe for successive
5348         // rounds because they will permute elements within both vectors.
5349         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5350             EltStride == NumElems/2)
5351           continue;
5352
5353         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5354       }
5355       EltStride >>= 1;
5356     }
5357     return V[0];
5358   }
5359   return SDValue();
5360 }
5361
5362 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5363 // them in a MMX register.  This is better than doing a stack convert.
5364 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5365   DebugLoc dl = Op.getDebugLoc();
5366   EVT ResVT = Op.getValueType();
5367
5368   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5369          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5370   int Mask[2];
5371   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5372   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5373   InVec = Op.getOperand(1);
5374   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5375     unsigned NumElts = ResVT.getVectorNumElements();
5376     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5377     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5378                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5379   } else {
5380     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5381     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5382     Mask[0] = 0; Mask[1] = 2;
5383     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5384   }
5385   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5386 }
5387
5388 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5389 // to create 256-bit vectors from two other 128-bit ones.
5390 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5391   DebugLoc dl = Op.getDebugLoc();
5392   EVT ResVT = Op.getValueType();
5393
5394   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5395
5396   SDValue V1 = Op.getOperand(0);
5397   SDValue V2 = Op.getOperand(1);
5398   unsigned NumElems = ResVT.getVectorNumElements();
5399
5400   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5401                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5402   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5403                             DAG, dl);
5404 }
5405
5406 SDValue
5407 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5408   EVT ResVT = Op.getValueType();
5409
5410   assert(Op.getNumOperands() == 2);
5411   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5412          "Unsupported CONCAT_VECTORS for value type");
5413
5414   // We support concatenate two MMX registers and place them in a MMX register.
5415   // This is better than doing a stack convert.
5416   if (ResVT.is128BitVector())
5417     return LowerMMXCONCAT_VECTORS(Op, DAG);
5418
5419   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5420   // from two other 128-bit ones.
5421   return LowerAVXCONCAT_VECTORS(Op, DAG);
5422 }
5423
5424 // v8i16 shuffles - Prefer shuffles in the following order:
5425 // 1. [all]   pshuflw, pshufhw, optional move
5426 // 2. [ssse3] 1 x pshufb
5427 // 3. [ssse3] 2 x pshufb + 1 x por
5428 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5429 SDValue
5430 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5431                                             SelectionDAG &DAG) const {
5432   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5433   SDValue V1 = SVOp->getOperand(0);
5434   SDValue V2 = SVOp->getOperand(1);
5435   DebugLoc dl = SVOp->getDebugLoc();
5436   SmallVector<int, 8> MaskVals;
5437
5438   // Determine if more than 1 of the words in each of the low and high quadwords
5439   // of the result come from the same quadword of one of the two inputs.  Undef
5440   // mask values count as coming from any quadword, for better codegen.
5441   SmallVector<unsigned, 4> LoQuad(4);
5442   SmallVector<unsigned, 4> HiQuad(4);
5443   BitVector InputQuads(4);
5444   for (unsigned i = 0; i < 8; ++i) {
5445     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
5446     int EltIdx = SVOp->getMaskElt(i);
5447     MaskVals.push_back(EltIdx);
5448     if (EltIdx < 0) {
5449       ++Quad[0];
5450       ++Quad[1];
5451       ++Quad[2];
5452       ++Quad[3];
5453       continue;
5454     }
5455     ++Quad[EltIdx / 4];
5456     InputQuads.set(EltIdx / 4);
5457   }
5458
5459   int BestLoQuad = -1;
5460   unsigned MaxQuad = 1;
5461   for (unsigned i = 0; i < 4; ++i) {
5462     if (LoQuad[i] > MaxQuad) {
5463       BestLoQuad = i;
5464       MaxQuad = LoQuad[i];
5465     }
5466   }
5467
5468   int BestHiQuad = -1;
5469   MaxQuad = 1;
5470   for (unsigned i = 0; i < 4; ++i) {
5471     if (HiQuad[i] > MaxQuad) {
5472       BestHiQuad = i;
5473       MaxQuad = HiQuad[i];
5474     }
5475   }
5476
5477   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5478   // of the two input vectors, shuffle them into one input vector so only a
5479   // single pshufb instruction is necessary. If There are more than 2 input
5480   // quads, disable the next transformation since it does not help SSSE3.
5481   bool V1Used = InputQuads[0] || InputQuads[1];
5482   bool V2Used = InputQuads[2] || InputQuads[3];
5483   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5484     if (InputQuads.count() == 2 && V1Used && V2Used) {
5485       BestLoQuad = InputQuads.find_first();
5486       BestHiQuad = InputQuads.find_next(BestLoQuad);
5487     }
5488     if (InputQuads.count() > 2) {
5489       BestLoQuad = -1;
5490       BestHiQuad = -1;
5491     }
5492   }
5493
5494   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5495   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5496   // words from all 4 input quadwords.
5497   SDValue NewV;
5498   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5499     SmallVector<int, 8> MaskV;
5500     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5501     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5502     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5503                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5504                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5505     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5506
5507     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5508     // source words for the shuffle, to aid later transformations.
5509     bool AllWordsInNewV = true;
5510     bool InOrder[2] = { true, true };
5511     for (unsigned i = 0; i != 8; ++i) {
5512       int idx = MaskVals[i];
5513       if (idx != (int)i)
5514         InOrder[i/4] = false;
5515       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5516         continue;
5517       AllWordsInNewV = false;
5518       break;
5519     }
5520
5521     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5522     if (AllWordsInNewV) {
5523       for (int i = 0; i != 8; ++i) {
5524         int idx = MaskVals[i];
5525         if (idx < 0)
5526           continue;
5527         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5528         if ((idx != i) && idx < 4)
5529           pshufhw = false;
5530         if ((idx != i) && idx > 3)
5531           pshuflw = false;
5532       }
5533       V1 = NewV;
5534       V2Used = false;
5535       BestLoQuad = 0;
5536       BestHiQuad = 1;
5537     }
5538
5539     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5540     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5541     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5542       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5543       unsigned TargetMask = 0;
5544       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5545                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5546       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5547                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5548       V1 = NewV.getOperand(0);
5549       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5550     }
5551   }
5552
5553   // If we have SSSE3, and all words of the result are from 1 input vector,
5554   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5555   // is present, fall back to case 4.
5556   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5557     SmallVector<SDValue,16> pshufbMask;
5558
5559     // If we have elements from both input vectors, set the high bit of the
5560     // shuffle mask element to zero out elements that come from V2 in the V1
5561     // mask, and elements that come from V1 in the V2 mask, so that the two
5562     // results can be OR'd together.
5563     bool TwoInputs = V1Used && V2Used;
5564     for (unsigned i = 0; i != 8; ++i) {
5565       int EltIdx = MaskVals[i] * 2;
5566       if (TwoInputs && (EltIdx >= 16)) {
5567         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5568         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5569         continue;
5570       }
5571       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5572       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5573     }
5574     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5575     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5576                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5577                                  MVT::v16i8, &pshufbMask[0], 16));
5578     if (!TwoInputs)
5579       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5580
5581     // Calculate the shuffle mask for the second input, shuffle it, and
5582     // OR it with the first shuffled input.
5583     pshufbMask.clear();
5584     for (unsigned i = 0; i != 8; ++i) {
5585       int EltIdx = MaskVals[i] * 2;
5586       if (EltIdx < 16) {
5587         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5588         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5589         continue;
5590       }
5591       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5592       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5593     }
5594     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5595     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5596                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5597                                  MVT::v16i8, &pshufbMask[0], 16));
5598     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5599     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5600   }
5601
5602   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5603   // and update MaskVals with new element order.
5604   BitVector InOrder(8);
5605   if (BestLoQuad >= 0) {
5606     SmallVector<int, 8> MaskV;
5607     for (int i = 0; i != 4; ++i) {
5608       int idx = MaskVals[i];
5609       if (idx < 0) {
5610         MaskV.push_back(-1);
5611         InOrder.set(i);
5612       } else if ((idx / 4) == BestLoQuad) {
5613         MaskV.push_back(idx & 3);
5614         InOrder.set(i);
5615       } else {
5616         MaskV.push_back(-1);
5617       }
5618     }
5619     for (unsigned i = 4; i != 8; ++i)
5620       MaskV.push_back(i);
5621     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5622                                 &MaskV[0]);
5623
5624     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5625         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5626       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5627                                NewV.getOperand(0),
5628                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5629                                DAG);
5630   }
5631
5632   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5633   // and update MaskVals with the new element order.
5634   if (BestHiQuad >= 0) {
5635     SmallVector<int, 8> MaskV;
5636     for (unsigned i = 0; i != 4; ++i)
5637       MaskV.push_back(i);
5638     for (unsigned i = 4; i != 8; ++i) {
5639       int idx = MaskVals[i];
5640       if (idx < 0) {
5641         MaskV.push_back(-1);
5642         InOrder.set(i);
5643       } else if ((idx / 4) == BestHiQuad) {
5644         MaskV.push_back((idx & 3) + 4);
5645         InOrder.set(i);
5646       } else {
5647         MaskV.push_back(-1);
5648       }
5649     }
5650     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5651                                 &MaskV[0]);
5652
5653     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5654         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5655       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5656                               NewV.getOperand(0),
5657                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5658                               DAG);
5659   }
5660
5661   // In case BestHi & BestLo were both -1, which means each quadword has a word
5662   // from each of the four input quadwords, calculate the InOrder bitvector now
5663   // before falling through to the insert/extract cleanup.
5664   if (BestLoQuad == -1 && BestHiQuad == -1) {
5665     NewV = V1;
5666     for (int i = 0; i != 8; ++i)
5667       if (MaskVals[i] < 0 || MaskVals[i] == i)
5668         InOrder.set(i);
5669   }
5670
5671   // The other elements are put in the right place using pextrw and pinsrw.
5672   for (unsigned i = 0; i != 8; ++i) {
5673     if (InOrder[i])
5674       continue;
5675     int EltIdx = MaskVals[i];
5676     if (EltIdx < 0)
5677       continue;
5678     SDValue ExtOp = (EltIdx < 8)
5679     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5680                   DAG.getIntPtrConstant(EltIdx))
5681     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5682                   DAG.getIntPtrConstant(EltIdx - 8));
5683     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5684                        DAG.getIntPtrConstant(i));
5685   }
5686   return NewV;
5687 }
5688
5689 // v16i8 shuffles - Prefer shuffles in the following order:
5690 // 1. [ssse3] 1 x pshufb
5691 // 2. [ssse3] 2 x pshufb + 1 x por
5692 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5693 static
5694 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5695                                  SelectionDAG &DAG,
5696                                  const X86TargetLowering &TLI) {
5697   SDValue V1 = SVOp->getOperand(0);
5698   SDValue V2 = SVOp->getOperand(1);
5699   DebugLoc dl = SVOp->getDebugLoc();
5700   SmallVector<int, 16> MaskVals;
5701   SVOp->getMask(MaskVals);
5702
5703   // If we have SSSE3, case 1 is generated when all result bytes come from
5704   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5705   // present, fall back to case 3.
5706   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5707   bool V1Only = true;
5708   bool V2Only = true;
5709   for (unsigned i = 0; i < 16; ++i) {
5710     int EltIdx = MaskVals[i];
5711     if (EltIdx < 0)
5712       continue;
5713     if (EltIdx < 16)
5714       V2Only = false;
5715     else
5716       V1Only = false;
5717   }
5718
5719   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5720   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5721     SmallVector<SDValue,16> pshufbMask;
5722
5723     // If all result elements are from one input vector, then only translate
5724     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5725     //
5726     // Otherwise, we have elements from both input vectors, and must zero out
5727     // elements that come from V2 in the first mask, and V1 in the second mask
5728     // so that we can OR them together.
5729     bool TwoInputs = !(V1Only || V2Only);
5730     for (unsigned i = 0; i != 16; ++i) {
5731       int EltIdx = MaskVals[i];
5732       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5733         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5734         continue;
5735       }
5736       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5737     }
5738     // If all the elements are from V2, assign it to V1 and return after
5739     // building the first pshufb.
5740     if (V2Only)
5741       V1 = V2;
5742     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5743                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5744                                  MVT::v16i8, &pshufbMask[0], 16));
5745     if (!TwoInputs)
5746       return V1;
5747
5748     // Calculate the shuffle mask for the second input, shuffle it, and
5749     // OR it with the first shuffled input.
5750     pshufbMask.clear();
5751     for (unsigned i = 0; i != 16; ++i) {
5752       int EltIdx = MaskVals[i];
5753       if (EltIdx < 16) {
5754         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5755         continue;
5756       }
5757       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5758     }
5759     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5760                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5761                                  MVT::v16i8, &pshufbMask[0], 16));
5762     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5763   }
5764
5765   // No SSSE3 - Calculate in place words and then fix all out of place words
5766   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5767   // the 16 different words that comprise the two doublequadword input vectors.
5768   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5769   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5770   SDValue NewV = V2Only ? V2 : V1;
5771   for (int i = 0; i != 8; ++i) {
5772     int Elt0 = MaskVals[i*2];
5773     int Elt1 = MaskVals[i*2+1];
5774
5775     // This word of the result is all undef, skip it.
5776     if (Elt0 < 0 && Elt1 < 0)
5777       continue;
5778
5779     // This word of the result is already in the correct place, skip it.
5780     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5781       continue;
5782     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5783       continue;
5784
5785     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5786     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5787     SDValue InsElt;
5788
5789     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5790     // using a single extract together, load it and store it.
5791     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5792       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5793                            DAG.getIntPtrConstant(Elt1 / 2));
5794       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5795                         DAG.getIntPtrConstant(i));
5796       continue;
5797     }
5798
5799     // If Elt1 is defined, extract it from the appropriate source.  If the
5800     // source byte is not also odd, shift the extracted word left 8 bits
5801     // otherwise clear the bottom 8 bits if we need to do an or.
5802     if (Elt1 >= 0) {
5803       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5804                            DAG.getIntPtrConstant(Elt1 / 2));
5805       if ((Elt1 & 1) == 0)
5806         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5807                              DAG.getConstant(8,
5808                                   TLI.getShiftAmountTy(InsElt.getValueType())));
5809       else if (Elt0 >= 0)
5810         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5811                              DAG.getConstant(0xFF00, MVT::i16));
5812     }
5813     // If Elt0 is defined, extract it from the appropriate source.  If the
5814     // source byte is not also even, shift the extracted word right 8 bits. If
5815     // Elt1 was also defined, OR the extracted values together before
5816     // inserting them in the result.
5817     if (Elt0 >= 0) {
5818       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5819                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5820       if ((Elt0 & 1) != 0)
5821         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5822                               DAG.getConstant(8,
5823                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
5824       else if (Elt1 >= 0)
5825         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5826                              DAG.getConstant(0x00FF, MVT::i16));
5827       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5828                          : InsElt0;
5829     }
5830     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5831                        DAG.getIntPtrConstant(i));
5832   }
5833   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5834 }
5835
5836 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5837 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5838 /// done when every pair / quad of shuffle mask elements point to elements in
5839 /// the right sequence. e.g.
5840 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5841 static
5842 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5843                                  SelectionDAG &DAG, DebugLoc dl) {
5844   EVT VT = SVOp->getValueType(0);
5845   SDValue V1 = SVOp->getOperand(0);
5846   SDValue V2 = SVOp->getOperand(1);
5847   unsigned NumElems = VT.getVectorNumElements();
5848   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
5849   EVT NewVT;
5850   switch (VT.getSimpleVT().SimpleTy) {
5851   default: assert(false && "Unexpected!");
5852   case MVT::v4f32: NewVT = MVT::v2f64; break;
5853   case MVT::v4i32: NewVT = MVT::v2i64; break;
5854   case MVT::v8i16: NewVT = MVT::v4i32; break;
5855   case MVT::v16i8: NewVT = MVT::v4i32; break;
5856   }
5857
5858   int Scale = NumElems / NewWidth;
5859   SmallVector<int, 8> MaskVec;
5860   for (unsigned i = 0; i < NumElems; i += Scale) {
5861     int StartIdx = -1;
5862     for (int j = 0; j < Scale; ++j) {
5863       int EltIdx = SVOp->getMaskElt(i+j);
5864       if (EltIdx < 0)
5865         continue;
5866       if (StartIdx == -1)
5867         StartIdx = EltIdx - (EltIdx % Scale);
5868       if (EltIdx != StartIdx + j)
5869         return SDValue();
5870     }
5871     if (StartIdx == -1)
5872       MaskVec.push_back(-1);
5873     else
5874       MaskVec.push_back(StartIdx / Scale);
5875   }
5876
5877   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
5878   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
5879   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5880 }
5881
5882 /// getVZextMovL - Return a zero-extending vector move low node.
5883 ///
5884 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5885                             SDValue SrcOp, SelectionDAG &DAG,
5886                             const X86Subtarget *Subtarget, DebugLoc dl) {
5887   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5888     LoadSDNode *LD = NULL;
5889     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5890       LD = dyn_cast<LoadSDNode>(SrcOp);
5891     if (!LD) {
5892       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5893       // instead.
5894       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5895       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5896           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5897           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5898           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5899         // PR2108
5900         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5901         return DAG.getNode(ISD::BITCAST, dl, VT,
5902                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5903                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5904                                                    OpVT,
5905                                                    SrcOp.getOperand(0)
5906                                                           .getOperand(0))));
5907       }
5908     }
5909   }
5910
5911   return DAG.getNode(ISD::BITCAST, dl, VT,
5912                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5913                                  DAG.getNode(ISD::BITCAST, dl,
5914                                              OpVT, SrcOp)));
5915 }
5916
5917 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
5918 /// shuffle node referes to only one lane in the sources.
5919 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
5920   EVT VT = SVOp->getValueType(0);
5921   int NumElems = VT.getVectorNumElements();
5922   int HalfSize = NumElems/2;
5923   SmallVector<int, 16> M;
5924   SVOp->getMask(M);
5925   bool MatchA = false, MatchB = false;
5926
5927   for (int l = 0; l < NumElems*2; l += HalfSize) {
5928     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
5929       MatchA = true;
5930       break;
5931     }
5932   }
5933
5934   for (int l = 0; l < NumElems*2; l += HalfSize) {
5935     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
5936       MatchB = true;
5937       break;
5938     }
5939   }
5940
5941   return MatchA && MatchB;
5942 }
5943
5944 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5945 /// which could not be matched by any known target speficic shuffle
5946 static SDValue
5947 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5948   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
5949     // If each half of a vector shuffle node referes to only one lane in the
5950     // source vectors, extract each used 128-bit lane and shuffle them using
5951     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
5952     // the work to the legalizer.
5953     DebugLoc dl = SVOp->getDebugLoc();
5954     EVT VT = SVOp->getValueType(0);
5955     int NumElems = VT.getVectorNumElements();
5956     int HalfSize = NumElems/2;
5957
5958     // Extract the reference for each half
5959     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
5960     int FstVecOpNum = 0, SndVecOpNum = 0;
5961     for (int i = 0; i < HalfSize; ++i) {
5962       int Elt = SVOp->getMaskElt(i);
5963       if (SVOp->getMaskElt(i) < 0)
5964         continue;
5965       FstVecOpNum = Elt/NumElems;
5966       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5967       break;
5968     }
5969     for (int i = HalfSize; i < NumElems; ++i) {
5970       int Elt = SVOp->getMaskElt(i);
5971       if (SVOp->getMaskElt(i) < 0)
5972         continue;
5973       SndVecOpNum = Elt/NumElems;
5974       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
5975       break;
5976     }
5977
5978     // Extract the subvectors
5979     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
5980                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
5981     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
5982                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
5983
5984     // Generate 128-bit shuffles
5985     SmallVector<int, 16> MaskV1, MaskV2;
5986     for (int i = 0; i < HalfSize; ++i) {
5987       int Elt = SVOp->getMaskElt(i);
5988       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5989     }
5990     for (int i = HalfSize; i < NumElems; ++i) {
5991       int Elt = SVOp->getMaskElt(i);
5992       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
5993     }
5994
5995     EVT NVT = V1.getValueType();
5996     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
5997     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
5998
5999     // Concatenate the result back
6000     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6001                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6002     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6003                               DAG, dl);
6004   }
6005
6006   return SDValue();
6007 }
6008
6009 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6010 /// 4 elements, and match them with several different shuffle types.
6011 static SDValue
6012 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6013   SDValue V1 = SVOp->getOperand(0);
6014   SDValue V2 = SVOp->getOperand(1);
6015   DebugLoc dl = SVOp->getDebugLoc();
6016   EVT VT = SVOp->getValueType(0);
6017
6018   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6019
6020   SmallVector<std::pair<int, int>, 8> Locs;
6021   Locs.resize(4);
6022   SmallVector<int, 8> Mask1(4U, -1);
6023   SmallVector<int, 8> PermMask;
6024   SVOp->getMask(PermMask);
6025
6026   unsigned NumHi = 0;
6027   unsigned NumLo = 0;
6028   for (unsigned i = 0; i != 4; ++i) {
6029     int Idx = PermMask[i];
6030     if (Idx < 0) {
6031       Locs[i] = std::make_pair(-1, -1);
6032     } else {
6033       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6034       if (Idx < 4) {
6035         Locs[i] = std::make_pair(0, NumLo);
6036         Mask1[NumLo] = Idx;
6037         NumLo++;
6038       } else {
6039         Locs[i] = std::make_pair(1, NumHi);
6040         if (2+NumHi < 4)
6041           Mask1[2+NumHi] = Idx;
6042         NumHi++;
6043       }
6044     }
6045   }
6046
6047   if (NumLo <= 2 && NumHi <= 2) {
6048     // If no more than two elements come from either vector. This can be
6049     // implemented with two shuffles. First shuffle gather the elements.
6050     // The second shuffle, which takes the first shuffle as both of its
6051     // vector operands, put the elements into the right order.
6052     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6053
6054     SmallVector<int, 8> Mask2(4U, -1);
6055
6056     for (unsigned i = 0; i != 4; ++i) {
6057       if (Locs[i].first == -1)
6058         continue;
6059       else {
6060         unsigned Idx = (i < 2) ? 0 : 4;
6061         Idx += Locs[i].first * 2 + Locs[i].second;
6062         Mask2[i] = Idx;
6063       }
6064     }
6065
6066     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6067   } else if (NumLo == 3 || NumHi == 3) {
6068     // Otherwise, we must have three elements from one vector, call it X, and
6069     // one element from the other, call it Y.  First, use a shufps to build an
6070     // intermediate vector with the one element from Y and the element from X
6071     // that will be in the same half in the final destination (the indexes don't
6072     // matter). Then, use a shufps to build the final vector, taking the half
6073     // containing the element from Y from the intermediate, and the other half
6074     // from X.
6075     if (NumHi == 3) {
6076       // Normalize it so the 3 elements come from V1.
6077       CommuteVectorShuffleMask(PermMask, VT);
6078       std::swap(V1, V2);
6079     }
6080
6081     // Find the element from V2.
6082     unsigned HiIndex;
6083     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6084       int Val = PermMask[HiIndex];
6085       if (Val < 0)
6086         continue;
6087       if (Val >= 4)
6088         break;
6089     }
6090
6091     Mask1[0] = PermMask[HiIndex];
6092     Mask1[1] = -1;
6093     Mask1[2] = PermMask[HiIndex^1];
6094     Mask1[3] = -1;
6095     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6096
6097     if (HiIndex >= 2) {
6098       Mask1[0] = PermMask[0];
6099       Mask1[1] = PermMask[1];
6100       Mask1[2] = HiIndex & 1 ? 6 : 4;
6101       Mask1[3] = HiIndex & 1 ? 4 : 6;
6102       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6103     } else {
6104       Mask1[0] = HiIndex & 1 ? 2 : 0;
6105       Mask1[1] = HiIndex & 1 ? 0 : 2;
6106       Mask1[2] = PermMask[2];
6107       Mask1[3] = PermMask[3];
6108       if (Mask1[2] >= 0)
6109         Mask1[2] += 4;
6110       if (Mask1[3] >= 0)
6111         Mask1[3] += 4;
6112       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6113     }
6114   }
6115
6116   // Break it into (shuffle shuffle_hi, shuffle_lo).
6117   Locs.clear();
6118   Locs.resize(4);
6119   SmallVector<int,8> LoMask(4U, -1);
6120   SmallVector<int,8> HiMask(4U, -1);
6121
6122   SmallVector<int,8> *MaskPtr = &LoMask;
6123   unsigned MaskIdx = 0;
6124   unsigned LoIdx = 0;
6125   unsigned HiIdx = 2;
6126   for (unsigned i = 0; i != 4; ++i) {
6127     if (i == 2) {
6128       MaskPtr = &HiMask;
6129       MaskIdx = 1;
6130       LoIdx = 0;
6131       HiIdx = 2;
6132     }
6133     int Idx = PermMask[i];
6134     if (Idx < 0) {
6135       Locs[i] = std::make_pair(-1, -1);
6136     } else if (Idx < 4) {
6137       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6138       (*MaskPtr)[LoIdx] = Idx;
6139       LoIdx++;
6140     } else {
6141       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6142       (*MaskPtr)[HiIdx] = Idx;
6143       HiIdx++;
6144     }
6145   }
6146
6147   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6148   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6149   SmallVector<int, 8> MaskOps;
6150   for (unsigned i = 0; i != 4; ++i) {
6151     if (Locs[i].first == -1) {
6152       MaskOps.push_back(-1);
6153     } else {
6154       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6155       MaskOps.push_back(Idx);
6156     }
6157   }
6158   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6159 }
6160
6161 static bool MayFoldVectorLoad(SDValue V) {
6162   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6163     V = V.getOperand(0);
6164   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6165     V = V.getOperand(0);
6166   if (MayFoldLoad(V))
6167     return true;
6168   return false;
6169 }
6170
6171 // FIXME: the version above should always be used. Since there's
6172 // a bug where several vector shuffles can't be folded because the
6173 // DAG is not updated during lowering and a node claims to have two
6174 // uses while it only has one, use this version, and let isel match
6175 // another instruction if the load really happens to have more than
6176 // one use. Remove this version after this bug get fixed.
6177 // rdar://8434668, PR8156
6178 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6179   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6180     V = V.getOperand(0);
6181   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6182     V = V.getOperand(0);
6183   if (ISD::isNormalLoad(V.getNode()))
6184     return true;
6185   return false;
6186 }
6187
6188 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6189 /// a vector extract, and if both can be later optimized into a single load.
6190 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6191 /// here because otherwise a target specific shuffle node is going to be
6192 /// emitted for this shuffle, and the optimization not done.
6193 /// FIXME: This is probably not the best approach, but fix the problem
6194 /// until the right path is decided.
6195 static
6196 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6197                                          const TargetLowering &TLI) {
6198   EVT VT = V.getValueType();
6199   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6200
6201   // Be sure that the vector shuffle is present in a pattern like this:
6202   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6203   if (!V.hasOneUse())
6204     return false;
6205
6206   SDNode *N = *V.getNode()->use_begin();
6207   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6208     return false;
6209
6210   SDValue EltNo = N->getOperand(1);
6211   if (!isa<ConstantSDNode>(EltNo))
6212     return false;
6213
6214   // If the bit convert changed the number of elements, it is unsafe
6215   // to examine the mask.
6216   bool HasShuffleIntoBitcast = false;
6217   if (V.getOpcode() == ISD::BITCAST) {
6218     EVT SrcVT = V.getOperand(0).getValueType();
6219     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6220       return false;
6221     V = V.getOperand(0);
6222     HasShuffleIntoBitcast = true;
6223   }
6224
6225   // Select the input vector, guarding against out of range extract vector.
6226   unsigned NumElems = VT.getVectorNumElements();
6227   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6228   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6229   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6230
6231   // Skip one more bit_convert if necessary
6232   if (V.getOpcode() == ISD::BITCAST)
6233     V = V.getOperand(0);
6234
6235   if (ISD::isNormalLoad(V.getNode())) {
6236     // Is the original load suitable?
6237     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6238
6239     // FIXME: avoid the multi-use bug that is preventing lots of
6240     // of foldings to be detected, this is still wrong of course, but
6241     // give the temporary desired behavior, and if it happens that
6242     // the load has real more uses, during isel it will not fold, and
6243     // will generate poor code.
6244     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6245       return false;
6246
6247     if (!HasShuffleIntoBitcast)
6248       return true;
6249
6250     // If there's a bitcast before the shuffle, check if the load type and
6251     // alignment is valid.
6252     unsigned Align = LN0->getAlignment();
6253     unsigned NewAlign =
6254       TLI.getTargetData()->getABITypeAlignment(
6255                                     VT.getTypeForEVT(*DAG.getContext()));
6256
6257     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6258       return false;
6259   }
6260
6261   return true;
6262 }
6263
6264 static
6265 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6266   EVT VT = Op.getValueType();
6267
6268   // Canonizalize to v2f64.
6269   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6270   return DAG.getNode(ISD::BITCAST, dl, VT,
6271                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6272                                           V1, DAG));
6273 }
6274
6275 static
6276 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6277                         bool HasXMMInt) {
6278   SDValue V1 = Op.getOperand(0);
6279   SDValue V2 = Op.getOperand(1);
6280   EVT VT = Op.getValueType();
6281
6282   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6283
6284   if (HasXMMInt && VT == MVT::v2f64)
6285     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6286
6287   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6288   return DAG.getNode(ISD::BITCAST, dl, VT,
6289                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6290                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6291                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6292 }
6293
6294 static
6295 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6296   SDValue V1 = Op.getOperand(0);
6297   SDValue V2 = Op.getOperand(1);
6298   EVT VT = Op.getValueType();
6299
6300   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6301          "unsupported shuffle type");
6302
6303   if (V2.getOpcode() == ISD::UNDEF)
6304     V2 = V1;
6305
6306   // v4i32 or v4f32
6307   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6308 }
6309
6310 static inline unsigned getSHUFPOpcode(EVT VT) {
6311   switch(VT.getSimpleVT().SimpleTy) {
6312   case MVT::v8i32: // Use fp unit for int unpack.
6313   case MVT::v8f32:
6314   case MVT::v4i32: // Use fp unit for int unpack.
6315   case MVT::v4f32: return X86ISD::SHUFPS;
6316   case MVT::v4i64: // Use fp unit for int unpack.
6317   case MVT::v4f64:
6318   case MVT::v2i64: // Use fp unit for int unpack.
6319   case MVT::v2f64: return X86ISD::SHUFPD;
6320   default:
6321     llvm_unreachable("Unknown type for shufp*");
6322   }
6323   return 0;
6324 }
6325
6326 static
6327 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6328   SDValue V1 = Op.getOperand(0);
6329   SDValue V2 = Op.getOperand(1);
6330   EVT VT = Op.getValueType();
6331   unsigned NumElems = VT.getVectorNumElements();
6332
6333   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6334   // operand of these instructions is only memory, so check if there's a
6335   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6336   // same masks.
6337   bool CanFoldLoad = false;
6338
6339   // Trivial case, when V2 comes from a load.
6340   if (MayFoldVectorLoad(V2))
6341     CanFoldLoad = true;
6342
6343   // When V1 is a load, it can be folded later into a store in isel, example:
6344   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6345   //    turns into:
6346   //  (MOVLPSmr addr:$src1, VR128:$src2)
6347   // So, recognize this potential and also use MOVLPS or MOVLPD
6348   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6349     CanFoldLoad = true;
6350
6351   // Both of them can't be memory operations though.
6352   if (MayFoldVectorLoad(V1) && MayFoldVectorLoad(V2))
6353     CanFoldLoad = false;
6354
6355   if (CanFoldLoad) {
6356     if (HasXMMInt && NumElems == 2)
6357       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6358
6359     if (NumElems == 4)
6360       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6361   }
6362
6363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6364   // movl and movlp will both match v2i64, but v2i64 is never matched by
6365   // movl earlier because we make it strict to avoid messing with the movlp load
6366   // folding logic (see the code above getMOVLP call). Match it here then,
6367   // this is horrible, but will stay like this until we move all shuffle
6368   // matching to x86 specific nodes. Note that for the 1st condition all
6369   // types are matched with movsd.
6370   if (HasXMMInt) {
6371     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6372     // as to remove this logic from here, as much as possible
6373     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6374       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6375     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6376   }
6377
6378   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6379
6380   // Invert the operand order and use SHUFPS to match it.
6381   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6382                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6383 }
6384
6385 static inline unsigned getUNPCKLOpcode(EVT VT) {
6386   switch(VT.getSimpleVT().SimpleTy) {
6387   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6388   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6389   case MVT::v4f32: return X86ISD::UNPCKLPS;
6390   case MVT::v2f64: return X86ISD::UNPCKLPD;
6391   case MVT::v8i32: // Use fp unit for int unpack.
6392   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6393   case MVT::v4i64: // Use fp unit for int unpack.
6394   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6395   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6396   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6397   default:
6398     llvm_unreachable("Unknown type for unpckl");
6399   }
6400   return 0;
6401 }
6402
6403 static inline unsigned getUNPCKHOpcode(EVT VT) {
6404   switch(VT.getSimpleVT().SimpleTy) {
6405   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6406   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6407   case MVT::v4f32: return X86ISD::UNPCKHPS;
6408   case MVT::v2f64: return X86ISD::UNPCKHPD;
6409   case MVT::v8i32: // Use fp unit for int unpack.
6410   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6411   case MVT::v4i64: // Use fp unit for int unpack.
6412   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6413   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6414   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6415   default:
6416     llvm_unreachable("Unknown type for unpckh");
6417   }
6418   return 0;
6419 }
6420
6421 static inline unsigned getVPERMILOpcode(EVT VT) {
6422   switch(VT.getSimpleVT().SimpleTy) {
6423   case MVT::v4i32:
6424   case MVT::v4f32: return X86ISD::VPERMILPS;
6425   case MVT::v2i64:
6426   case MVT::v2f64: return X86ISD::VPERMILPD;
6427   case MVT::v8i32:
6428   case MVT::v8f32: return X86ISD::VPERMILPSY;
6429   case MVT::v4i64:
6430   case MVT::v4f64: return X86ISD::VPERMILPDY;
6431   default:
6432     llvm_unreachable("Unknown type for vpermil");
6433   }
6434   return 0;
6435 }
6436
6437 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
6438 /// a vbroadcast node. The nodes are suitable whenever we can fold a load coming
6439 /// from a 32 or 64 bit scalar. Update Op to the desired load to be folded.
6440 static bool isVectorBroadcast(SDValue &Op) {
6441   EVT VT = Op.getValueType();
6442   bool Is256 = VT.getSizeInBits() == 256;
6443
6444   assert((VT.getSizeInBits() == 128 || Is256) &&
6445          "Unsupported type for vbroadcast node");
6446
6447   SDValue V = Op;
6448   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6449     V = V.getOperand(0);
6450
6451   if (Is256 && !(V.hasOneUse() &&
6452                  V.getOpcode() == ISD::INSERT_SUBVECTOR &&
6453                  V.getOperand(0).getOpcode() == ISD::UNDEF))
6454     return false;
6455
6456   if (Is256)
6457     V = V.getOperand(1);
6458
6459   if (!V.hasOneUse())
6460     return false;
6461
6462   // Check the source scalar_to_vector type. 256-bit broadcasts are
6463   // supported for 32/64-bit sizes, while 128-bit ones are only supported
6464   // for 32-bit scalars.
6465   if (V.getOpcode() != ISD::SCALAR_TO_VECTOR)
6466     return false;
6467
6468   unsigned ScalarSize = V.getOperand(0).getValueType().getSizeInBits();
6469   if (ScalarSize != 32 && ScalarSize != 64)
6470     return false;
6471   if (!Is256 && ScalarSize == 64)
6472     return false;
6473
6474   V = V.getOperand(0);
6475   if (!MayFoldLoad(V))
6476     return false;
6477
6478   // Return the load node
6479   Op = V;
6480   return true;
6481 }
6482
6483 static
6484 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6485                                const TargetLowering &TLI,
6486                                const X86Subtarget *Subtarget) {
6487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6488   EVT VT = Op.getValueType();
6489   DebugLoc dl = Op.getDebugLoc();
6490   SDValue V1 = Op.getOperand(0);
6491   SDValue V2 = Op.getOperand(1);
6492
6493   if (isZeroShuffle(SVOp))
6494     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6495
6496   // Handle splat operations
6497   if (SVOp->isSplat()) {
6498     unsigned NumElem = VT.getVectorNumElements();
6499     int Size = VT.getSizeInBits();
6500     // Special case, this is the only place now where it's allowed to return
6501     // a vector_shuffle operation without using a target specific node, because
6502     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6503     // this be moved to DAGCombine instead?
6504     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6505       return Op;
6506
6507     // Use vbroadcast whenever the splat comes from a foldable load
6508     if (Subtarget->hasAVX() && isVectorBroadcast(V1))
6509       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, V1);
6510
6511     // Handle splats by matching through known shuffle masks
6512     if ((Size == 128 && NumElem <= 4) ||
6513         (Size == 256 && NumElem < 8))
6514       return SDValue();
6515
6516     // All remaning splats are promoted to target supported vector shuffles.
6517     return PromoteSplat(SVOp, DAG);
6518   }
6519
6520   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6521   // do it!
6522   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6523     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6524     if (NewOp.getNode())
6525       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6526   } else if ((VT == MVT::v4i32 ||
6527              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6528     // FIXME: Figure out a cleaner way to do this.
6529     // Try to make use of movq to zero out the top part.
6530     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6531       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6532       if (NewOp.getNode()) {
6533         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6534           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6535                               DAG, Subtarget, dl);
6536       }
6537     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6538       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6539       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6540         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6541                             DAG, Subtarget, dl);
6542     }
6543   }
6544   return SDValue();
6545 }
6546
6547 SDValue
6548 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6550   SDValue V1 = Op.getOperand(0);
6551   SDValue V2 = Op.getOperand(1);
6552   EVT VT = Op.getValueType();
6553   DebugLoc dl = Op.getDebugLoc();
6554   unsigned NumElems = VT.getVectorNumElements();
6555   bool isMMX = VT.getSizeInBits() == 64;
6556   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6557   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6558   bool V1IsSplat = false;
6559   bool V2IsSplat = false;
6560   bool HasXMMInt = Subtarget->hasXMMInt();
6561   MachineFunction &MF = DAG.getMachineFunction();
6562   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6563
6564   // Shuffle operations on MMX not supported.
6565   if (isMMX)
6566     return Op;
6567
6568   // Vector shuffle lowering takes 3 steps:
6569   //
6570   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6571   //    narrowing and commutation of operands should be handled.
6572   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6573   //    shuffle nodes.
6574   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6575   //    so the shuffle can be broken into other shuffles and the legalizer can
6576   //    try the lowering again.
6577   //
6578   // The general ideia is that no vector_shuffle operation should be left to
6579   // be matched during isel, all of them must be converted to a target specific
6580   // node here.
6581
6582   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6583   // narrowing and commutation of operands should be handled. The actual code
6584   // doesn't include all of those, work in progress...
6585   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6586   if (NewOp.getNode())
6587     return NewOp;
6588
6589   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6590   // unpckh_undef). Only use pshufd if speed is more important than size.
6591   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6592     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6593   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6594     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6595
6596   if (X86::isMOVDDUPMask(SVOp) &&
6597       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6598       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6599     return getMOVDDup(Op, dl, V1, DAG);
6600
6601   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6602     return getMOVHighToLow(Op, dl, DAG);
6603
6604   // Use to match splats
6605   if (HasXMMInt && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
6606       (VT == MVT::v2f64 || VT == MVT::v2i64))
6607     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6608
6609   if (X86::isPSHUFDMask(SVOp)) {
6610     // The actual implementation will match the mask in the if above and then
6611     // during isel it can match several different instructions, not only pshufd
6612     // as its name says, sad but true, emulate the behavior for now...
6613     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6614         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6615
6616     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6617
6618     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6619       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6620
6621     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6622                                 TargetMask, DAG);
6623   }
6624
6625   // Check if this can be converted into a logical shift.
6626   bool isLeft = false;
6627   unsigned ShAmt = 0;
6628   SDValue ShVal;
6629   bool isShift = getSubtarget()->hasXMMInt() &&
6630                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6631   if (isShift && ShVal.hasOneUse()) {
6632     // If the shifted value has multiple uses, it may be cheaper to use
6633     // v_set0 + movlhps or movhlps, etc.
6634     EVT EltVT = VT.getVectorElementType();
6635     ShAmt *= EltVT.getSizeInBits();
6636     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6637   }
6638
6639   if (X86::isMOVLMask(SVOp)) {
6640     if (V1IsUndef)
6641       return V2;
6642     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6643       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6644     if (!X86::isMOVLPMask(SVOp)) {
6645       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6646         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6647
6648       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6649         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6650     }
6651   }
6652
6653   // FIXME: fold these into legal mask.
6654   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
6655     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6656
6657   if (X86::isMOVHLPSMask(SVOp))
6658     return getMOVHighToLow(Op, dl, DAG);
6659
6660   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6661     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6662
6663   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6664     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6665
6666   if (X86::isMOVLPMask(SVOp))
6667     return getMOVLP(Op, dl, DAG, HasXMMInt);
6668
6669   if (ShouldXformToMOVHLPS(SVOp) ||
6670       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6671     return CommuteVectorShuffle(SVOp, DAG);
6672
6673   if (isShift) {
6674     // No better options. Use a vshl / vsrl.
6675     EVT EltVT = VT.getVectorElementType();
6676     ShAmt *= EltVT.getSizeInBits();
6677     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6678   }
6679
6680   bool Commuted = false;
6681   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6682   // 1,1,1,1 -> v8i16 though.
6683   V1IsSplat = isSplatVector(V1.getNode());
6684   V2IsSplat = isSplatVector(V2.getNode());
6685
6686   // Canonicalize the splat or undef, if present, to be on the RHS.
6687   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6688     Op = CommuteVectorShuffle(SVOp, DAG);
6689     SVOp = cast<ShuffleVectorSDNode>(Op);
6690     V1 = SVOp->getOperand(0);
6691     V2 = SVOp->getOperand(1);
6692     std::swap(V1IsSplat, V2IsSplat);
6693     std::swap(V1IsUndef, V2IsUndef);
6694     Commuted = true;
6695   }
6696
6697   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6698     // Shuffling low element of v1 into undef, just return v1.
6699     if (V2IsUndef)
6700       return V1;
6701     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6702     // the instruction selector will not match, so get a canonical MOVL with
6703     // swapped operands to undo the commute.
6704     return getMOVL(DAG, dl, VT, V2, V1);
6705   }
6706
6707   if (X86::isUNPCKLMask(SVOp))
6708     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
6709
6710   if (X86::isUNPCKHMask(SVOp))
6711     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
6712
6713   if (V2IsSplat) {
6714     // Normalize mask so all entries that point to V2 points to its first
6715     // element then try to match unpck{h|l} again. If match, return a
6716     // new vector_shuffle with the corrected mask.
6717     SDValue NewMask = NormalizeMask(SVOp, DAG);
6718     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6719     if (NSVOp != SVOp) {
6720       if (X86::isUNPCKLMask(NSVOp, true)) {
6721         return NewMask;
6722       } else if (X86::isUNPCKHMask(NSVOp, true)) {
6723         return NewMask;
6724       }
6725     }
6726   }
6727
6728   if (Commuted) {
6729     // Commute is back and try unpck* again.
6730     // FIXME: this seems wrong.
6731     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6732     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6733
6734     if (X86::isUNPCKLMask(NewSVOp))
6735       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
6736
6737     if (X86::isUNPCKHMask(NewSVOp))
6738       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
6739   }
6740
6741   // Normalize the node to match x86 shuffle ops if needed
6742   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6743     return CommuteVectorShuffle(SVOp, DAG);
6744
6745   // The checks below are all present in isShuffleMaskLegal, but they are
6746   // inlined here right now to enable us to directly emit target specific
6747   // nodes, and remove one by one until they don't return Op anymore.
6748   SmallVector<int, 16> M;
6749   SVOp->getMask(M);
6750
6751   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6752     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6753                                 X86::getShufflePALIGNRImmediate(SVOp),
6754                                 DAG);
6755
6756   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6757       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6758     if (VT == MVT::v2f64)
6759       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6760     if (VT == MVT::v2i64)
6761       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6762   }
6763
6764   if (isPSHUFHWMask(M, VT))
6765     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6766                                 X86::getShufflePSHUFHWImmediate(SVOp),
6767                                 DAG);
6768
6769   if (isPSHUFLWMask(M, VT))
6770     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6771                                 X86::getShufflePSHUFLWImmediate(SVOp),
6772                                 DAG);
6773
6774   if (isSHUFPMask(M, VT))
6775     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6776                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6777
6778   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6779     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
6780   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6781     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
6782
6783   //===--------------------------------------------------------------------===//
6784   // Generate target specific nodes for 128 or 256-bit shuffles only
6785   // supported in the AVX instruction set.
6786   //
6787
6788   // Handle VMOVDDUPY permutations
6789   if (isMOVDDUPYMask(SVOp, Subtarget))
6790     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6791
6792   // Handle VPERMILPS* permutations
6793   if (isVPERMILPSMask(M, VT, Subtarget))
6794     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6795                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6796
6797   // Handle VPERMILPD* permutations
6798   if (isVPERMILPDMask(M, VT, Subtarget))
6799     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6800                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6801
6802   // Handle VPERM2F128 permutations
6803   if (isVPERM2F128Mask(M, VT, Subtarget))
6804     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6805                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6806
6807   // Handle VSHUFPSY permutations
6808   if (isVSHUFPSYMask(M, VT, Subtarget))
6809     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6810                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6811
6812   // Handle VSHUFPDY permutations
6813   if (isVSHUFPDYMask(M, VT, Subtarget))
6814     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6815                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6816
6817   //===--------------------------------------------------------------------===//
6818   // Since no target specific shuffle was selected for this generic one,
6819   // lower it into other known shuffles. FIXME: this isn't true yet, but
6820   // this is the plan.
6821   //
6822
6823   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6824   if (VT == MVT::v8i16) {
6825     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6826     if (NewOp.getNode())
6827       return NewOp;
6828   }
6829
6830   if (VT == MVT::v16i8) {
6831     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6832     if (NewOp.getNode())
6833       return NewOp;
6834   }
6835
6836   // Handle all 128-bit wide vectors with 4 elements, and match them with
6837   // several different shuffle types.
6838   if (NumElems == 4 && VT.getSizeInBits() == 128)
6839     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6840
6841   // Handle general 256-bit shuffles
6842   if (VT.is256BitVector())
6843     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6844
6845   return SDValue();
6846 }
6847
6848 SDValue
6849 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6850                                                 SelectionDAG &DAG) const {
6851   EVT VT = Op.getValueType();
6852   DebugLoc dl = Op.getDebugLoc();
6853
6854   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6855     return SDValue();
6856
6857   if (VT.getSizeInBits() == 8) {
6858     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6859                                     Op.getOperand(0), Op.getOperand(1));
6860     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6861                                     DAG.getValueType(VT));
6862     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6863   } else if (VT.getSizeInBits() == 16) {
6864     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6865     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6866     if (Idx == 0)
6867       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6868                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6869                                      DAG.getNode(ISD::BITCAST, dl,
6870                                                  MVT::v4i32,
6871                                                  Op.getOperand(0)),
6872                                      Op.getOperand(1)));
6873     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6874                                     Op.getOperand(0), Op.getOperand(1));
6875     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6876                                     DAG.getValueType(VT));
6877     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6878   } else if (VT == MVT::f32) {
6879     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6880     // the result back to FR32 register. It's only worth matching if the
6881     // result has a single use which is a store or a bitcast to i32.  And in
6882     // the case of a store, it's not worth it if the index is a constant 0,
6883     // because a MOVSSmr can be used instead, which is smaller and faster.
6884     if (!Op.hasOneUse())
6885       return SDValue();
6886     SDNode *User = *Op.getNode()->use_begin();
6887     if ((User->getOpcode() != ISD::STORE ||
6888          (isa<ConstantSDNode>(Op.getOperand(1)) &&
6889           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6890         (User->getOpcode() != ISD::BITCAST ||
6891          User->getValueType(0) != MVT::i32))
6892       return SDValue();
6893     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6894                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6895                                               Op.getOperand(0)),
6896                                               Op.getOperand(1));
6897     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6898   } else if (VT == MVT::i32) {
6899     // ExtractPS works with constant index.
6900     if (isa<ConstantSDNode>(Op.getOperand(1)))
6901       return Op;
6902   }
6903   return SDValue();
6904 }
6905
6906
6907 SDValue
6908 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6909                                            SelectionDAG &DAG) const {
6910   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6911     return SDValue();
6912
6913   SDValue Vec = Op.getOperand(0);
6914   EVT VecVT = Vec.getValueType();
6915
6916   // If this is a 256-bit vector result, first extract the 128-bit vector and
6917   // then extract the element from the 128-bit vector.
6918   if (VecVT.getSizeInBits() == 256) {
6919     DebugLoc dl = Op.getNode()->getDebugLoc();
6920     unsigned NumElems = VecVT.getVectorNumElements();
6921     SDValue Idx = Op.getOperand(1);
6922     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6923
6924     // Get the 128-bit vector.
6925     bool Upper = IdxVal >= NumElems/2;
6926     Vec = Extract128BitVector(Vec,
6927                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
6928
6929     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6930                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
6931   }
6932
6933   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6934
6935   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
6936     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6937     if (Res.getNode())
6938       return Res;
6939   }
6940
6941   EVT VT = Op.getValueType();
6942   DebugLoc dl = Op.getDebugLoc();
6943   // TODO: handle v16i8.
6944   if (VT.getSizeInBits() == 16) {
6945     SDValue Vec = Op.getOperand(0);
6946     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6947     if (Idx == 0)
6948       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6949                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6950                                      DAG.getNode(ISD::BITCAST, dl,
6951                                                  MVT::v4i32, Vec),
6952                                      Op.getOperand(1)));
6953     // Transform it so it match pextrw which produces a 32-bit result.
6954     EVT EltVT = MVT::i32;
6955     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6956                                     Op.getOperand(0), Op.getOperand(1));
6957     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6958                                     DAG.getValueType(VT));
6959     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6960   } else if (VT.getSizeInBits() == 32) {
6961     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6962     if (Idx == 0)
6963       return Op;
6964
6965     // SHUFPS the element to the lowest double word, then movss.
6966     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6967     EVT VVT = Op.getOperand(0).getValueType();
6968     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6969                                        DAG.getUNDEF(VVT), Mask);
6970     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6971                        DAG.getIntPtrConstant(0));
6972   } else if (VT.getSizeInBits() == 64) {
6973     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6974     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6975     //        to match extract_elt for f64.
6976     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6977     if (Idx == 0)
6978       return Op;
6979
6980     // UNPCKHPD the element to the lowest double word, then movsd.
6981     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6982     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6983     int Mask[2] = { 1, -1 };
6984     EVT VVT = Op.getOperand(0).getValueType();
6985     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6986                                        DAG.getUNDEF(VVT), Mask);
6987     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6988                        DAG.getIntPtrConstant(0));
6989   }
6990
6991   return SDValue();
6992 }
6993
6994 SDValue
6995 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6996                                                SelectionDAG &DAG) const {
6997   EVT VT = Op.getValueType();
6998   EVT EltVT = VT.getVectorElementType();
6999   DebugLoc dl = Op.getDebugLoc();
7000
7001   SDValue N0 = Op.getOperand(0);
7002   SDValue N1 = Op.getOperand(1);
7003   SDValue N2 = Op.getOperand(2);
7004
7005   if (VT.getSizeInBits() == 256)
7006     return SDValue();
7007
7008   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7009       isa<ConstantSDNode>(N2)) {
7010     unsigned Opc;
7011     if (VT == MVT::v8i16)
7012       Opc = X86ISD::PINSRW;
7013     else if (VT == MVT::v16i8)
7014       Opc = X86ISD::PINSRB;
7015     else
7016       Opc = X86ISD::PINSRB;
7017
7018     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7019     // argument.
7020     if (N1.getValueType() != MVT::i32)
7021       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7022     if (N2.getValueType() != MVT::i32)
7023       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7024     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7025   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7026     // Bits [7:6] of the constant are the source select.  This will always be
7027     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7028     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7029     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7030     // Bits [5:4] of the constant are the destination select.  This is the
7031     //  value of the incoming immediate.
7032     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7033     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7034     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7035     // Create this as a scalar to vector..
7036     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7037     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7038   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
7039     // PINSR* works with constant index.
7040     return Op;
7041   }
7042   return SDValue();
7043 }
7044
7045 SDValue
7046 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7047   EVT VT = Op.getValueType();
7048   EVT EltVT = VT.getVectorElementType();
7049
7050   DebugLoc dl = Op.getDebugLoc();
7051   SDValue N0 = Op.getOperand(0);
7052   SDValue N1 = Op.getOperand(1);
7053   SDValue N2 = Op.getOperand(2);
7054
7055   // If this is a 256-bit vector result, first extract the 128-bit vector,
7056   // insert the element into the extracted half and then place it back.
7057   if (VT.getSizeInBits() == 256) {
7058     if (!isa<ConstantSDNode>(N2))
7059       return SDValue();
7060
7061     // Get the desired 128-bit vector half.
7062     unsigned NumElems = VT.getVectorNumElements();
7063     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7064     bool Upper = IdxVal >= NumElems/2;
7065     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7066     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7067
7068     // Insert the element into the desired half.
7069     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7070                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7071
7072     // Insert the changed part back to the 256-bit vector
7073     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7074   }
7075
7076   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7077     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7078
7079   if (EltVT == MVT::i8)
7080     return SDValue();
7081
7082   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7083     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7084     // as its second argument.
7085     if (N1.getValueType() != MVT::i32)
7086       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7087     if (N2.getValueType() != MVT::i32)
7088       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7089     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7090   }
7091   return SDValue();
7092 }
7093
7094 SDValue
7095 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7096   LLVMContext *Context = DAG.getContext();
7097   DebugLoc dl = Op.getDebugLoc();
7098   EVT OpVT = Op.getValueType();
7099
7100   // If this is a 256-bit vector result, first insert into a 128-bit
7101   // vector and then insert into the 256-bit vector.
7102   if (OpVT.getSizeInBits() > 128) {
7103     // Insert into a 128-bit vector.
7104     EVT VT128 = EVT::getVectorVT(*Context,
7105                                  OpVT.getVectorElementType(),
7106                                  OpVT.getVectorNumElements() / 2);
7107
7108     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7109
7110     // Insert the 128-bit vector.
7111     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7112                               DAG.getConstant(0, MVT::i32),
7113                               DAG, dl);
7114   }
7115
7116   if (Op.getValueType() == MVT::v1i64 &&
7117       Op.getOperand(0).getValueType() == MVT::i64)
7118     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7119
7120   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7121   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7122          "Expected an SSE type!");
7123   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7124                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7125 }
7126
7127 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7128 // a simple subregister reference or explicit instructions to grab
7129 // upper bits of a vector.
7130 SDValue
7131 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7132   if (Subtarget->hasAVX()) {
7133     DebugLoc dl = Op.getNode()->getDebugLoc();
7134     SDValue Vec = Op.getNode()->getOperand(0);
7135     SDValue Idx = Op.getNode()->getOperand(1);
7136
7137     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7138         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7139         return Extract128BitVector(Vec, Idx, DAG, dl);
7140     }
7141   }
7142   return SDValue();
7143 }
7144
7145 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7146 // simple superregister reference or explicit instructions to insert
7147 // the upper bits of a vector.
7148 SDValue
7149 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7150   if (Subtarget->hasAVX()) {
7151     DebugLoc dl = Op.getNode()->getDebugLoc();
7152     SDValue Vec = Op.getNode()->getOperand(0);
7153     SDValue SubVec = Op.getNode()->getOperand(1);
7154     SDValue Idx = Op.getNode()->getOperand(2);
7155
7156     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7157         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7158       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7159     }
7160   }
7161   return SDValue();
7162 }
7163
7164 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7165 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7166 // one of the above mentioned nodes. It has to be wrapped because otherwise
7167 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7168 // be used to form addressing mode. These wrapped nodes will be selected
7169 // into MOV32ri.
7170 SDValue
7171 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7172   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7173
7174   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7175   // global base reg.
7176   unsigned char OpFlag = 0;
7177   unsigned WrapperKind = X86ISD::Wrapper;
7178   CodeModel::Model M = getTargetMachine().getCodeModel();
7179
7180   if (Subtarget->isPICStyleRIPRel() &&
7181       (M == CodeModel::Small || M == CodeModel::Kernel))
7182     WrapperKind = X86ISD::WrapperRIP;
7183   else if (Subtarget->isPICStyleGOT())
7184     OpFlag = X86II::MO_GOTOFF;
7185   else if (Subtarget->isPICStyleStubPIC())
7186     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7187
7188   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7189                                              CP->getAlignment(),
7190                                              CP->getOffset(), OpFlag);
7191   DebugLoc DL = CP->getDebugLoc();
7192   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7193   // With PIC, the address is actually $g + Offset.
7194   if (OpFlag) {
7195     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7196                          DAG.getNode(X86ISD::GlobalBaseReg,
7197                                      DebugLoc(), getPointerTy()),
7198                          Result);
7199   }
7200
7201   return Result;
7202 }
7203
7204 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7205   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7206
7207   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7208   // global base reg.
7209   unsigned char OpFlag = 0;
7210   unsigned WrapperKind = X86ISD::Wrapper;
7211   CodeModel::Model M = getTargetMachine().getCodeModel();
7212
7213   if (Subtarget->isPICStyleRIPRel() &&
7214       (M == CodeModel::Small || M == CodeModel::Kernel))
7215     WrapperKind = X86ISD::WrapperRIP;
7216   else if (Subtarget->isPICStyleGOT())
7217     OpFlag = X86II::MO_GOTOFF;
7218   else if (Subtarget->isPICStyleStubPIC())
7219     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7220
7221   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7222                                           OpFlag);
7223   DebugLoc DL = JT->getDebugLoc();
7224   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7225
7226   // With PIC, the address is actually $g + Offset.
7227   if (OpFlag)
7228     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7229                          DAG.getNode(X86ISD::GlobalBaseReg,
7230                                      DebugLoc(), getPointerTy()),
7231                          Result);
7232
7233   return Result;
7234 }
7235
7236 SDValue
7237 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7238   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7239
7240   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7241   // global base reg.
7242   unsigned char OpFlag = 0;
7243   unsigned WrapperKind = X86ISD::Wrapper;
7244   CodeModel::Model M = getTargetMachine().getCodeModel();
7245
7246   if (Subtarget->isPICStyleRIPRel() &&
7247       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7248     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7249       OpFlag = X86II::MO_GOTPCREL;
7250     WrapperKind = X86ISD::WrapperRIP;
7251   } else if (Subtarget->isPICStyleGOT()) {
7252     OpFlag = X86II::MO_GOT;
7253   } else if (Subtarget->isPICStyleStubPIC()) {
7254     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7255   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7256     OpFlag = X86II::MO_DARWIN_NONLAZY;
7257   }
7258
7259   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7260
7261   DebugLoc DL = Op.getDebugLoc();
7262   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7263
7264
7265   // With PIC, the address is actually $g + Offset.
7266   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7267       !Subtarget->is64Bit()) {
7268     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7269                          DAG.getNode(X86ISD::GlobalBaseReg,
7270                                      DebugLoc(), getPointerTy()),
7271                          Result);
7272   }
7273
7274   // For symbols that require a load from a stub to get the address, emit the
7275   // load.
7276   if (isGlobalStubReference(OpFlag))
7277     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7278                          MachinePointerInfo::getGOT(), false, false, 0);
7279
7280   return Result;
7281 }
7282
7283 SDValue
7284 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7285   // Create the TargetBlockAddressAddress node.
7286   unsigned char OpFlags =
7287     Subtarget->ClassifyBlockAddressReference();
7288   CodeModel::Model M = getTargetMachine().getCodeModel();
7289   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7290   DebugLoc dl = Op.getDebugLoc();
7291   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7292                                        /*isTarget=*/true, OpFlags);
7293
7294   if (Subtarget->isPICStyleRIPRel() &&
7295       (M == CodeModel::Small || M == CodeModel::Kernel))
7296     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7297   else
7298     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7299
7300   // With PIC, the address is actually $g + Offset.
7301   if (isGlobalRelativeToPICBase(OpFlags)) {
7302     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7303                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7304                          Result);
7305   }
7306
7307   return Result;
7308 }
7309
7310 SDValue
7311 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7312                                       int64_t Offset,
7313                                       SelectionDAG &DAG) const {
7314   // Create the TargetGlobalAddress node, folding in the constant
7315   // offset if it is legal.
7316   unsigned char OpFlags =
7317     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7318   CodeModel::Model M = getTargetMachine().getCodeModel();
7319   SDValue Result;
7320   if (OpFlags == X86II::MO_NO_FLAG &&
7321       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7322     // A direct static reference to a global.
7323     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7324     Offset = 0;
7325   } else {
7326     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7327   }
7328
7329   if (Subtarget->isPICStyleRIPRel() &&
7330       (M == CodeModel::Small || M == CodeModel::Kernel))
7331     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7332   else
7333     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7334
7335   // With PIC, the address is actually $g + Offset.
7336   if (isGlobalRelativeToPICBase(OpFlags)) {
7337     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7338                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7339                          Result);
7340   }
7341
7342   // For globals that require a load from a stub to get the address, emit the
7343   // load.
7344   if (isGlobalStubReference(OpFlags))
7345     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7346                          MachinePointerInfo::getGOT(), false, false, 0);
7347
7348   // If there was a non-zero offset that we didn't fold, create an explicit
7349   // addition for it.
7350   if (Offset != 0)
7351     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7352                          DAG.getConstant(Offset, getPointerTy()));
7353
7354   return Result;
7355 }
7356
7357 SDValue
7358 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7359   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7360   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7361   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7362 }
7363
7364 static SDValue
7365 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7366            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7367            unsigned char OperandFlags) {
7368   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7369   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7370   DebugLoc dl = GA->getDebugLoc();
7371   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7372                                            GA->getValueType(0),
7373                                            GA->getOffset(),
7374                                            OperandFlags);
7375   if (InFlag) {
7376     SDValue Ops[] = { Chain,  TGA, *InFlag };
7377     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7378   } else {
7379     SDValue Ops[]  = { Chain, TGA };
7380     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7381   }
7382
7383   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7384   MFI->setAdjustsStack(true);
7385
7386   SDValue Flag = Chain.getValue(1);
7387   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7388 }
7389
7390 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7391 static SDValue
7392 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7393                                 const EVT PtrVT) {
7394   SDValue InFlag;
7395   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7396   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7397                                      DAG.getNode(X86ISD::GlobalBaseReg,
7398                                                  DebugLoc(), PtrVT), InFlag);
7399   InFlag = Chain.getValue(1);
7400
7401   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7402 }
7403
7404 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7405 static SDValue
7406 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7407                                 const EVT PtrVT) {
7408   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7409                     X86::RAX, X86II::MO_TLSGD);
7410 }
7411
7412 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7413 // "local exec" model.
7414 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7415                                    const EVT PtrVT, TLSModel::Model model,
7416                                    bool is64Bit) {
7417   DebugLoc dl = GA->getDebugLoc();
7418
7419   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7420   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7421                                                          is64Bit ? 257 : 256));
7422
7423   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7424                                       DAG.getIntPtrConstant(0),
7425                                       MachinePointerInfo(Ptr), false, false, 0);
7426
7427   unsigned char OperandFlags = 0;
7428   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7429   // initialexec.
7430   unsigned WrapperKind = X86ISD::Wrapper;
7431   if (model == TLSModel::LocalExec) {
7432     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7433   } else if (is64Bit) {
7434     assert(model == TLSModel::InitialExec);
7435     OperandFlags = X86II::MO_GOTTPOFF;
7436     WrapperKind = X86ISD::WrapperRIP;
7437   } else {
7438     assert(model == TLSModel::InitialExec);
7439     OperandFlags = X86II::MO_INDNTPOFF;
7440   }
7441
7442   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7443   // exec)
7444   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7445                                            GA->getValueType(0),
7446                                            GA->getOffset(), OperandFlags);
7447   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7448
7449   if (model == TLSModel::InitialExec)
7450     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7451                          MachinePointerInfo::getGOT(), false, false, 0);
7452
7453   // The address of the thread local variable is the add of the thread
7454   // pointer with the offset of the variable.
7455   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7456 }
7457
7458 SDValue
7459 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7460
7461   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7462   const GlobalValue *GV = GA->getGlobal();
7463
7464   if (Subtarget->isTargetELF()) {
7465     // TODO: implement the "local dynamic" model
7466     // TODO: implement the "initial exec"model for pic executables
7467
7468     // If GV is an alias then use the aliasee for determining
7469     // thread-localness.
7470     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7471       GV = GA->resolveAliasedGlobal(false);
7472
7473     TLSModel::Model model
7474       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7475
7476     switch (model) {
7477       case TLSModel::GeneralDynamic:
7478       case TLSModel::LocalDynamic: // not implemented
7479         if (Subtarget->is64Bit())
7480           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7481         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7482
7483       case TLSModel::InitialExec:
7484       case TLSModel::LocalExec:
7485         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7486                                    Subtarget->is64Bit());
7487     }
7488   } else if (Subtarget->isTargetDarwin()) {
7489     // Darwin only has one model of TLS.  Lower to that.
7490     unsigned char OpFlag = 0;
7491     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7492                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7493
7494     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7495     // global base reg.
7496     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7497                   !Subtarget->is64Bit();
7498     if (PIC32)
7499       OpFlag = X86II::MO_TLVP_PIC_BASE;
7500     else
7501       OpFlag = X86II::MO_TLVP;
7502     DebugLoc DL = Op.getDebugLoc();
7503     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7504                                                 GA->getValueType(0),
7505                                                 GA->getOffset(), OpFlag);
7506     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7507
7508     // With PIC32, the address is actually $g + Offset.
7509     if (PIC32)
7510       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7511                            DAG.getNode(X86ISD::GlobalBaseReg,
7512                                        DebugLoc(), getPointerTy()),
7513                            Offset);
7514
7515     // Lowering the machine isd will make sure everything is in the right
7516     // location.
7517     SDValue Chain = DAG.getEntryNode();
7518     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7519     SDValue Args[] = { Chain, Offset };
7520     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7521
7522     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7523     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7524     MFI->setAdjustsStack(true);
7525
7526     // And our return value (tls address) is in the standard call return value
7527     // location.
7528     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7529     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
7530   }
7531
7532   assert(false &&
7533          "TLS not implemented for this target.");
7534
7535   llvm_unreachable("Unreachable");
7536   return SDValue();
7537 }
7538
7539
7540 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7541 /// take a 2 x i32 value to shift plus a shift amount.
7542 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7543   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7544   EVT VT = Op.getValueType();
7545   unsigned VTBits = VT.getSizeInBits();
7546   DebugLoc dl = Op.getDebugLoc();
7547   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7548   SDValue ShOpLo = Op.getOperand(0);
7549   SDValue ShOpHi = Op.getOperand(1);
7550   SDValue ShAmt  = Op.getOperand(2);
7551   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7552                                      DAG.getConstant(VTBits - 1, MVT::i8))
7553                        : DAG.getConstant(0, VT);
7554
7555   SDValue Tmp2, Tmp3;
7556   if (Op.getOpcode() == ISD::SHL_PARTS) {
7557     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7558     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7559   } else {
7560     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7561     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7562   }
7563
7564   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7565                                 DAG.getConstant(VTBits, MVT::i8));
7566   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7567                              AndNode, DAG.getConstant(0, MVT::i8));
7568
7569   SDValue Hi, Lo;
7570   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7571   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7572   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7573
7574   if (Op.getOpcode() == ISD::SHL_PARTS) {
7575     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7576     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7577   } else {
7578     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7579     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7580   }
7581
7582   SDValue Ops[2] = { Lo, Hi };
7583   return DAG.getMergeValues(Ops, 2, dl);
7584 }
7585
7586 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7587                                            SelectionDAG &DAG) const {
7588   EVT SrcVT = Op.getOperand(0).getValueType();
7589
7590   if (SrcVT.isVector())
7591     return SDValue();
7592
7593   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7594          "Unknown SINT_TO_FP to lower!");
7595
7596   // These are really Legal; return the operand so the caller accepts it as
7597   // Legal.
7598   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7599     return Op;
7600   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7601       Subtarget->is64Bit()) {
7602     return Op;
7603   }
7604
7605   DebugLoc dl = Op.getDebugLoc();
7606   unsigned Size = SrcVT.getSizeInBits()/8;
7607   MachineFunction &MF = DAG.getMachineFunction();
7608   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7609   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7610   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7611                                StackSlot,
7612                                MachinePointerInfo::getFixedStack(SSFI),
7613                                false, false, 0);
7614   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7615 }
7616
7617 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7618                                      SDValue StackSlot,
7619                                      SelectionDAG &DAG) const {
7620   // Build the FILD
7621   DebugLoc DL = Op.getDebugLoc();
7622   SDVTList Tys;
7623   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7624   if (useSSE)
7625     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7626   else
7627     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7628
7629   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7630
7631   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7632   MachineMemOperand *MMO;
7633   if (FI) {
7634     int SSFI = FI->getIndex();
7635     MMO =
7636       DAG.getMachineFunction()
7637       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7638                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7639   } else {
7640     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7641     StackSlot = StackSlot.getOperand(1);
7642   }
7643   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7644   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7645                                            X86ISD::FILD, DL,
7646                                            Tys, Ops, array_lengthof(Ops),
7647                                            SrcVT, MMO);
7648
7649   if (useSSE) {
7650     Chain = Result.getValue(1);
7651     SDValue InFlag = Result.getValue(2);
7652
7653     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7654     // shouldn't be necessary except that RFP cannot be live across
7655     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7656     MachineFunction &MF = DAG.getMachineFunction();
7657     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7658     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7659     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7660     Tys = DAG.getVTList(MVT::Other);
7661     SDValue Ops[] = {
7662       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7663     };
7664     MachineMemOperand *MMO =
7665       DAG.getMachineFunction()
7666       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7667                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7668
7669     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7670                                     Ops, array_lengthof(Ops),
7671                                     Op.getValueType(), MMO);
7672     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7673                          MachinePointerInfo::getFixedStack(SSFI),
7674                          false, false, 0);
7675   }
7676
7677   return Result;
7678 }
7679
7680 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7681 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7682                                                SelectionDAG &DAG) const {
7683   // This algorithm is not obvious. Here it is in C code, more or less:
7684   /*
7685     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7686       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7687       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7688
7689       // Copy ints to xmm registers.
7690       __m128i xh = _mm_cvtsi32_si128( hi );
7691       __m128i xl = _mm_cvtsi32_si128( lo );
7692
7693       // Combine into low half of a single xmm register.
7694       __m128i x = _mm_unpacklo_epi32( xh, xl );
7695       __m128d d;
7696       double sd;
7697
7698       // Merge in appropriate exponents to give the integer bits the right
7699       // magnitude.
7700       x = _mm_unpacklo_epi32( x, exp );
7701
7702       // Subtract away the biases to deal with the IEEE-754 double precision
7703       // implicit 1.
7704       d = _mm_sub_pd( (__m128d) x, bias );
7705
7706       // All conversions up to here are exact. The correctly rounded result is
7707       // calculated using the current rounding mode using the following
7708       // horizontal add.
7709       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7710       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7711                                 // store doesn't really need to be here (except
7712                                 // maybe to zero the other double)
7713       return sd;
7714     }
7715   */
7716
7717   DebugLoc dl = Op.getDebugLoc();
7718   LLVMContext *Context = DAG.getContext();
7719
7720   // Build some magic constants.
7721   std::vector<Constant*> CV0;
7722   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7723   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7724   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7725   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7726   Constant *C0 = ConstantVector::get(CV0);
7727   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7728
7729   std::vector<Constant*> CV1;
7730   CV1.push_back(
7731     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7732   CV1.push_back(
7733     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7734   Constant *C1 = ConstantVector::get(CV1);
7735   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7736
7737   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7738                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7739                                         Op.getOperand(0),
7740                                         DAG.getIntPtrConstant(1)));
7741   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7742                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7743                                         Op.getOperand(0),
7744                                         DAG.getIntPtrConstant(0)));
7745   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7746   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7747                               MachinePointerInfo::getConstantPool(),
7748                               false, false, 16);
7749   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7750   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7751   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7752                               MachinePointerInfo::getConstantPool(),
7753                               false, false, 16);
7754   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7755
7756   // Add the halves; easiest way is to swap them into another reg first.
7757   int ShufMask[2] = { 1, -1 };
7758   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7759                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7760   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7761   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7762                      DAG.getIntPtrConstant(0));
7763 }
7764
7765 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7766 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7767                                                SelectionDAG &DAG) const {
7768   DebugLoc dl = Op.getDebugLoc();
7769   // FP constant to bias correct the final result.
7770   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7771                                    MVT::f64);
7772
7773   // Load the 32-bit value into an XMM register.
7774   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7775                              Op.getOperand(0));
7776
7777   // Zero out the upper parts of the register.
7778   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7779                                      DAG);
7780
7781   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7782                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7783                      DAG.getIntPtrConstant(0));
7784
7785   // Or the load with the bias.
7786   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7787                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7788                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7789                                                    MVT::v2f64, Load)),
7790                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7791                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7792                                                    MVT::v2f64, Bias)));
7793   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7794                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7795                    DAG.getIntPtrConstant(0));
7796
7797   // Subtract the bias.
7798   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7799
7800   // Handle final rounding.
7801   EVT DestVT = Op.getValueType();
7802
7803   if (DestVT.bitsLT(MVT::f64)) {
7804     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7805                        DAG.getIntPtrConstant(0));
7806   } else if (DestVT.bitsGT(MVT::f64)) {
7807     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7808   }
7809
7810   // Handle final rounding.
7811   return Sub;
7812 }
7813
7814 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7815                                            SelectionDAG &DAG) const {
7816   SDValue N0 = Op.getOperand(0);
7817   DebugLoc dl = Op.getDebugLoc();
7818
7819   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7820   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7821   // the optimization here.
7822   if (DAG.SignBitIsZero(N0))
7823     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7824
7825   EVT SrcVT = N0.getValueType();
7826   EVT DstVT = Op.getValueType();
7827   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7828     return LowerUINT_TO_FP_i64(Op, DAG);
7829   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7830     return LowerUINT_TO_FP_i32(Op, DAG);
7831
7832   // Make a 64-bit buffer, and use it to build an FILD.
7833   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7834   if (SrcVT == MVT::i32) {
7835     SDValue WordOff = DAG.getConstant(4, getPointerTy());
7836     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7837                                      getPointerTy(), StackSlot, WordOff);
7838     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7839                                   StackSlot, MachinePointerInfo(),
7840                                   false, false, 0);
7841     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7842                                   OffsetSlot, MachinePointerInfo(),
7843                                   false, false, 0);
7844     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7845     return Fild;
7846   }
7847
7848   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7849   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7850                                 StackSlot, MachinePointerInfo(),
7851                                false, false, 0);
7852   // For i64 source, we need to add the appropriate power of 2 if the input
7853   // was negative.  This is the same as the optimization in
7854   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7855   // we must be careful to do the computation in x87 extended precision, not
7856   // in SSE. (The generic code can't know it's OK to do this, or how to.)
7857   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7858   MachineMemOperand *MMO =
7859     DAG.getMachineFunction()
7860     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7861                           MachineMemOperand::MOLoad, 8, 8);
7862
7863   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7864   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7865   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7866                                          MVT::i64, MMO);
7867
7868   APInt FF(32, 0x5F800000ULL);
7869
7870   // Check whether the sign bit is set.
7871   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7872                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7873                                  ISD::SETLT);
7874
7875   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7876   SDValue FudgePtr = DAG.getConstantPool(
7877                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7878                                          getPointerTy());
7879
7880   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7881   SDValue Zero = DAG.getIntPtrConstant(0);
7882   SDValue Four = DAG.getIntPtrConstant(4);
7883   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7884                                Zero, Four);
7885   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7886
7887   // Load the value out, extending it from f32 to f80.
7888   // FIXME: Avoid the extend by constructing the right constant pool?
7889   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7890                                  FudgePtr, MachinePointerInfo::getConstantPool(),
7891                                  MVT::f32, false, false, 4);
7892   // Extend everything to 80 bits to force it to be done on x87.
7893   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7894   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7895 }
7896
7897 std::pair<SDValue,SDValue> X86TargetLowering::
7898 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
7899   DebugLoc DL = Op.getDebugLoc();
7900
7901   EVT DstTy = Op.getValueType();
7902
7903   if (!IsSigned) {
7904     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7905     DstTy = MVT::i64;
7906   }
7907
7908   assert(DstTy.getSimpleVT() <= MVT::i64 &&
7909          DstTy.getSimpleVT() >= MVT::i16 &&
7910          "Unknown FP_TO_SINT to lower!");
7911
7912   // These are really Legal.
7913   if (DstTy == MVT::i32 &&
7914       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7915     return std::make_pair(SDValue(), SDValue());
7916   if (Subtarget->is64Bit() &&
7917       DstTy == MVT::i64 &&
7918       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7919     return std::make_pair(SDValue(), SDValue());
7920
7921   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
7922   // stack slot.
7923   MachineFunction &MF = DAG.getMachineFunction();
7924   unsigned MemSize = DstTy.getSizeInBits()/8;
7925   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7926   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7927
7928
7929
7930   unsigned Opc;
7931   switch (DstTy.getSimpleVT().SimpleTy) {
7932   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7933   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7934   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7935   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7936   }
7937
7938   SDValue Chain = DAG.getEntryNode();
7939   SDValue Value = Op.getOperand(0);
7940   EVT TheVT = Op.getOperand(0).getValueType();
7941   if (isScalarFPTypeInSSEReg(TheVT)) {
7942     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7943     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7944                          MachinePointerInfo::getFixedStack(SSFI),
7945                          false, false, 0);
7946     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7947     SDValue Ops[] = {
7948       Chain, StackSlot, DAG.getValueType(TheVT)
7949     };
7950
7951     MachineMemOperand *MMO =
7952       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7953                               MachineMemOperand::MOLoad, MemSize, MemSize);
7954     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7955                                     DstTy, MMO);
7956     Chain = Value.getValue(1);
7957     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7958     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7959   }
7960
7961   MachineMemOperand *MMO =
7962     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7963                             MachineMemOperand::MOStore, MemSize, MemSize);
7964
7965   // Build the FP_TO_INT*_IN_MEM
7966   SDValue Ops[] = { Chain, Value, StackSlot };
7967   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7968                                          Ops, 3, DstTy, MMO);
7969
7970   return std::make_pair(FIST, StackSlot);
7971 }
7972
7973 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7974                                            SelectionDAG &DAG) const {
7975   if (Op.getValueType().isVector())
7976     return SDValue();
7977
7978   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
7979   SDValue FIST = Vals.first, StackSlot = Vals.second;
7980   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7981   if (FIST.getNode() == 0) return Op;
7982
7983   // Load the result.
7984   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7985                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7986 }
7987
7988 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7989                                            SelectionDAG &DAG) const {
7990   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
7991   SDValue FIST = Vals.first, StackSlot = Vals.second;
7992   assert(FIST.getNode() && "Unexpected failure");
7993
7994   // Load the result.
7995   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7996                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
7997 }
7998
7999 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8000                                      SelectionDAG &DAG) const {
8001   LLVMContext *Context = DAG.getContext();
8002   DebugLoc dl = Op.getDebugLoc();
8003   EVT VT = Op.getValueType();
8004   EVT EltVT = VT;
8005   if (VT.isVector())
8006     EltVT = VT.getVectorElementType();
8007   std::vector<Constant*> CV;
8008   if (EltVT == MVT::f64) {
8009     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8010     CV.push_back(C);
8011     CV.push_back(C);
8012   } else {
8013     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8014     CV.push_back(C);
8015     CV.push_back(C);
8016     CV.push_back(C);
8017     CV.push_back(C);
8018   }
8019   Constant *C = ConstantVector::get(CV);
8020   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8021   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8022                              MachinePointerInfo::getConstantPool(),
8023                              false, false, 16);
8024   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8025 }
8026
8027 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8028   LLVMContext *Context = DAG.getContext();
8029   DebugLoc dl = Op.getDebugLoc();
8030   EVT VT = Op.getValueType();
8031   EVT EltVT = VT;
8032   if (VT.isVector())
8033     EltVT = VT.getVectorElementType();
8034   std::vector<Constant*> CV;
8035   if (EltVT == MVT::f64) {
8036     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8037     CV.push_back(C);
8038     CV.push_back(C);
8039   } else {
8040     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8041     CV.push_back(C);
8042     CV.push_back(C);
8043     CV.push_back(C);
8044     CV.push_back(C);
8045   }
8046   Constant *C = ConstantVector::get(CV);
8047   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8048   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8049                              MachinePointerInfo::getConstantPool(),
8050                              false, false, 16);
8051   if (VT.isVector()) {
8052     return DAG.getNode(ISD::BITCAST, dl, VT,
8053                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8054                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8055                                 Op.getOperand(0)),
8056                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8057   } else {
8058     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8059   }
8060 }
8061
8062 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8063   LLVMContext *Context = DAG.getContext();
8064   SDValue Op0 = Op.getOperand(0);
8065   SDValue Op1 = Op.getOperand(1);
8066   DebugLoc dl = Op.getDebugLoc();
8067   EVT VT = Op.getValueType();
8068   EVT SrcVT = Op1.getValueType();
8069
8070   // If second operand is smaller, extend it first.
8071   if (SrcVT.bitsLT(VT)) {
8072     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8073     SrcVT = VT;
8074   }
8075   // And if it is bigger, shrink it first.
8076   if (SrcVT.bitsGT(VT)) {
8077     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8078     SrcVT = VT;
8079   }
8080
8081   // At this point the operands and the result should have the same
8082   // type, and that won't be f80 since that is not custom lowered.
8083
8084   // First get the sign bit of second operand.
8085   std::vector<Constant*> CV;
8086   if (SrcVT == MVT::f64) {
8087     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8088     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8089   } else {
8090     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8091     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8092     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8093     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8094   }
8095   Constant *C = ConstantVector::get(CV);
8096   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8097   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8098                               MachinePointerInfo::getConstantPool(),
8099                               false, false, 16);
8100   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8101
8102   // Shift sign bit right or left if the two operands have different types.
8103   if (SrcVT.bitsGT(VT)) {
8104     // Op0 is MVT::f32, Op1 is MVT::f64.
8105     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8106     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8107                           DAG.getConstant(32, MVT::i32));
8108     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8109     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8110                           DAG.getIntPtrConstant(0));
8111   }
8112
8113   // Clear first operand sign bit.
8114   CV.clear();
8115   if (VT == MVT::f64) {
8116     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8117     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8118   } else {
8119     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8120     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8121     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8122     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8123   }
8124   C = ConstantVector::get(CV);
8125   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8126   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8127                               MachinePointerInfo::getConstantPool(),
8128                               false, false, 16);
8129   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8130
8131   // Or the value with the sign bit.
8132   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8133 }
8134
8135 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8136   SDValue N0 = Op.getOperand(0);
8137   DebugLoc dl = Op.getDebugLoc();
8138   EVT VT = Op.getValueType();
8139
8140   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8141   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8142                                   DAG.getConstant(1, VT));
8143   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8144 }
8145
8146 /// Emit nodes that will be selected as "test Op0,Op0", or something
8147 /// equivalent.
8148 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8149                                     SelectionDAG &DAG) const {
8150   DebugLoc dl = Op.getDebugLoc();
8151
8152   // CF and OF aren't always set the way we want. Determine which
8153   // of these we need.
8154   bool NeedCF = false;
8155   bool NeedOF = false;
8156   switch (X86CC) {
8157   default: break;
8158   case X86::COND_A: case X86::COND_AE:
8159   case X86::COND_B: case X86::COND_BE:
8160     NeedCF = true;
8161     break;
8162   case X86::COND_G: case X86::COND_GE:
8163   case X86::COND_L: case X86::COND_LE:
8164   case X86::COND_O: case X86::COND_NO:
8165     NeedOF = true;
8166     break;
8167   }
8168
8169   // See if we can use the EFLAGS value from the operand instead of
8170   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8171   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8172   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8173     // Emit a CMP with 0, which is the TEST pattern.
8174     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8175                        DAG.getConstant(0, Op.getValueType()));
8176
8177   unsigned Opcode = 0;
8178   unsigned NumOperands = 0;
8179   switch (Op.getNode()->getOpcode()) {
8180   case ISD::ADD:
8181     // Due to an isel shortcoming, be conservative if this add is likely to be
8182     // selected as part of a load-modify-store instruction. When the root node
8183     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8184     // uses of other nodes in the match, such as the ADD in this case. This
8185     // leads to the ADD being left around and reselected, with the result being
8186     // two adds in the output.  Alas, even if none our users are stores, that
8187     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8188     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8189     // climbing the DAG back to the root, and it doesn't seem to be worth the
8190     // effort.
8191     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8192            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8193       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
8194         goto default_case;
8195
8196     if (ConstantSDNode *C =
8197         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8198       // An add of one will be selected as an INC.
8199       if (C->getAPIntValue() == 1) {
8200         Opcode = X86ISD::INC;
8201         NumOperands = 1;
8202         break;
8203       }
8204
8205       // An add of negative one (subtract of one) will be selected as a DEC.
8206       if (C->getAPIntValue().isAllOnesValue()) {
8207         Opcode = X86ISD::DEC;
8208         NumOperands = 1;
8209         break;
8210       }
8211     }
8212
8213     // Otherwise use a regular EFLAGS-setting add.
8214     Opcode = X86ISD::ADD;
8215     NumOperands = 2;
8216     break;
8217   case ISD::AND: {
8218     // If the primary and result isn't used, don't bother using X86ISD::AND,
8219     // because a TEST instruction will be better.
8220     bool NonFlagUse = false;
8221     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8222            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8223       SDNode *User = *UI;
8224       unsigned UOpNo = UI.getOperandNo();
8225       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8226         // Look pass truncate.
8227         UOpNo = User->use_begin().getOperandNo();
8228         User = *User->use_begin();
8229       }
8230
8231       if (User->getOpcode() != ISD::BRCOND &&
8232           User->getOpcode() != ISD::SETCC &&
8233           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8234         NonFlagUse = true;
8235         break;
8236       }
8237     }
8238
8239     if (!NonFlagUse)
8240       break;
8241   }
8242     // FALL THROUGH
8243   case ISD::SUB:
8244   case ISD::OR:
8245   case ISD::XOR:
8246     // Due to the ISEL shortcoming noted above, be conservative if this op is
8247     // likely to be selected as part of a load-modify-store instruction.
8248     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8249            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8250       if (UI->getOpcode() == ISD::STORE)
8251         goto default_case;
8252
8253     // Otherwise use a regular EFLAGS-setting instruction.
8254     switch (Op.getNode()->getOpcode()) {
8255     default: llvm_unreachable("unexpected operator!");
8256     case ISD::SUB: Opcode = X86ISD::SUB; break;
8257     case ISD::OR:  Opcode = X86ISD::OR;  break;
8258     case ISD::XOR: Opcode = X86ISD::XOR; break;
8259     case ISD::AND: Opcode = X86ISD::AND; break;
8260     }
8261
8262     NumOperands = 2;
8263     break;
8264   case X86ISD::ADD:
8265   case X86ISD::SUB:
8266   case X86ISD::INC:
8267   case X86ISD::DEC:
8268   case X86ISD::OR:
8269   case X86ISD::XOR:
8270   case X86ISD::AND:
8271     return SDValue(Op.getNode(), 1);
8272   default:
8273   default_case:
8274     break;
8275   }
8276
8277   if (Opcode == 0)
8278     // Emit a CMP with 0, which is the TEST pattern.
8279     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8280                        DAG.getConstant(0, Op.getValueType()));
8281
8282   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8283   SmallVector<SDValue, 4> Ops;
8284   for (unsigned i = 0; i != NumOperands; ++i)
8285     Ops.push_back(Op.getOperand(i));
8286
8287   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8288   DAG.ReplaceAllUsesWith(Op, New);
8289   return SDValue(New.getNode(), 1);
8290 }
8291
8292 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8293 /// equivalent.
8294 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8295                                    SelectionDAG &DAG) const {
8296   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8297     if (C->getAPIntValue() == 0)
8298       return EmitTest(Op0, X86CC, DAG);
8299
8300   DebugLoc dl = Op0.getDebugLoc();
8301   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8302 }
8303
8304 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8305 /// if it's possible.
8306 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8307                                      DebugLoc dl, SelectionDAG &DAG) const {
8308   SDValue Op0 = And.getOperand(0);
8309   SDValue Op1 = And.getOperand(1);
8310   if (Op0.getOpcode() == ISD::TRUNCATE)
8311     Op0 = Op0.getOperand(0);
8312   if (Op1.getOpcode() == ISD::TRUNCATE)
8313     Op1 = Op1.getOperand(0);
8314
8315   SDValue LHS, RHS;
8316   if (Op1.getOpcode() == ISD::SHL)
8317     std::swap(Op0, Op1);
8318   if (Op0.getOpcode() == ISD::SHL) {
8319     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8320       if (And00C->getZExtValue() == 1) {
8321         // If we looked past a truncate, check that it's only truncating away
8322         // known zeros.
8323         unsigned BitWidth = Op0.getValueSizeInBits();
8324         unsigned AndBitWidth = And.getValueSizeInBits();
8325         if (BitWidth > AndBitWidth) {
8326           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8327           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8328           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8329             return SDValue();
8330         }
8331         LHS = Op1;
8332         RHS = Op0.getOperand(1);
8333       }
8334   } else if (Op1.getOpcode() == ISD::Constant) {
8335     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8336     SDValue AndLHS = Op0;
8337     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8338       LHS = AndLHS.getOperand(0);
8339       RHS = AndLHS.getOperand(1);
8340     }
8341   }
8342
8343   if (LHS.getNode()) {
8344     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8345     // instruction.  Since the shift amount is in-range-or-undefined, we know
8346     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8347     // the encoding for the i16 version is larger than the i32 version.
8348     // Also promote i16 to i32 for performance / code size reason.
8349     if (LHS.getValueType() == MVT::i8 ||
8350         LHS.getValueType() == MVT::i16)
8351       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8352
8353     // If the operand types disagree, extend the shift amount to match.  Since
8354     // BT ignores high bits (like shifts) we can use anyextend.
8355     if (LHS.getValueType() != RHS.getValueType())
8356       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8357
8358     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8359     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8360     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8361                        DAG.getConstant(Cond, MVT::i8), BT);
8362   }
8363
8364   return SDValue();
8365 }
8366
8367 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8368
8369   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8370
8371   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8372   SDValue Op0 = Op.getOperand(0);
8373   SDValue Op1 = Op.getOperand(1);
8374   DebugLoc dl = Op.getDebugLoc();
8375   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8376
8377   // Optimize to BT if possible.
8378   // Lower (X & (1 << N)) == 0 to BT(X, N).
8379   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8380   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8381   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8382       Op1.getOpcode() == ISD::Constant &&
8383       cast<ConstantSDNode>(Op1)->isNullValue() &&
8384       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8385     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8386     if (NewSetCC.getNode())
8387       return NewSetCC;
8388   }
8389
8390   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8391   // these.
8392   if (Op1.getOpcode() == ISD::Constant &&
8393       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8394        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8395       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8396
8397     // If the input is a setcc, then reuse the input setcc or use a new one with
8398     // the inverted condition.
8399     if (Op0.getOpcode() == X86ISD::SETCC) {
8400       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8401       bool Invert = (CC == ISD::SETNE) ^
8402         cast<ConstantSDNode>(Op1)->isNullValue();
8403       if (!Invert) return Op0;
8404
8405       CCode = X86::GetOppositeBranchCondition(CCode);
8406       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8407                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8408     }
8409   }
8410
8411   bool isFP = Op1.getValueType().isFloatingPoint();
8412   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8413   if (X86CC == X86::COND_INVALID)
8414     return SDValue();
8415
8416   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8417   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8418                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8419 }
8420
8421 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8422 // ones, and then concatenate the result back.
8423 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8424   EVT VT = Op.getValueType();
8425
8426   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8427          "Unsupported value type for operation");
8428
8429   int NumElems = VT.getVectorNumElements();
8430   DebugLoc dl = Op.getDebugLoc();
8431   SDValue CC = Op.getOperand(2);
8432   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8433   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8434
8435   // Extract the LHS vectors
8436   SDValue LHS = Op.getOperand(0);
8437   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8438   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8439
8440   // Extract the RHS vectors
8441   SDValue RHS = Op.getOperand(1);
8442   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8443   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8444
8445   // Issue the operation on the smaller types and concatenate the result back
8446   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8447   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8448   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8449                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8450                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8451 }
8452
8453
8454 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8455   SDValue Cond;
8456   SDValue Op0 = Op.getOperand(0);
8457   SDValue Op1 = Op.getOperand(1);
8458   SDValue CC = Op.getOperand(2);
8459   EVT VT = Op.getValueType();
8460   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8461   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8462   DebugLoc dl = Op.getDebugLoc();
8463
8464   if (isFP) {
8465     unsigned SSECC = 8;
8466     EVT EltVT = Op0.getValueType().getVectorElementType();
8467     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8468
8469     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8470     bool Swap = false;
8471
8472     // SSE Condition code mapping:
8473     //  0 - EQ
8474     //  1 - LT
8475     //  2 - LE
8476     //  3 - UNORD
8477     //  4 - NEQ
8478     //  5 - NLT
8479     //  6 - NLE
8480     //  7 - ORD
8481     switch (SetCCOpcode) {
8482     default: break;
8483     case ISD::SETOEQ:
8484     case ISD::SETEQ:  SSECC = 0; break;
8485     case ISD::SETOGT:
8486     case ISD::SETGT: Swap = true; // Fallthrough
8487     case ISD::SETLT:
8488     case ISD::SETOLT: SSECC = 1; break;
8489     case ISD::SETOGE:
8490     case ISD::SETGE: Swap = true; // Fallthrough
8491     case ISD::SETLE:
8492     case ISD::SETOLE: SSECC = 2; break;
8493     case ISD::SETUO:  SSECC = 3; break;
8494     case ISD::SETUNE:
8495     case ISD::SETNE:  SSECC = 4; break;
8496     case ISD::SETULE: Swap = true;
8497     case ISD::SETUGE: SSECC = 5; break;
8498     case ISD::SETULT: Swap = true;
8499     case ISD::SETUGT: SSECC = 6; break;
8500     case ISD::SETO:   SSECC = 7; break;
8501     }
8502     if (Swap)
8503       std::swap(Op0, Op1);
8504
8505     // In the two special cases we can't handle, emit two comparisons.
8506     if (SSECC == 8) {
8507       if (SetCCOpcode == ISD::SETUEQ) {
8508         SDValue UNORD, EQ;
8509         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8510         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8511         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8512       }
8513       else if (SetCCOpcode == ISD::SETONE) {
8514         SDValue ORD, NEQ;
8515         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8516         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8517         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8518       }
8519       llvm_unreachable("Illegal FP comparison");
8520     }
8521     // Handle all other FP comparisons here.
8522     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8523   }
8524
8525   // Break 256-bit integer vector compare into smaller ones.
8526   if (!isFP && VT.getSizeInBits() == 256)
8527     return Lower256IntVSETCC(Op, DAG);
8528
8529   // We are handling one of the integer comparisons here.  Since SSE only has
8530   // GT and EQ comparisons for integer, swapping operands and multiple
8531   // operations may be required for some comparisons.
8532   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8533   bool Swap = false, Invert = false, FlipSigns = false;
8534
8535   switch (VT.getSimpleVT().SimpleTy) {
8536   default: break;
8537   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8538   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8539   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8540   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8541   }
8542
8543   switch (SetCCOpcode) {
8544   default: break;
8545   case ISD::SETNE:  Invert = true;
8546   case ISD::SETEQ:  Opc = EQOpc; break;
8547   case ISD::SETLT:  Swap = true;
8548   case ISD::SETGT:  Opc = GTOpc; break;
8549   case ISD::SETGE:  Swap = true;
8550   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8551   case ISD::SETULT: Swap = true;
8552   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8553   case ISD::SETUGE: Swap = true;
8554   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8555   }
8556   if (Swap)
8557     std::swap(Op0, Op1);
8558
8559   // Check that the operation in question is available (most are plain SSE2,
8560   // but PCMPGTQ and PCMPEQQ have different requirements).
8561   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8562     return SDValue();
8563   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8564     return SDValue();
8565
8566   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8567   // bits of the inputs before performing those operations.
8568   if (FlipSigns) {
8569     EVT EltVT = VT.getVectorElementType();
8570     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8571                                       EltVT);
8572     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8573     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8574                                     SignBits.size());
8575     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8576     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8577   }
8578
8579   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8580
8581   // If the logical-not of the result is required, perform that now.
8582   if (Invert)
8583     Result = DAG.getNOT(dl, Result, VT);
8584
8585   return Result;
8586 }
8587
8588 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8589 static bool isX86LogicalCmp(SDValue Op) {
8590   unsigned Opc = Op.getNode()->getOpcode();
8591   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8592     return true;
8593   if (Op.getResNo() == 1 &&
8594       (Opc == X86ISD::ADD ||
8595        Opc == X86ISD::SUB ||
8596        Opc == X86ISD::ADC ||
8597        Opc == X86ISD::SBB ||
8598        Opc == X86ISD::SMUL ||
8599        Opc == X86ISD::UMUL ||
8600        Opc == X86ISD::INC ||
8601        Opc == X86ISD::DEC ||
8602        Opc == X86ISD::OR ||
8603        Opc == X86ISD::XOR ||
8604        Opc == X86ISD::AND))
8605     return true;
8606
8607   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8608     return true;
8609
8610   return false;
8611 }
8612
8613 static bool isZero(SDValue V) {
8614   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8615   return C && C->isNullValue();
8616 }
8617
8618 static bool isAllOnes(SDValue V) {
8619   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8620   return C && C->isAllOnesValue();
8621 }
8622
8623 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8624   bool addTest = true;
8625   SDValue Cond  = Op.getOperand(0);
8626   SDValue Op1 = Op.getOperand(1);
8627   SDValue Op2 = Op.getOperand(2);
8628   DebugLoc DL = Op.getDebugLoc();
8629   SDValue CC;
8630
8631   if (Cond.getOpcode() == ISD::SETCC) {
8632     SDValue NewCond = LowerSETCC(Cond, DAG);
8633     if (NewCond.getNode())
8634       Cond = NewCond;
8635   }
8636
8637   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8638   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8639   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8640   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8641   if (Cond.getOpcode() == X86ISD::SETCC &&
8642       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8643       isZero(Cond.getOperand(1).getOperand(1))) {
8644     SDValue Cmp = Cond.getOperand(1);
8645
8646     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8647
8648     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8649         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8650       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8651
8652       SDValue CmpOp0 = Cmp.getOperand(0);
8653       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8654                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8655
8656       SDValue Res =   // Res = 0 or -1.
8657         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8658                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8659
8660       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8661         Res = DAG.getNOT(DL, Res, Res.getValueType());
8662
8663       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8664       if (N2C == 0 || !N2C->isNullValue())
8665         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8666       return Res;
8667     }
8668   }
8669
8670   // Look past (and (setcc_carry (cmp ...)), 1).
8671   if (Cond.getOpcode() == ISD::AND &&
8672       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8673     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8674     if (C && C->getAPIntValue() == 1)
8675       Cond = Cond.getOperand(0);
8676   }
8677
8678   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8679   // setting operand in place of the X86ISD::SETCC.
8680   if (Cond.getOpcode() == X86ISD::SETCC ||
8681       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8682     CC = Cond.getOperand(0);
8683
8684     SDValue Cmp = Cond.getOperand(1);
8685     unsigned Opc = Cmp.getOpcode();
8686     EVT VT = Op.getValueType();
8687
8688     bool IllegalFPCMov = false;
8689     if (VT.isFloatingPoint() && !VT.isVector() &&
8690         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8691       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8692
8693     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8694         Opc == X86ISD::BT) { // FIXME
8695       Cond = Cmp;
8696       addTest = false;
8697     }
8698   }
8699
8700   if (addTest) {
8701     // Look pass the truncate.
8702     if (Cond.getOpcode() == ISD::TRUNCATE)
8703       Cond = Cond.getOperand(0);
8704
8705     // We know the result of AND is compared against zero. Try to match
8706     // it to BT.
8707     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8708       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8709       if (NewSetCC.getNode()) {
8710         CC = NewSetCC.getOperand(0);
8711         Cond = NewSetCC.getOperand(1);
8712         addTest = false;
8713       }
8714     }
8715   }
8716
8717   if (addTest) {
8718     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8719     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8720   }
8721
8722   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8723   // a <  b ?  0 : -1 -> RES = setcc_carry
8724   // a >= b ? -1 :  0 -> RES = setcc_carry
8725   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8726   if (Cond.getOpcode() == X86ISD::CMP) {
8727     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8728
8729     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8730         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8731       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8732                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8733       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8734         return DAG.getNOT(DL, Res, Res.getValueType());
8735       return Res;
8736     }
8737   }
8738
8739   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8740   // condition is true.
8741   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8742   SDValue Ops[] = { Op2, Op1, CC, Cond };
8743   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8744 }
8745
8746 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8747 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8748 // from the AND / OR.
8749 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8750   Opc = Op.getOpcode();
8751   if (Opc != ISD::OR && Opc != ISD::AND)
8752     return false;
8753   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8754           Op.getOperand(0).hasOneUse() &&
8755           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8756           Op.getOperand(1).hasOneUse());
8757 }
8758
8759 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8760 // 1 and that the SETCC node has a single use.
8761 static bool isXor1OfSetCC(SDValue Op) {
8762   if (Op.getOpcode() != ISD::XOR)
8763     return false;
8764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8765   if (N1C && N1C->getAPIntValue() == 1) {
8766     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8767       Op.getOperand(0).hasOneUse();
8768   }
8769   return false;
8770 }
8771
8772 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8773   bool addTest = true;
8774   SDValue Chain = Op.getOperand(0);
8775   SDValue Cond  = Op.getOperand(1);
8776   SDValue Dest  = Op.getOperand(2);
8777   DebugLoc dl = Op.getDebugLoc();
8778   SDValue CC;
8779
8780   if (Cond.getOpcode() == ISD::SETCC) {
8781     SDValue NewCond = LowerSETCC(Cond, DAG);
8782     if (NewCond.getNode())
8783       Cond = NewCond;
8784   }
8785 #if 0
8786   // FIXME: LowerXALUO doesn't handle these!!
8787   else if (Cond.getOpcode() == X86ISD::ADD  ||
8788            Cond.getOpcode() == X86ISD::SUB  ||
8789            Cond.getOpcode() == X86ISD::SMUL ||
8790            Cond.getOpcode() == X86ISD::UMUL)
8791     Cond = LowerXALUO(Cond, DAG);
8792 #endif
8793
8794   // Look pass (and (setcc_carry (cmp ...)), 1).
8795   if (Cond.getOpcode() == ISD::AND &&
8796       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8797     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8798     if (C && C->getAPIntValue() == 1)
8799       Cond = Cond.getOperand(0);
8800   }
8801
8802   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8803   // setting operand in place of the X86ISD::SETCC.
8804   if (Cond.getOpcode() == X86ISD::SETCC ||
8805       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
8806     CC = Cond.getOperand(0);
8807
8808     SDValue Cmp = Cond.getOperand(1);
8809     unsigned Opc = Cmp.getOpcode();
8810     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8811     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8812       Cond = Cmp;
8813       addTest = false;
8814     } else {
8815       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8816       default: break;
8817       case X86::COND_O:
8818       case X86::COND_B:
8819         // These can only come from an arithmetic instruction with overflow,
8820         // e.g. SADDO, UADDO.
8821         Cond = Cond.getNode()->getOperand(1);
8822         addTest = false;
8823         break;
8824       }
8825     }
8826   } else {
8827     unsigned CondOpc;
8828     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8829       SDValue Cmp = Cond.getOperand(0).getOperand(1);
8830       if (CondOpc == ISD::OR) {
8831         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8832         // two branches instead of an explicit OR instruction with a
8833         // separate test.
8834         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8835             isX86LogicalCmp(Cmp)) {
8836           CC = Cond.getOperand(0).getOperand(0);
8837           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8838                               Chain, Dest, CC, Cmp);
8839           CC = Cond.getOperand(1).getOperand(0);
8840           Cond = Cmp;
8841           addTest = false;
8842         }
8843       } else { // ISD::AND
8844         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8845         // two branches instead of an explicit AND instruction with a
8846         // separate test. However, we only do this if this block doesn't
8847         // have a fall-through edge, because this requires an explicit
8848         // jmp when the condition is false.
8849         if (Cmp == Cond.getOperand(1).getOperand(1) &&
8850             isX86LogicalCmp(Cmp) &&
8851             Op.getNode()->hasOneUse()) {
8852           X86::CondCode CCode =
8853             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8854           CCode = X86::GetOppositeBranchCondition(CCode);
8855           CC = DAG.getConstant(CCode, MVT::i8);
8856           SDNode *User = *Op.getNode()->use_begin();
8857           // Look for an unconditional branch following this conditional branch.
8858           // We need this because we need to reverse the successors in order
8859           // to implement FCMP_OEQ.
8860           if (User->getOpcode() == ISD::BR) {
8861             SDValue FalseBB = User->getOperand(1);
8862             SDNode *NewBR =
8863               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
8864             assert(NewBR == User);
8865             (void)NewBR;
8866             Dest = FalseBB;
8867
8868             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8869                                 Chain, Dest, CC, Cmp);
8870             X86::CondCode CCode =
8871               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
8872             CCode = X86::GetOppositeBranchCondition(CCode);
8873             CC = DAG.getConstant(CCode, MVT::i8);
8874             Cond = Cmp;
8875             addTest = false;
8876           }
8877         }
8878       }
8879     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
8880       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
8881       // It should be transformed during dag combiner except when the condition
8882       // is set by a arithmetics with overflow node.
8883       X86::CondCode CCode =
8884         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8885       CCode = X86::GetOppositeBranchCondition(CCode);
8886       CC = DAG.getConstant(CCode, MVT::i8);
8887       Cond = Cond.getOperand(0).getOperand(1);
8888       addTest = false;
8889     }
8890   }
8891
8892   if (addTest) {
8893     // Look pass the truncate.
8894     if (Cond.getOpcode() == ISD::TRUNCATE)
8895       Cond = Cond.getOperand(0);
8896
8897     // We know the result of AND is compared against zero. Try to match
8898     // it to BT.
8899     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8900       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
8901       if (NewSetCC.getNode()) {
8902         CC = NewSetCC.getOperand(0);
8903         Cond = NewSetCC.getOperand(1);
8904         addTest = false;
8905       }
8906     }
8907   }
8908
8909   if (addTest) {
8910     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8911     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8912   }
8913   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8914                      Chain, Dest, CC, Cond);
8915 }
8916
8917
8918 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
8919 // Calls to _alloca is needed to probe the stack when allocating more than 4k
8920 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
8921 // that the guard pages used by the OS virtual memory manager are allocated in
8922 // correct sequence.
8923 SDValue
8924 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8925                                            SelectionDAG &DAG) const {
8926   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
8927           EnableSegmentedStacks) &&
8928          "This should be used only on Windows targets or when segmented stacks "
8929          "are being used");
8930   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
8931   DebugLoc dl = Op.getDebugLoc();
8932
8933   // Get the inputs.
8934   SDValue Chain = Op.getOperand(0);
8935   SDValue Size  = Op.getOperand(1);
8936   // FIXME: Ensure alignment here
8937
8938   bool Is64Bit = Subtarget->is64Bit();
8939   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
8940
8941   if (EnableSegmentedStacks) {
8942     MachineFunction &MF = DAG.getMachineFunction();
8943     MachineRegisterInfo &MRI = MF.getRegInfo();
8944
8945     if (Is64Bit) {
8946       // The 64 bit implementation of segmented stacks needs to clobber both r10
8947       // r11. This makes it impossible to use it along with nested parameters.
8948       const Function *F = MF.getFunction();
8949
8950       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
8951            I != E; I++)
8952         if (I->hasNestAttr())
8953           report_fatal_error("Cannot use segmented stacks with functions that "
8954                              "have nested arguments.");
8955     }
8956
8957     const TargetRegisterClass *AddrRegClass =
8958       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
8959     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
8960     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
8961     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
8962                                 DAG.getRegister(Vreg, SPTy));
8963     SDValue Ops1[2] = { Value, Chain };
8964     return DAG.getMergeValues(Ops1, 2, dl);
8965   } else {
8966     SDValue Flag;
8967     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
8968
8969     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
8970     Flag = Chain.getValue(1);
8971     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8972
8973     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
8974     Flag = Chain.getValue(1);
8975
8976     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
8977
8978     SDValue Ops1[2] = { Chain.getValue(0), Chain };
8979     return DAG.getMergeValues(Ops1, 2, dl);
8980   }
8981 }
8982
8983 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
8984   MachineFunction &MF = DAG.getMachineFunction();
8985   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
8986
8987   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
8988   DebugLoc DL = Op.getDebugLoc();
8989
8990   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
8991     // vastart just stores the address of the VarArgsFrameIndex slot into the
8992     // memory location argument.
8993     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
8994                                    getPointerTy());
8995     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
8996                         MachinePointerInfo(SV), false, false, 0);
8997   }
8998
8999   // __va_list_tag:
9000   //   gp_offset         (0 - 6 * 8)
9001   //   fp_offset         (48 - 48 + 8 * 16)
9002   //   overflow_arg_area (point to parameters coming in memory).
9003   //   reg_save_area
9004   SmallVector<SDValue, 8> MemOps;
9005   SDValue FIN = Op.getOperand(1);
9006   // Store gp_offset
9007   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9008                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9009                                                MVT::i32),
9010                                FIN, MachinePointerInfo(SV), false, false, 0);
9011   MemOps.push_back(Store);
9012
9013   // Store fp_offset
9014   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9015                     FIN, DAG.getIntPtrConstant(4));
9016   Store = DAG.getStore(Op.getOperand(0), DL,
9017                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9018                                        MVT::i32),
9019                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9020   MemOps.push_back(Store);
9021
9022   // Store ptr to overflow_arg_area
9023   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9024                     FIN, DAG.getIntPtrConstant(4));
9025   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9026                                     getPointerTy());
9027   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9028                        MachinePointerInfo(SV, 8),
9029                        false, false, 0);
9030   MemOps.push_back(Store);
9031
9032   // Store ptr to reg_save_area.
9033   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9034                     FIN, DAG.getIntPtrConstant(8));
9035   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9036                                     getPointerTy());
9037   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9038                        MachinePointerInfo(SV, 16), false, false, 0);
9039   MemOps.push_back(Store);
9040   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9041                      &MemOps[0], MemOps.size());
9042 }
9043
9044 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9045   assert(Subtarget->is64Bit() &&
9046          "LowerVAARG only handles 64-bit va_arg!");
9047   assert((Subtarget->isTargetLinux() ||
9048           Subtarget->isTargetDarwin()) &&
9049           "Unhandled target in LowerVAARG");
9050   assert(Op.getNode()->getNumOperands() == 4);
9051   SDValue Chain = Op.getOperand(0);
9052   SDValue SrcPtr = Op.getOperand(1);
9053   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9054   unsigned Align = Op.getConstantOperandVal(3);
9055   DebugLoc dl = Op.getDebugLoc();
9056
9057   EVT ArgVT = Op.getNode()->getValueType(0);
9058   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9059   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9060   uint8_t ArgMode;
9061
9062   // Decide which area this value should be read from.
9063   // TODO: Implement the AMD64 ABI in its entirety. This simple
9064   // selection mechanism works only for the basic types.
9065   if (ArgVT == MVT::f80) {
9066     llvm_unreachable("va_arg for f80 not yet implemented");
9067   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9068     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9069   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9070     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9071   } else {
9072     llvm_unreachable("Unhandled argument type in LowerVAARG");
9073   }
9074
9075   if (ArgMode == 2) {
9076     // Sanity Check: Make sure using fp_offset makes sense.
9077     assert(!UseSoftFloat &&
9078            !(DAG.getMachineFunction()
9079                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9080            Subtarget->hasXMM());
9081   }
9082
9083   // Insert VAARG_64 node into the DAG
9084   // VAARG_64 returns two values: Variable Argument Address, Chain
9085   SmallVector<SDValue, 11> InstOps;
9086   InstOps.push_back(Chain);
9087   InstOps.push_back(SrcPtr);
9088   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9089   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9090   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9091   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9092   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9093                                           VTs, &InstOps[0], InstOps.size(),
9094                                           MVT::i64,
9095                                           MachinePointerInfo(SV),
9096                                           /*Align=*/0,
9097                                           /*Volatile=*/false,
9098                                           /*ReadMem=*/true,
9099                                           /*WriteMem=*/true);
9100   Chain = VAARG.getValue(1);
9101
9102   // Load the next argument and return it
9103   return DAG.getLoad(ArgVT, dl,
9104                      Chain,
9105                      VAARG,
9106                      MachinePointerInfo(),
9107                      false, false, 0);
9108 }
9109
9110 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9111   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9112   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9113   SDValue Chain = Op.getOperand(0);
9114   SDValue DstPtr = Op.getOperand(1);
9115   SDValue SrcPtr = Op.getOperand(2);
9116   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9117   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9118   DebugLoc DL = Op.getDebugLoc();
9119
9120   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9121                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9122                        false,
9123                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9124 }
9125
9126 SDValue
9127 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9128   DebugLoc dl = Op.getDebugLoc();
9129   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9130   switch (IntNo) {
9131   default: return SDValue();    // Don't custom lower most intrinsics.
9132   // Comparison intrinsics.
9133   case Intrinsic::x86_sse_comieq_ss:
9134   case Intrinsic::x86_sse_comilt_ss:
9135   case Intrinsic::x86_sse_comile_ss:
9136   case Intrinsic::x86_sse_comigt_ss:
9137   case Intrinsic::x86_sse_comige_ss:
9138   case Intrinsic::x86_sse_comineq_ss:
9139   case Intrinsic::x86_sse_ucomieq_ss:
9140   case Intrinsic::x86_sse_ucomilt_ss:
9141   case Intrinsic::x86_sse_ucomile_ss:
9142   case Intrinsic::x86_sse_ucomigt_ss:
9143   case Intrinsic::x86_sse_ucomige_ss:
9144   case Intrinsic::x86_sse_ucomineq_ss:
9145   case Intrinsic::x86_sse2_comieq_sd:
9146   case Intrinsic::x86_sse2_comilt_sd:
9147   case Intrinsic::x86_sse2_comile_sd:
9148   case Intrinsic::x86_sse2_comigt_sd:
9149   case Intrinsic::x86_sse2_comige_sd:
9150   case Intrinsic::x86_sse2_comineq_sd:
9151   case Intrinsic::x86_sse2_ucomieq_sd:
9152   case Intrinsic::x86_sse2_ucomilt_sd:
9153   case Intrinsic::x86_sse2_ucomile_sd:
9154   case Intrinsic::x86_sse2_ucomigt_sd:
9155   case Intrinsic::x86_sse2_ucomige_sd:
9156   case Intrinsic::x86_sse2_ucomineq_sd: {
9157     unsigned Opc = 0;
9158     ISD::CondCode CC = ISD::SETCC_INVALID;
9159     switch (IntNo) {
9160     default: break;
9161     case Intrinsic::x86_sse_comieq_ss:
9162     case Intrinsic::x86_sse2_comieq_sd:
9163       Opc = X86ISD::COMI;
9164       CC = ISD::SETEQ;
9165       break;
9166     case Intrinsic::x86_sse_comilt_ss:
9167     case Intrinsic::x86_sse2_comilt_sd:
9168       Opc = X86ISD::COMI;
9169       CC = ISD::SETLT;
9170       break;
9171     case Intrinsic::x86_sse_comile_ss:
9172     case Intrinsic::x86_sse2_comile_sd:
9173       Opc = X86ISD::COMI;
9174       CC = ISD::SETLE;
9175       break;
9176     case Intrinsic::x86_sse_comigt_ss:
9177     case Intrinsic::x86_sse2_comigt_sd:
9178       Opc = X86ISD::COMI;
9179       CC = ISD::SETGT;
9180       break;
9181     case Intrinsic::x86_sse_comige_ss:
9182     case Intrinsic::x86_sse2_comige_sd:
9183       Opc = X86ISD::COMI;
9184       CC = ISD::SETGE;
9185       break;
9186     case Intrinsic::x86_sse_comineq_ss:
9187     case Intrinsic::x86_sse2_comineq_sd:
9188       Opc = X86ISD::COMI;
9189       CC = ISD::SETNE;
9190       break;
9191     case Intrinsic::x86_sse_ucomieq_ss:
9192     case Intrinsic::x86_sse2_ucomieq_sd:
9193       Opc = X86ISD::UCOMI;
9194       CC = ISD::SETEQ;
9195       break;
9196     case Intrinsic::x86_sse_ucomilt_ss:
9197     case Intrinsic::x86_sse2_ucomilt_sd:
9198       Opc = X86ISD::UCOMI;
9199       CC = ISD::SETLT;
9200       break;
9201     case Intrinsic::x86_sse_ucomile_ss:
9202     case Intrinsic::x86_sse2_ucomile_sd:
9203       Opc = X86ISD::UCOMI;
9204       CC = ISD::SETLE;
9205       break;
9206     case Intrinsic::x86_sse_ucomigt_ss:
9207     case Intrinsic::x86_sse2_ucomigt_sd:
9208       Opc = X86ISD::UCOMI;
9209       CC = ISD::SETGT;
9210       break;
9211     case Intrinsic::x86_sse_ucomige_ss:
9212     case Intrinsic::x86_sse2_ucomige_sd:
9213       Opc = X86ISD::UCOMI;
9214       CC = ISD::SETGE;
9215       break;
9216     case Intrinsic::x86_sse_ucomineq_ss:
9217     case Intrinsic::x86_sse2_ucomineq_sd:
9218       Opc = X86ISD::UCOMI;
9219       CC = ISD::SETNE;
9220       break;
9221     }
9222
9223     SDValue LHS = Op.getOperand(1);
9224     SDValue RHS = Op.getOperand(2);
9225     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9226     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9227     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9228     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9229                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9230     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9231   }
9232   // Arithmetic intrinsics.
9233   case Intrinsic::x86_sse3_hadd_ps:
9234   case Intrinsic::x86_sse3_hadd_pd:
9235   case Intrinsic::x86_avx_hadd_ps_256:
9236   case Intrinsic::x86_avx_hadd_pd_256:
9237     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9238                        Op.getOperand(1), Op.getOperand(2));
9239   case Intrinsic::x86_sse3_hsub_ps:
9240   case Intrinsic::x86_sse3_hsub_pd:
9241   case Intrinsic::x86_avx_hsub_ps_256:
9242   case Intrinsic::x86_avx_hsub_pd_256:
9243     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9244                        Op.getOperand(1), Op.getOperand(2));
9245   // ptest and testp intrinsics. The intrinsic these come from are designed to
9246   // return an integer value, not just an instruction so lower it to the ptest
9247   // or testp pattern and a setcc for the result.
9248   case Intrinsic::x86_sse41_ptestz:
9249   case Intrinsic::x86_sse41_ptestc:
9250   case Intrinsic::x86_sse41_ptestnzc:
9251   case Intrinsic::x86_avx_ptestz_256:
9252   case Intrinsic::x86_avx_ptestc_256:
9253   case Intrinsic::x86_avx_ptestnzc_256:
9254   case Intrinsic::x86_avx_vtestz_ps:
9255   case Intrinsic::x86_avx_vtestc_ps:
9256   case Intrinsic::x86_avx_vtestnzc_ps:
9257   case Intrinsic::x86_avx_vtestz_pd:
9258   case Intrinsic::x86_avx_vtestc_pd:
9259   case Intrinsic::x86_avx_vtestnzc_pd:
9260   case Intrinsic::x86_avx_vtestz_ps_256:
9261   case Intrinsic::x86_avx_vtestc_ps_256:
9262   case Intrinsic::x86_avx_vtestnzc_ps_256:
9263   case Intrinsic::x86_avx_vtestz_pd_256:
9264   case Intrinsic::x86_avx_vtestc_pd_256:
9265   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9266     bool IsTestPacked = false;
9267     unsigned X86CC = 0;
9268     switch (IntNo) {
9269     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9270     case Intrinsic::x86_avx_vtestz_ps:
9271     case Intrinsic::x86_avx_vtestz_pd:
9272     case Intrinsic::x86_avx_vtestz_ps_256:
9273     case Intrinsic::x86_avx_vtestz_pd_256:
9274       IsTestPacked = true; // Fallthrough
9275     case Intrinsic::x86_sse41_ptestz:
9276     case Intrinsic::x86_avx_ptestz_256:
9277       // ZF = 1
9278       X86CC = X86::COND_E;
9279       break;
9280     case Intrinsic::x86_avx_vtestc_ps:
9281     case Intrinsic::x86_avx_vtestc_pd:
9282     case Intrinsic::x86_avx_vtestc_ps_256:
9283     case Intrinsic::x86_avx_vtestc_pd_256:
9284       IsTestPacked = true; // Fallthrough
9285     case Intrinsic::x86_sse41_ptestc:
9286     case Intrinsic::x86_avx_ptestc_256:
9287       // CF = 1
9288       X86CC = X86::COND_B;
9289       break;
9290     case Intrinsic::x86_avx_vtestnzc_ps:
9291     case Intrinsic::x86_avx_vtestnzc_pd:
9292     case Intrinsic::x86_avx_vtestnzc_ps_256:
9293     case Intrinsic::x86_avx_vtestnzc_pd_256:
9294       IsTestPacked = true; // Fallthrough
9295     case Intrinsic::x86_sse41_ptestnzc:
9296     case Intrinsic::x86_avx_ptestnzc_256:
9297       // ZF and CF = 0
9298       X86CC = X86::COND_A;
9299       break;
9300     }
9301
9302     SDValue LHS = Op.getOperand(1);
9303     SDValue RHS = Op.getOperand(2);
9304     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9305     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9306     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9307     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9308     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9309   }
9310
9311   // Fix vector shift instructions where the last operand is a non-immediate
9312   // i32 value.
9313   case Intrinsic::x86_sse2_pslli_w:
9314   case Intrinsic::x86_sse2_pslli_d:
9315   case Intrinsic::x86_sse2_pslli_q:
9316   case Intrinsic::x86_sse2_psrli_w:
9317   case Intrinsic::x86_sse2_psrli_d:
9318   case Intrinsic::x86_sse2_psrli_q:
9319   case Intrinsic::x86_sse2_psrai_w:
9320   case Intrinsic::x86_sse2_psrai_d:
9321   case Intrinsic::x86_mmx_pslli_w:
9322   case Intrinsic::x86_mmx_pslli_d:
9323   case Intrinsic::x86_mmx_pslli_q:
9324   case Intrinsic::x86_mmx_psrli_w:
9325   case Intrinsic::x86_mmx_psrli_d:
9326   case Intrinsic::x86_mmx_psrli_q:
9327   case Intrinsic::x86_mmx_psrai_w:
9328   case Intrinsic::x86_mmx_psrai_d: {
9329     SDValue ShAmt = Op.getOperand(2);
9330     if (isa<ConstantSDNode>(ShAmt))
9331       return SDValue();
9332
9333     unsigned NewIntNo = 0;
9334     EVT ShAmtVT = MVT::v4i32;
9335     switch (IntNo) {
9336     case Intrinsic::x86_sse2_pslli_w:
9337       NewIntNo = Intrinsic::x86_sse2_psll_w;
9338       break;
9339     case Intrinsic::x86_sse2_pslli_d:
9340       NewIntNo = Intrinsic::x86_sse2_psll_d;
9341       break;
9342     case Intrinsic::x86_sse2_pslli_q:
9343       NewIntNo = Intrinsic::x86_sse2_psll_q;
9344       break;
9345     case Intrinsic::x86_sse2_psrli_w:
9346       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9347       break;
9348     case Intrinsic::x86_sse2_psrli_d:
9349       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9350       break;
9351     case Intrinsic::x86_sse2_psrli_q:
9352       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9353       break;
9354     case Intrinsic::x86_sse2_psrai_w:
9355       NewIntNo = Intrinsic::x86_sse2_psra_w;
9356       break;
9357     case Intrinsic::x86_sse2_psrai_d:
9358       NewIntNo = Intrinsic::x86_sse2_psra_d;
9359       break;
9360     default: {
9361       ShAmtVT = MVT::v2i32;
9362       switch (IntNo) {
9363       case Intrinsic::x86_mmx_pslli_w:
9364         NewIntNo = Intrinsic::x86_mmx_psll_w;
9365         break;
9366       case Intrinsic::x86_mmx_pslli_d:
9367         NewIntNo = Intrinsic::x86_mmx_psll_d;
9368         break;
9369       case Intrinsic::x86_mmx_pslli_q:
9370         NewIntNo = Intrinsic::x86_mmx_psll_q;
9371         break;
9372       case Intrinsic::x86_mmx_psrli_w:
9373         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9374         break;
9375       case Intrinsic::x86_mmx_psrli_d:
9376         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9377         break;
9378       case Intrinsic::x86_mmx_psrli_q:
9379         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9380         break;
9381       case Intrinsic::x86_mmx_psrai_w:
9382         NewIntNo = Intrinsic::x86_mmx_psra_w;
9383         break;
9384       case Intrinsic::x86_mmx_psrai_d:
9385         NewIntNo = Intrinsic::x86_mmx_psra_d;
9386         break;
9387       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9388       }
9389       break;
9390     }
9391     }
9392
9393     // The vector shift intrinsics with scalars uses 32b shift amounts but
9394     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9395     // to be zero.
9396     SDValue ShOps[4];
9397     ShOps[0] = ShAmt;
9398     ShOps[1] = DAG.getConstant(0, MVT::i32);
9399     if (ShAmtVT == MVT::v4i32) {
9400       ShOps[2] = DAG.getUNDEF(MVT::i32);
9401       ShOps[3] = DAG.getUNDEF(MVT::i32);
9402       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9403     } else {
9404       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9405 // FIXME this must be lowered to get rid of the invalid type.
9406     }
9407
9408     EVT VT = Op.getValueType();
9409     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9410     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9411                        DAG.getConstant(NewIntNo, MVT::i32),
9412                        Op.getOperand(1), ShAmt);
9413   }
9414   }
9415 }
9416
9417 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9418                                            SelectionDAG &DAG) const {
9419   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9420   MFI->setReturnAddressIsTaken(true);
9421
9422   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9423   DebugLoc dl = Op.getDebugLoc();
9424
9425   if (Depth > 0) {
9426     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9427     SDValue Offset =
9428       DAG.getConstant(TD->getPointerSize(),
9429                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9430     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9431                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9432                                    FrameAddr, Offset),
9433                        MachinePointerInfo(), false, false, 0);
9434   }
9435
9436   // Just load the return address.
9437   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9438   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9439                      RetAddrFI, MachinePointerInfo(), false, false, 0);
9440 }
9441
9442 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9443   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9444   MFI->setFrameAddressIsTaken(true);
9445
9446   EVT VT = Op.getValueType();
9447   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9448   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9449   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9450   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9451   while (Depth--)
9452     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9453                             MachinePointerInfo(),
9454                             false, false, 0);
9455   return FrameAddr;
9456 }
9457
9458 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9459                                                      SelectionDAG &DAG) const {
9460   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9461 }
9462
9463 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9464   MachineFunction &MF = DAG.getMachineFunction();
9465   SDValue Chain     = Op.getOperand(0);
9466   SDValue Offset    = Op.getOperand(1);
9467   SDValue Handler   = Op.getOperand(2);
9468   DebugLoc dl       = Op.getDebugLoc();
9469
9470   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9471                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9472                                      getPointerTy());
9473   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9474
9475   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9476                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9477   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9478   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9479                        false, false, 0);
9480   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9481   MF.getRegInfo().addLiveOut(StoreAddrReg);
9482
9483   return DAG.getNode(X86ISD::EH_RETURN, dl,
9484                      MVT::Other,
9485                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9486 }
9487
9488 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9489                                                   SelectionDAG &DAG) const {
9490   return Op.getOperand(0);
9491 }
9492
9493 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9494                                                 SelectionDAG &DAG) const {
9495   SDValue Root = Op.getOperand(0);
9496   SDValue Trmp = Op.getOperand(1); // trampoline
9497   SDValue FPtr = Op.getOperand(2); // nested function
9498   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9499   DebugLoc dl  = Op.getDebugLoc();
9500
9501   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9502
9503   if (Subtarget->is64Bit()) {
9504     SDValue OutChains[6];
9505
9506     // Large code-model.
9507     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9508     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9509
9510     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9511     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9512
9513     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9514
9515     // Load the pointer to the nested function into R11.
9516     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9517     SDValue Addr = Trmp;
9518     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9519                                 Addr, MachinePointerInfo(TrmpAddr),
9520                                 false, false, 0);
9521
9522     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9523                        DAG.getConstant(2, MVT::i64));
9524     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9525                                 MachinePointerInfo(TrmpAddr, 2),
9526                                 false, false, 2);
9527
9528     // Load the 'nest' parameter value into R10.
9529     // R10 is specified in X86CallingConv.td
9530     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9531     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9532                        DAG.getConstant(10, MVT::i64));
9533     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9534                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9535                                 false, false, 0);
9536
9537     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9538                        DAG.getConstant(12, MVT::i64));
9539     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9540                                 MachinePointerInfo(TrmpAddr, 12),
9541                                 false, false, 2);
9542
9543     // Jump to the nested function.
9544     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9545     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9546                        DAG.getConstant(20, MVT::i64));
9547     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9548                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9549                                 false, false, 0);
9550
9551     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9552     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9553                        DAG.getConstant(22, MVT::i64));
9554     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9555                                 MachinePointerInfo(TrmpAddr, 22),
9556                                 false, false, 0);
9557
9558     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9559   } else {
9560     const Function *Func =
9561       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9562     CallingConv::ID CC = Func->getCallingConv();
9563     unsigned NestReg;
9564
9565     switch (CC) {
9566     default:
9567       llvm_unreachable("Unsupported calling convention");
9568     case CallingConv::C:
9569     case CallingConv::X86_StdCall: {
9570       // Pass 'nest' parameter in ECX.
9571       // Must be kept in sync with X86CallingConv.td
9572       NestReg = X86::ECX;
9573
9574       // Check that ECX wasn't needed by an 'inreg' parameter.
9575       FunctionType *FTy = Func->getFunctionType();
9576       const AttrListPtr &Attrs = Func->getAttributes();
9577
9578       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9579         unsigned InRegCount = 0;
9580         unsigned Idx = 1;
9581
9582         for (FunctionType::param_iterator I = FTy->param_begin(),
9583              E = FTy->param_end(); I != E; ++I, ++Idx)
9584           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9585             // FIXME: should only count parameters that are lowered to integers.
9586             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9587
9588         if (InRegCount > 2) {
9589           report_fatal_error("Nest register in use - reduce number of inreg"
9590                              " parameters!");
9591         }
9592       }
9593       break;
9594     }
9595     case CallingConv::X86_FastCall:
9596     case CallingConv::X86_ThisCall:
9597     case CallingConv::Fast:
9598       // Pass 'nest' parameter in EAX.
9599       // Must be kept in sync with X86CallingConv.td
9600       NestReg = X86::EAX;
9601       break;
9602     }
9603
9604     SDValue OutChains[4];
9605     SDValue Addr, Disp;
9606
9607     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9608                        DAG.getConstant(10, MVT::i32));
9609     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9610
9611     // This is storing the opcode for MOV32ri.
9612     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9613     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9614     OutChains[0] = DAG.getStore(Root, dl,
9615                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9616                                 Trmp, MachinePointerInfo(TrmpAddr),
9617                                 false, false, 0);
9618
9619     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9620                        DAG.getConstant(1, MVT::i32));
9621     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
9622                                 MachinePointerInfo(TrmpAddr, 1),
9623                                 false, false, 1);
9624
9625     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
9626     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9627                        DAG.getConstant(5, MVT::i32));
9628     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
9629                                 MachinePointerInfo(TrmpAddr, 5),
9630                                 false, false, 1);
9631
9632     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9633                        DAG.getConstant(6, MVT::i32));
9634     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
9635                                 MachinePointerInfo(TrmpAddr, 6),
9636                                 false, false, 1);
9637
9638     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
9639   }
9640 }
9641
9642 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
9643                                             SelectionDAG &DAG) const {
9644   /*
9645    The rounding mode is in bits 11:10 of FPSR, and has the following
9646    settings:
9647      00 Round to nearest
9648      01 Round to -inf
9649      10 Round to +inf
9650      11 Round to 0
9651
9652   FLT_ROUNDS, on the other hand, expects the following:
9653     -1 Undefined
9654      0 Round to 0
9655      1 Round to nearest
9656      2 Round to +inf
9657      3 Round to -inf
9658
9659   To perform the conversion, we do:
9660     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
9661   */
9662
9663   MachineFunction &MF = DAG.getMachineFunction();
9664   const TargetMachine &TM = MF.getTarget();
9665   const TargetFrameLowering &TFI = *TM.getFrameLowering();
9666   unsigned StackAlignment = TFI.getStackAlignment();
9667   EVT VT = Op.getValueType();
9668   DebugLoc DL = Op.getDebugLoc();
9669
9670   // Save FP Control Word to stack slot
9671   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
9672   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9673
9674
9675   MachineMemOperand *MMO =
9676    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9677                            MachineMemOperand::MOStore, 2, 2);
9678
9679   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
9680   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
9681                                           DAG.getVTList(MVT::Other),
9682                                           Ops, 2, MVT::i16, MMO);
9683
9684   // Load FP Control Word from stack slot
9685   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
9686                             MachinePointerInfo(), false, false, 0);
9687
9688   // Transform as necessary
9689   SDValue CWD1 =
9690     DAG.getNode(ISD::SRL, DL, MVT::i16,
9691                 DAG.getNode(ISD::AND, DL, MVT::i16,
9692                             CWD, DAG.getConstant(0x800, MVT::i16)),
9693                 DAG.getConstant(11, MVT::i8));
9694   SDValue CWD2 =
9695     DAG.getNode(ISD::SRL, DL, MVT::i16,
9696                 DAG.getNode(ISD::AND, DL, MVT::i16,
9697                             CWD, DAG.getConstant(0x400, MVT::i16)),
9698                 DAG.getConstant(9, MVT::i8));
9699
9700   SDValue RetVal =
9701     DAG.getNode(ISD::AND, DL, MVT::i16,
9702                 DAG.getNode(ISD::ADD, DL, MVT::i16,
9703                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
9704                             DAG.getConstant(1, MVT::i16)),
9705                 DAG.getConstant(3, MVT::i16));
9706
9707
9708   return DAG.getNode((VT.getSizeInBits() < 16 ?
9709                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
9710 }
9711
9712 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
9713   EVT VT = Op.getValueType();
9714   EVT OpVT = VT;
9715   unsigned NumBits = VT.getSizeInBits();
9716   DebugLoc dl = Op.getDebugLoc();
9717
9718   Op = Op.getOperand(0);
9719   if (VT == MVT::i8) {
9720     // Zero extend to i32 since there is not an i8 bsr.
9721     OpVT = MVT::i32;
9722     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9723   }
9724
9725   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
9726   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9727   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
9728
9729   // If src is zero (i.e. bsr sets ZF), returns NumBits.
9730   SDValue Ops[] = {
9731     Op,
9732     DAG.getConstant(NumBits+NumBits-1, OpVT),
9733     DAG.getConstant(X86::COND_E, MVT::i8),
9734     Op.getValue(1)
9735   };
9736   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9737
9738   // Finally xor with NumBits-1.
9739   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
9740
9741   if (VT == MVT::i8)
9742     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9743   return Op;
9744 }
9745
9746 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
9747   EVT VT = Op.getValueType();
9748   EVT OpVT = VT;
9749   unsigned NumBits = VT.getSizeInBits();
9750   DebugLoc dl = Op.getDebugLoc();
9751
9752   Op = Op.getOperand(0);
9753   if (VT == MVT::i8) {
9754     OpVT = MVT::i32;
9755     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
9756   }
9757
9758   // Issue a bsf (scan bits forward) which also sets EFLAGS.
9759   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
9760   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
9761
9762   // If src is zero (i.e. bsf sets ZF), returns NumBits.
9763   SDValue Ops[] = {
9764     Op,
9765     DAG.getConstant(NumBits, OpVT),
9766     DAG.getConstant(X86::COND_E, MVT::i8),
9767     Op.getValue(1)
9768   };
9769   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
9770
9771   if (VT == MVT::i8)
9772     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
9773   return Op;
9774 }
9775
9776 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
9777 // ones, and then concatenate the result back.
9778 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
9779   EVT VT = Op.getValueType();
9780
9781   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
9782          "Unsupported value type for operation");
9783
9784   int NumElems = VT.getVectorNumElements();
9785   DebugLoc dl = Op.getDebugLoc();
9786   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
9787   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
9788
9789   // Extract the LHS vectors
9790   SDValue LHS = Op.getOperand(0);
9791   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
9792   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
9793
9794   // Extract the RHS vectors
9795   SDValue RHS = Op.getOperand(1);
9796   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
9797   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
9798
9799   MVT EltVT = VT.getVectorElementType().getSimpleVT();
9800   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9801
9802   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9803                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
9804                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
9805 }
9806
9807 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
9808   assert(Op.getValueType().getSizeInBits() == 256 &&
9809          Op.getValueType().isInteger() &&
9810          "Only handle AVX 256-bit vector integer operation");
9811   return Lower256IntArith(Op, DAG);
9812 }
9813
9814 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
9815   assert(Op.getValueType().getSizeInBits() == 256 &&
9816          Op.getValueType().isInteger() &&
9817          "Only handle AVX 256-bit vector integer operation");
9818   return Lower256IntArith(Op, DAG);
9819 }
9820
9821 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9822   EVT VT = Op.getValueType();
9823
9824   // Decompose 256-bit ops into smaller 128-bit ops.
9825   if (VT.getSizeInBits() == 256)
9826     return Lower256IntArith(Op, DAG);
9827
9828   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
9829   DebugLoc dl = Op.getDebugLoc();
9830
9831   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
9832   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
9833   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
9834   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
9835   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
9836   //
9837   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
9838   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
9839   //  return AloBlo + AloBhi + AhiBlo;
9840
9841   SDValue A = Op.getOperand(0);
9842   SDValue B = Op.getOperand(1);
9843
9844   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9845                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9846                        A, DAG.getConstant(32, MVT::i32));
9847   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9848                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9849                        B, DAG.getConstant(32, MVT::i32));
9850   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9851                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9852                        A, B);
9853   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9854                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9855                        A, Bhi);
9856   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9857                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
9858                        Ahi, B);
9859   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9860                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9861                        AloBhi, DAG.getConstant(32, MVT::i32));
9862   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9863                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9864                        AhiBlo, DAG.getConstant(32, MVT::i32));
9865   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
9866   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
9867   return Res;
9868 }
9869
9870 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
9871
9872   EVT VT = Op.getValueType();
9873   DebugLoc dl = Op.getDebugLoc();
9874   SDValue R = Op.getOperand(0);
9875   SDValue Amt = Op.getOperand(1);
9876   LLVMContext *Context = DAG.getContext();
9877
9878   if (!Subtarget->hasXMMInt())
9879     return SDValue();
9880
9881   // Decompose 256-bit shifts into smaller 128-bit shifts.
9882   if (VT.getSizeInBits() == 256) {
9883     int NumElems = VT.getVectorNumElements();
9884     MVT EltVT = VT.getVectorElementType().getSimpleVT();
9885     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9886
9887     // Extract the two vectors
9888     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
9889     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
9890                                      DAG, dl);
9891
9892     // Recreate the shift amount vectors
9893     SDValue Amt1, Amt2;
9894     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
9895       // Constant shift amount
9896       SmallVector<SDValue, 4> Amt1Csts;
9897       SmallVector<SDValue, 4> Amt2Csts;
9898       for (int i = 0; i < NumElems/2; ++i)
9899         Amt1Csts.push_back(Amt->getOperand(i));
9900       for (int i = NumElems/2; i < NumElems; ++i)
9901         Amt2Csts.push_back(Amt->getOperand(i));
9902
9903       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9904                                  &Amt1Csts[0], NumElems/2);
9905       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
9906                                  &Amt2Csts[0], NumElems/2);
9907     } else {
9908       // Variable shift amount
9909       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
9910       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
9911                                  DAG, dl);
9912     }
9913
9914     // Issue new vector shifts for the smaller types
9915     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
9916     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
9917
9918     // Concatenate the result back
9919     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
9920   }
9921
9922   // Optimize shl/srl/sra with constant shift amount.
9923   if (isSplatVector(Amt.getNode())) {
9924     SDValue SclrAmt = Amt->getOperand(0);
9925     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
9926       uint64_t ShiftAmt = C->getZExtValue();
9927
9928       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
9929        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9930                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9931                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9932
9933       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
9934        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9935                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9936                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9937
9938       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
9939        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9940                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9941                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9942
9943       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
9944        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9945                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9946                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9947
9948       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
9949        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9950                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9951                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9952
9953       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
9954        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9955                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9956                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9957
9958       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
9959        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9960                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9961                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9962
9963       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
9964        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9965                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9966                      R, DAG.getConstant(ShiftAmt, MVT::i32));
9967     }
9968   }
9969
9970   // Lower SHL with variable shift amount.
9971   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
9972     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9973                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9974                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
9975
9976     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
9977
9978     std::vector<Constant*> CV(4, CI);
9979     Constant *C = ConstantVector::get(CV);
9980     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
9981     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9982                                  MachinePointerInfo::getConstantPool(),
9983                                  false, false, 16);
9984
9985     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
9986     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
9987     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
9988     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
9989   }
9990   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
9991     // a = a << 5;
9992     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9993                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9994                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
9995
9996     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
9997     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
9998
9999     std::vector<Constant*> CVM1(16, CM1);
10000     std::vector<Constant*> CVM2(16, CM2);
10001     Constant *C = ConstantVector::get(CVM1);
10002     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10003     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10004                             MachinePointerInfo::getConstantPool(),
10005                             false, false, 16);
10006
10007     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10008     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10009     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10010                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10011                     DAG.getConstant(4, MVT::i32));
10012     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10013     // a += a
10014     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10015
10016     C = ConstantVector::get(CVM2);
10017     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10018     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10019                     MachinePointerInfo::getConstantPool(),
10020                     false, false, 16);
10021
10022     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10023     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10024     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10025                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10026                     DAG.getConstant(2, MVT::i32));
10027     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10028     // a += a
10029     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10030
10031     // return pblendv(r, r+r, a);
10032     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10033                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10034     return R;
10035   }
10036   return SDValue();
10037 }
10038
10039 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10040   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10041   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10042   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10043   // has only one use.
10044   SDNode *N = Op.getNode();
10045   SDValue LHS = N->getOperand(0);
10046   SDValue RHS = N->getOperand(1);
10047   unsigned BaseOp = 0;
10048   unsigned Cond = 0;
10049   DebugLoc DL = Op.getDebugLoc();
10050   switch (Op.getOpcode()) {
10051   default: llvm_unreachable("Unknown ovf instruction!");
10052   case ISD::SADDO:
10053     // A subtract of one will be selected as a INC. Note that INC doesn't
10054     // set CF, so we can't do this for UADDO.
10055     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10056       if (C->isOne()) {
10057         BaseOp = X86ISD::INC;
10058         Cond = X86::COND_O;
10059         break;
10060       }
10061     BaseOp = X86ISD::ADD;
10062     Cond = X86::COND_O;
10063     break;
10064   case ISD::UADDO:
10065     BaseOp = X86ISD::ADD;
10066     Cond = X86::COND_B;
10067     break;
10068   case ISD::SSUBO:
10069     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10070     // set CF, so we can't do this for USUBO.
10071     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10072       if (C->isOne()) {
10073         BaseOp = X86ISD::DEC;
10074         Cond = X86::COND_O;
10075         break;
10076       }
10077     BaseOp = X86ISD::SUB;
10078     Cond = X86::COND_O;
10079     break;
10080   case ISD::USUBO:
10081     BaseOp = X86ISD::SUB;
10082     Cond = X86::COND_B;
10083     break;
10084   case ISD::SMULO:
10085     BaseOp = X86ISD::SMUL;
10086     Cond = X86::COND_O;
10087     break;
10088   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10089     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10090                                  MVT::i32);
10091     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10092
10093     SDValue SetCC =
10094       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10095                   DAG.getConstant(X86::COND_O, MVT::i32),
10096                   SDValue(Sum.getNode(), 2));
10097
10098     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10099   }
10100   }
10101
10102   // Also sets EFLAGS.
10103   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10104   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10105
10106   SDValue SetCC =
10107     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10108                 DAG.getConstant(Cond, MVT::i32),
10109                 SDValue(Sum.getNode(), 1));
10110
10111   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10112 }
10113
10114 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10115   DebugLoc dl = Op.getDebugLoc();
10116   SDNode* Node = Op.getNode();
10117   EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10118   EVT VT = Node->getValueType(0);
10119   if (Subtarget->hasXMMInt() && VT.isVector()) {
10120     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10121                         ExtraVT.getScalarType().getSizeInBits();
10122     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10123
10124     unsigned SHLIntrinsicsID = 0;
10125     unsigned SRAIntrinsicsID = 0;
10126     switch (VT.getSimpleVT().SimpleTy) {
10127       default:
10128         return SDValue();
10129       case MVT::v4i32: {
10130         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10131         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10132         break;
10133       }
10134       case MVT::v8i16: {
10135         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10136         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10137         break;
10138       }
10139     }
10140
10141     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10142                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10143                          Node->getOperand(0), ShAmt);
10144
10145     // In case of 1 bit sext, no need to shr
10146     if (ExtraVT.getScalarType().getSizeInBits() == 1) return Tmp1;
10147
10148     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10149                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10150                        Tmp1, ShAmt);
10151   }
10152
10153   return SDValue();
10154 }
10155
10156
10157 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10158   DebugLoc dl = Op.getDebugLoc();
10159
10160   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10161   // There isn't any reason to disable it if the target processor supports it.
10162   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10163     SDValue Chain = Op.getOperand(0);
10164     SDValue Zero = DAG.getConstant(0, MVT::i32);
10165     SDValue Ops[] = {
10166       DAG.getRegister(X86::ESP, MVT::i32), // Base
10167       DAG.getTargetConstant(1, MVT::i8),   // Scale
10168       DAG.getRegister(0, MVT::i32),        // Index
10169       DAG.getTargetConstant(0, MVT::i32),  // Disp
10170       DAG.getRegister(0, MVT::i32),        // Segment.
10171       Zero,
10172       Chain
10173     };
10174     SDNode *Res =
10175       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10176                           array_lengthof(Ops));
10177     return SDValue(Res, 0);
10178   }
10179
10180   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10181   if (!isDev)
10182     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10183
10184   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10185   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10186   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10187   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10188
10189   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10190   if (!Op1 && !Op2 && !Op3 && Op4)
10191     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10192
10193   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10194   if (Op1 && !Op2 && !Op3 && !Op4)
10195     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10196
10197   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10198   //           (MFENCE)>;
10199   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10200 }
10201
10202 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10203                                              SelectionDAG &DAG) const {
10204   DebugLoc dl = Op.getDebugLoc();
10205   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10206     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10207   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10208     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10209
10210   // The only fence that needs an instruction is a sequentially-consistent
10211   // cross-thread fence.
10212   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10213     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10214     // no-sse2). There isn't any reason to disable it if the target processor
10215     // supports it.
10216     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10217       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10218
10219     SDValue Chain = Op.getOperand(0);
10220     SDValue Zero = DAG.getConstant(0, MVT::i32);
10221     SDValue Ops[] = {
10222       DAG.getRegister(X86::ESP, MVT::i32), // Base
10223       DAG.getTargetConstant(1, MVT::i8),   // Scale
10224       DAG.getRegister(0, MVT::i32),        // Index
10225       DAG.getTargetConstant(0, MVT::i32),  // Disp
10226       DAG.getRegister(0, MVT::i32),        // Segment.
10227       Zero,
10228       Chain
10229     };
10230     SDNode *Res =
10231       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10232                          array_lengthof(Ops));
10233     return SDValue(Res, 0);
10234   }
10235
10236   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10237   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10238 }
10239
10240
10241 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10242   EVT T = Op.getValueType();
10243   DebugLoc DL = Op.getDebugLoc();
10244   unsigned Reg = 0;
10245   unsigned size = 0;
10246   switch(T.getSimpleVT().SimpleTy) {
10247   default:
10248     assert(false && "Invalid value type!");
10249   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10250   case MVT::i16: Reg = X86::AX;  size = 2; break;
10251   case MVT::i32: Reg = X86::EAX; size = 4; break;
10252   case MVT::i64:
10253     assert(Subtarget->is64Bit() && "Node not type legal!");
10254     Reg = X86::RAX; size = 8;
10255     break;
10256   }
10257   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10258                                     Op.getOperand(2), SDValue());
10259   SDValue Ops[] = { cpIn.getValue(0),
10260                     Op.getOperand(1),
10261                     Op.getOperand(3),
10262                     DAG.getTargetConstant(size, MVT::i8),
10263                     cpIn.getValue(1) };
10264   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10265   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10266   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10267                                            Ops, 5, T, MMO);
10268   SDValue cpOut =
10269     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10270   return cpOut;
10271 }
10272
10273 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10274                                                  SelectionDAG &DAG) const {
10275   assert(Subtarget->is64Bit() && "Result not type legalized?");
10276   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10277   SDValue TheChain = Op.getOperand(0);
10278   DebugLoc dl = Op.getDebugLoc();
10279   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10280   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10281   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10282                                    rax.getValue(2));
10283   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10284                             DAG.getConstant(32, MVT::i8));
10285   SDValue Ops[] = {
10286     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10287     rdx.getValue(1)
10288   };
10289   return DAG.getMergeValues(Ops, 2, dl);
10290 }
10291
10292 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10293                                             SelectionDAG &DAG) const {
10294   EVT SrcVT = Op.getOperand(0).getValueType();
10295   EVT DstVT = Op.getValueType();
10296   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10297          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10298   assert((DstVT == MVT::i64 ||
10299           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10300          "Unexpected custom BITCAST");
10301   // i64 <=> MMX conversions are Legal.
10302   if (SrcVT==MVT::i64 && DstVT.isVector())
10303     return Op;
10304   if (DstVT==MVT::i64 && SrcVT.isVector())
10305     return Op;
10306   // MMX <=> MMX conversions are Legal.
10307   if (SrcVT.isVector() && DstVT.isVector())
10308     return Op;
10309   // All other conversions need to be expanded.
10310   return SDValue();
10311 }
10312
10313 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10314   SDNode *Node = Op.getNode();
10315   DebugLoc dl = Node->getDebugLoc();
10316   EVT T = Node->getValueType(0);
10317   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10318                               DAG.getConstant(0, T), Node->getOperand(2));
10319   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10320                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10321                        Node->getOperand(0),
10322                        Node->getOperand(1), negOp,
10323                        cast<AtomicSDNode>(Node)->getSrcValue(),
10324                        cast<AtomicSDNode>(Node)->getAlignment(),
10325                        cast<AtomicSDNode>(Node)->getOrdering(),
10326                        cast<AtomicSDNode>(Node)->getSynchScope());
10327 }
10328
10329 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10330   SDNode *Node = Op.getNode();
10331   DebugLoc dl = Node->getDebugLoc();
10332   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10333
10334   // Convert seq_cst store -> xchg
10335   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10336   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10337   //        (The only way to get a 16-byte store is cmpxchg16b)
10338   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10339   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10340       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10341     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10342                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10343                                  Node->getOperand(0),
10344                                  Node->getOperand(1), Node->getOperand(2),
10345                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10346                                  cast<AtomicSDNode>(Node)->getOrdering(),
10347                                  cast<AtomicSDNode>(Node)->getSynchScope());
10348     return Swap.getValue(1);
10349   }
10350   // Other atomic stores have a simple pattern.
10351   return Op;
10352 }
10353
10354 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10355   EVT VT = Op.getNode()->getValueType(0);
10356
10357   // Let legalize expand this if it isn't a legal type yet.
10358   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10359     return SDValue();
10360
10361   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10362
10363   unsigned Opc;
10364   bool ExtraOp = false;
10365   switch (Op.getOpcode()) {
10366   default: assert(0 && "Invalid code");
10367   case ISD::ADDC: Opc = X86ISD::ADD; break;
10368   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10369   case ISD::SUBC: Opc = X86ISD::SUB; break;
10370   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10371   }
10372
10373   if (!ExtraOp)
10374     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10375                        Op.getOperand(1));
10376   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10377                      Op.getOperand(1), Op.getOperand(2));
10378 }
10379
10380 /// LowerOperation - Provide custom lowering hooks for some operations.
10381 ///
10382 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10383   switch (Op.getOpcode()) {
10384   default: llvm_unreachable("Should not custom lower this!");
10385   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10386   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10387   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10388   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10389   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10390   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10391   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10392   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10393   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10394   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10395   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10396   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10397   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10398   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10399   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10400   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10401   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10402   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10403   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10404   case ISD::SHL_PARTS:
10405   case ISD::SRA_PARTS:
10406   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10407   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10408   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10409   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10410   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10411   case ISD::FABS:               return LowerFABS(Op, DAG);
10412   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10413   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10414   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10415   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10416   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10417   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10418   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10419   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10420   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10421   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10422   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10423   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10424   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10425   case ISD::FRAME_TO_ARGS_OFFSET:
10426                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10427   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10428   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10429   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10430   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10431   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10432   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10433   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10434   case ISD::MUL:                return LowerMUL(Op, DAG);
10435   case ISD::SRA:
10436   case ISD::SRL:
10437   case ISD::SHL:                return LowerShift(Op, DAG);
10438   case ISD::SADDO:
10439   case ISD::UADDO:
10440   case ISD::SSUBO:
10441   case ISD::USUBO:
10442   case ISD::SMULO:
10443   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10444   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10445   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10446   case ISD::ADDC:
10447   case ISD::ADDE:
10448   case ISD::SUBC:
10449   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10450   case ISD::ADD:                return LowerADD(Op, DAG);
10451   case ISD::SUB:                return LowerSUB(Op, DAG);
10452   }
10453 }
10454
10455 static void ReplaceATOMIC_LOAD(SDNode *Node,
10456                                   SmallVectorImpl<SDValue> &Results,
10457                                   SelectionDAG &DAG) {
10458   DebugLoc dl = Node->getDebugLoc();
10459   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10460
10461   // Convert wide load -> cmpxchg8b/cmpxchg16b
10462   // FIXME: On 32-bit, load -> fild or movq would be more efficient
10463   //        (The only way to get a 16-byte load is cmpxchg16b)
10464   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
10465   SDValue Zero = DAG.getConstant(0, VT);
10466   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
10467                                Node->getOperand(0),
10468                                Node->getOperand(1), Zero, Zero,
10469                                cast<AtomicSDNode>(Node)->getMemOperand(),
10470                                cast<AtomicSDNode>(Node)->getOrdering(),
10471                                cast<AtomicSDNode>(Node)->getSynchScope());
10472   Results.push_back(Swap.getValue(0));
10473   Results.push_back(Swap.getValue(1));
10474 }
10475
10476 void X86TargetLowering::
10477 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
10478                         SelectionDAG &DAG, unsigned NewOp) const {
10479   EVT T = Node->getValueType(0);
10480   DebugLoc dl = Node->getDebugLoc();
10481   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
10482
10483   SDValue Chain = Node->getOperand(0);
10484   SDValue In1 = Node->getOperand(1);
10485   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10486                              Node->getOperand(2), DAG.getIntPtrConstant(0));
10487   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
10488                              Node->getOperand(2), DAG.getIntPtrConstant(1));
10489   SDValue Ops[] = { Chain, In1, In2L, In2H };
10490   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10491   SDValue Result =
10492     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
10493                             cast<MemSDNode>(Node)->getMemOperand());
10494   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
10495   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
10496   Results.push_back(Result.getValue(2));
10497 }
10498
10499 /// ReplaceNodeResults - Replace a node with an illegal result type
10500 /// with a new node built out of custom code.
10501 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
10502                                            SmallVectorImpl<SDValue>&Results,
10503                                            SelectionDAG &DAG) const {
10504   DebugLoc dl = N->getDebugLoc();
10505   switch (N->getOpcode()) {
10506   default:
10507     assert(false && "Do not know how to custom type legalize this operation!");
10508     return;
10509   case ISD::SIGN_EXTEND_INREG:
10510   case ISD::ADDC:
10511   case ISD::ADDE:
10512   case ISD::SUBC:
10513   case ISD::SUBE:
10514     // We don't want to expand or promote these.
10515     return;
10516   case ISD::FP_TO_SINT: {
10517     std::pair<SDValue,SDValue> Vals =
10518         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
10519     SDValue FIST = Vals.first, StackSlot = Vals.second;
10520     if (FIST.getNode() != 0) {
10521       EVT VT = N->getValueType(0);
10522       // Return a load from the stack slot.
10523       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
10524                                     MachinePointerInfo(), false, false, 0));
10525     }
10526     return;
10527   }
10528   case ISD::READCYCLECOUNTER: {
10529     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10530     SDValue TheChain = N->getOperand(0);
10531     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10532     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
10533                                      rd.getValue(1));
10534     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
10535                                      eax.getValue(2));
10536     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
10537     SDValue Ops[] = { eax, edx };
10538     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
10539     Results.push_back(edx.getValue(1));
10540     return;
10541   }
10542   case ISD::ATOMIC_CMP_SWAP: {
10543     EVT T = N->getValueType(0);
10544     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
10545     bool Regs64bit = T == MVT::i128;
10546     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
10547     SDValue cpInL, cpInH;
10548     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10549                         DAG.getConstant(0, HalfT));
10550     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
10551                         DAG.getConstant(1, HalfT));
10552     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
10553                              Regs64bit ? X86::RAX : X86::EAX,
10554                              cpInL, SDValue());
10555     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
10556                              Regs64bit ? X86::RDX : X86::EDX,
10557                              cpInH, cpInL.getValue(1));
10558     SDValue swapInL, swapInH;
10559     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10560                           DAG.getConstant(0, HalfT));
10561     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
10562                           DAG.getConstant(1, HalfT));
10563     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
10564                                Regs64bit ? X86::RBX : X86::EBX,
10565                                swapInL, cpInH.getValue(1));
10566     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
10567                                Regs64bit ? X86::RCX : X86::ECX, 
10568                                swapInH, swapInL.getValue(1));
10569     SDValue Ops[] = { swapInH.getValue(0),
10570                       N->getOperand(1),
10571                       swapInH.getValue(1) };
10572     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10573     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
10574     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
10575                                   X86ISD::LCMPXCHG8_DAG;
10576     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
10577                                              Ops, 3, T, MMO);
10578     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
10579                                         Regs64bit ? X86::RAX : X86::EAX,
10580                                         HalfT, Result.getValue(1));
10581     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
10582                                         Regs64bit ? X86::RDX : X86::EDX,
10583                                         HalfT, cpOutL.getValue(2));
10584     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
10585     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
10586     Results.push_back(cpOutH.getValue(1));
10587     return;
10588   }
10589   case ISD::ATOMIC_LOAD_ADD:
10590     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
10591     return;
10592   case ISD::ATOMIC_LOAD_AND:
10593     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
10594     return;
10595   case ISD::ATOMIC_LOAD_NAND:
10596     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
10597     return;
10598   case ISD::ATOMIC_LOAD_OR:
10599     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
10600     return;
10601   case ISD::ATOMIC_LOAD_SUB:
10602     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
10603     return;
10604   case ISD::ATOMIC_LOAD_XOR:
10605     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
10606     return;
10607   case ISD::ATOMIC_SWAP:
10608     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
10609     return;
10610   case ISD::ATOMIC_LOAD:
10611     ReplaceATOMIC_LOAD(N, Results, DAG);
10612   }
10613 }
10614
10615 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
10616   switch (Opcode) {
10617   default: return NULL;
10618   case X86ISD::BSF:                return "X86ISD::BSF";
10619   case X86ISD::BSR:                return "X86ISD::BSR";
10620   case X86ISD::SHLD:               return "X86ISD::SHLD";
10621   case X86ISD::SHRD:               return "X86ISD::SHRD";
10622   case X86ISD::FAND:               return "X86ISD::FAND";
10623   case X86ISD::FOR:                return "X86ISD::FOR";
10624   case X86ISD::FXOR:               return "X86ISD::FXOR";
10625   case X86ISD::FSRL:               return "X86ISD::FSRL";
10626   case X86ISD::FILD:               return "X86ISD::FILD";
10627   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
10628   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
10629   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
10630   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
10631   case X86ISD::FLD:                return "X86ISD::FLD";
10632   case X86ISD::FST:                return "X86ISD::FST";
10633   case X86ISD::CALL:               return "X86ISD::CALL";
10634   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
10635   case X86ISD::BT:                 return "X86ISD::BT";
10636   case X86ISD::CMP:                return "X86ISD::CMP";
10637   case X86ISD::COMI:               return "X86ISD::COMI";
10638   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
10639   case X86ISD::SETCC:              return "X86ISD::SETCC";
10640   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
10641   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
10642   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
10643   case X86ISD::CMOV:               return "X86ISD::CMOV";
10644   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
10645   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
10646   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
10647   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
10648   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
10649   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
10650   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
10651   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
10652   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
10653   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
10654   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
10655   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
10656   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
10657   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
10658   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
10659   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
10660   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
10661   case X86ISD::FMAX:               return "X86ISD::FMAX";
10662   case X86ISD::FMIN:               return "X86ISD::FMIN";
10663   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
10664   case X86ISD::FRCP:               return "X86ISD::FRCP";
10665   case X86ISD::FHADD:              return "X86ISD::FHADD";
10666   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
10667   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
10668   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
10669   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
10670   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
10671   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
10672   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
10673   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
10674   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
10675   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
10676   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
10677   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
10678   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
10679   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
10680   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
10681   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
10682   case X86ISD::VSHL:               return "X86ISD::VSHL";
10683   case X86ISD::VSRL:               return "X86ISD::VSRL";
10684   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
10685   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
10686   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
10687   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
10688   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
10689   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
10690   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
10691   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
10692   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
10693   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
10694   case X86ISD::ADD:                return "X86ISD::ADD";
10695   case X86ISD::SUB:                return "X86ISD::SUB";
10696   case X86ISD::ADC:                return "X86ISD::ADC";
10697   case X86ISD::SBB:                return "X86ISD::SBB";
10698   case X86ISD::SMUL:               return "X86ISD::SMUL";
10699   case X86ISD::UMUL:               return "X86ISD::UMUL";
10700   case X86ISD::INC:                return "X86ISD::INC";
10701   case X86ISD::DEC:                return "X86ISD::DEC";
10702   case X86ISD::OR:                 return "X86ISD::OR";
10703   case X86ISD::XOR:                return "X86ISD::XOR";
10704   case X86ISD::AND:                return "X86ISD::AND";
10705   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
10706   case X86ISD::PTEST:              return "X86ISD::PTEST";
10707   case X86ISD::TESTP:              return "X86ISD::TESTP";
10708   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
10709   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
10710   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
10711   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
10712   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
10713   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
10714   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
10715   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
10716   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
10717   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
10718   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
10719   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
10720   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
10721   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
10722   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
10723   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
10724   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
10725   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
10726   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
10727   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
10728   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
10729   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
10730   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
10731   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
10732   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
10733   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
10734   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
10735   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
10736   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
10737   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
10738   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
10739   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
10740   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
10741   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
10742   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
10743   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
10744   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
10745   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
10746   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
10747   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
10748   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
10749   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
10750   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
10751   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
10752   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
10753   }
10754 }
10755
10756 // isLegalAddressingMode - Return true if the addressing mode represented
10757 // by AM is legal for this target, for a load/store of the specified type.
10758 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
10759                                               Type *Ty) const {
10760   // X86 supports extremely general addressing modes.
10761   CodeModel::Model M = getTargetMachine().getCodeModel();
10762   Reloc::Model R = getTargetMachine().getRelocationModel();
10763
10764   // X86 allows a sign-extended 32-bit immediate field as a displacement.
10765   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
10766     return false;
10767
10768   if (AM.BaseGV) {
10769     unsigned GVFlags =
10770       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
10771
10772     // If a reference to this global requires an extra load, we can't fold it.
10773     if (isGlobalStubReference(GVFlags))
10774       return false;
10775
10776     // If BaseGV requires a register for the PIC base, we cannot also have a
10777     // BaseReg specified.
10778     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
10779       return false;
10780
10781     // If lower 4G is not available, then we must use rip-relative addressing.
10782     if ((M != CodeModel::Small || R != Reloc::Static) &&
10783         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
10784       return false;
10785   }
10786
10787   switch (AM.Scale) {
10788   case 0:
10789   case 1:
10790   case 2:
10791   case 4:
10792   case 8:
10793     // These scales always work.
10794     break;
10795   case 3:
10796   case 5:
10797   case 9:
10798     // These scales are formed with basereg+scalereg.  Only accept if there is
10799     // no basereg yet.
10800     if (AM.HasBaseReg)
10801       return false;
10802     break;
10803   default:  // Other stuff never works.
10804     return false;
10805   }
10806
10807   return true;
10808 }
10809
10810
10811 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
10812   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10813     return false;
10814   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
10815   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
10816   if (NumBits1 <= NumBits2)
10817     return false;
10818   return true;
10819 }
10820
10821 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
10822   if (!VT1.isInteger() || !VT2.isInteger())
10823     return false;
10824   unsigned NumBits1 = VT1.getSizeInBits();
10825   unsigned NumBits2 = VT2.getSizeInBits();
10826   if (NumBits1 <= NumBits2)
10827     return false;
10828   return true;
10829 }
10830
10831 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
10832   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10833   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
10834 }
10835
10836 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
10837   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
10838   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
10839 }
10840
10841 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
10842   // i16 instructions are longer (0x66 prefix) and potentially slower.
10843   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
10844 }
10845
10846 /// isShuffleMaskLegal - Targets can use this to indicate that they only
10847 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
10848 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
10849 /// are assumed to be legal.
10850 bool
10851 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
10852                                       EVT VT) const {
10853   // Very little shuffling can be done for 64-bit vectors right now.
10854   if (VT.getSizeInBits() == 64)
10855     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
10856
10857   // FIXME: pshufb, blends, shifts.
10858   return (VT.getVectorNumElements() == 2 ||
10859           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
10860           isMOVLMask(M, VT) ||
10861           isSHUFPMask(M, VT) ||
10862           isPSHUFDMask(M, VT) ||
10863           isPSHUFHWMask(M, VT) ||
10864           isPSHUFLWMask(M, VT) ||
10865           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
10866           isUNPCKLMask(M, VT) ||
10867           isUNPCKHMask(M, VT) ||
10868           isUNPCKL_v_undef_Mask(M, VT) ||
10869           isUNPCKH_v_undef_Mask(M, VT));
10870 }
10871
10872 bool
10873 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
10874                                           EVT VT) const {
10875   unsigned NumElts = VT.getVectorNumElements();
10876   // FIXME: This collection of masks seems suspect.
10877   if (NumElts == 2)
10878     return true;
10879   if (NumElts == 4 && VT.getSizeInBits() == 128) {
10880     return (isMOVLMask(Mask, VT)  ||
10881             isCommutedMOVLMask(Mask, VT, true) ||
10882             isSHUFPMask(Mask, VT) ||
10883             isCommutedSHUFPMask(Mask, VT));
10884   }
10885   return false;
10886 }
10887
10888 //===----------------------------------------------------------------------===//
10889 //                           X86 Scheduler Hooks
10890 //===----------------------------------------------------------------------===//
10891
10892 // private utility function
10893 MachineBasicBlock *
10894 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
10895                                                        MachineBasicBlock *MBB,
10896                                                        unsigned regOpc,
10897                                                        unsigned immOpc,
10898                                                        unsigned LoadOpc,
10899                                                        unsigned CXchgOpc,
10900                                                        unsigned notOpc,
10901                                                        unsigned EAXreg,
10902                                                        TargetRegisterClass *RC,
10903                                                        bool invSrc) const {
10904   // For the atomic bitwise operator, we generate
10905   //   thisMBB:
10906   //   newMBB:
10907   //     ld  t1 = [bitinstr.addr]
10908   //     op  t2 = t1, [bitinstr.val]
10909   //     mov EAX = t1
10910   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
10911   //     bz  newMBB
10912   //     fallthrough -->nextMBB
10913   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10914   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
10915   MachineFunction::iterator MBBIter = MBB;
10916   ++MBBIter;
10917
10918   /// First build the CFG
10919   MachineFunction *F = MBB->getParent();
10920   MachineBasicBlock *thisMBB = MBB;
10921   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
10922   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
10923   F->insert(MBBIter, newMBB);
10924   F->insert(MBBIter, nextMBB);
10925
10926   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
10927   nextMBB->splice(nextMBB->begin(), thisMBB,
10928                   llvm::next(MachineBasicBlock::iterator(bInstr)),
10929                   thisMBB->end());
10930   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
10931
10932   // Update thisMBB to fall through to newMBB
10933   thisMBB->addSuccessor(newMBB);
10934
10935   // newMBB jumps to itself and fall through to nextMBB
10936   newMBB->addSuccessor(nextMBB);
10937   newMBB->addSuccessor(newMBB);
10938
10939   // Insert instructions into newMBB based on incoming instruction
10940   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
10941          "unexpected number of operands");
10942   DebugLoc dl = bInstr->getDebugLoc();
10943   MachineOperand& destOper = bInstr->getOperand(0);
10944   MachineOperand* argOpers[2 + X86::AddrNumOperands];
10945   int numArgs = bInstr->getNumOperands() - 1;
10946   for (int i=0; i < numArgs; ++i)
10947     argOpers[i] = &bInstr->getOperand(i+1);
10948
10949   // x86 address has 4 operands: base, index, scale, and displacement
10950   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
10951   int valArgIndx = lastAddrIndx + 1;
10952
10953   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
10954   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
10955   for (int i=0; i <= lastAddrIndx; ++i)
10956     (*MIB).addOperand(*argOpers[i]);
10957
10958   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
10959   if (invSrc) {
10960     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
10961   }
10962   else
10963     tt = t1;
10964
10965   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
10966   assert((argOpers[valArgIndx]->isReg() ||
10967           argOpers[valArgIndx]->isImm()) &&
10968          "invalid operand");
10969   if (argOpers[valArgIndx]->isReg())
10970     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
10971   else
10972     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
10973   MIB.addReg(tt);
10974   (*MIB).addOperand(*argOpers[valArgIndx]);
10975
10976   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
10977   MIB.addReg(t1);
10978
10979   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
10980   for (int i=0; i <= lastAddrIndx; ++i)
10981     (*MIB).addOperand(*argOpers[i]);
10982   MIB.addReg(t2);
10983   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
10984   (*MIB).setMemRefs(bInstr->memoperands_begin(),
10985                     bInstr->memoperands_end());
10986
10987   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
10988   MIB.addReg(EAXreg);
10989
10990   // insert branch
10991   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
10992
10993   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
10994   return nextMBB;
10995 }
10996
10997 // private utility function:  64 bit atomics on 32 bit host.
10998 MachineBasicBlock *
10999 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11000                                                        MachineBasicBlock *MBB,
11001                                                        unsigned regOpcL,
11002                                                        unsigned regOpcH,
11003                                                        unsigned immOpcL,
11004                                                        unsigned immOpcH,
11005                                                        bool invSrc) const {
11006   // For the atomic bitwise operator, we generate
11007   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11008   //     ld t1,t2 = [bitinstr.addr]
11009   //   newMBB:
11010   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11011   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11012   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11013   //     mov ECX, EBX <- t5, t6
11014   //     mov EAX, EDX <- t1, t2
11015   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11016   //     mov t3, t4 <- EAX, EDX
11017   //     bz  newMBB
11018   //     result in out1, out2
11019   //     fallthrough -->nextMBB
11020
11021   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11022   const unsigned LoadOpc = X86::MOV32rm;
11023   const unsigned NotOpc = X86::NOT32r;
11024   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11025   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11026   MachineFunction::iterator MBBIter = MBB;
11027   ++MBBIter;
11028
11029   /// First build the CFG
11030   MachineFunction *F = MBB->getParent();
11031   MachineBasicBlock *thisMBB = MBB;
11032   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11033   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11034   F->insert(MBBIter, newMBB);
11035   F->insert(MBBIter, nextMBB);
11036
11037   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11038   nextMBB->splice(nextMBB->begin(), thisMBB,
11039                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11040                   thisMBB->end());
11041   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11042
11043   // Update thisMBB to fall through to newMBB
11044   thisMBB->addSuccessor(newMBB);
11045
11046   // newMBB jumps to itself and fall through to nextMBB
11047   newMBB->addSuccessor(nextMBB);
11048   newMBB->addSuccessor(newMBB);
11049
11050   DebugLoc dl = bInstr->getDebugLoc();
11051   // Insert instructions into newMBB based on incoming instruction
11052   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11053   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11054          "unexpected number of operands");
11055   MachineOperand& dest1Oper = bInstr->getOperand(0);
11056   MachineOperand& dest2Oper = bInstr->getOperand(1);
11057   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11058   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11059     argOpers[i] = &bInstr->getOperand(i+2);
11060
11061     // We use some of the operands multiple times, so conservatively just
11062     // clear any kill flags that might be present.
11063     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11064       argOpers[i]->setIsKill(false);
11065   }
11066
11067   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11068   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11069
11070   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11071   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11072   for (int i=0; i <= lastAddrIndx; ++i)
11073     (*MIB).addOperand(*argOpers[i]);
11074   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11075   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11076   // add 4 to displacement.
11077   for (int i=0; i <= lastAddrIndx-2; ++i)
11078     (*MIB).addOperand(*argOpers[i]);
11079   MachineOperand newOp3 = *(argOpers[3]);
11080   if (newOp3.isImm())
11081     newOp3.setImm(newOp3.getImm()+4);
11082   else
11083     newOp3.setOffset(newOp3.getOffset()+4);
11084   (*MIB).addOperand(newOp3);
11085   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11086
11087   // t3/4 are defined later, at the bottom of the loop
11088   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11089   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11090   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11091     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11092   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11093     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11094
11095   // The subsequent operations should be using the destination registers of
11096   //the PHI instructions.
11097   if (invSrc) {
11098     t1 = F->getRegInfo().createVirtualRegister(RC);
11099     t2 = F->getRegInfo().createVirtualRegister(RC);
11100     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11101     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11102   } else {
11103     t1 = dest1Oper.getReg();
11104     t2 = dest2Oper.getReg();
11105   }
11106
11107   int valArgIndx = lastAddrIndx + 1;
11108   assert((argOpers[valArgIndx]->isReg() ||
11109           argOpers[valArgIndx]->isImm()) &&
11110          "invalid operand");
11111   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11112   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11113   if (argOpers[valArgIndx]->isReg())
11114     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11115   else
11116     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11117   if (regOpcL != X86::MOV32rr)
11118     MIB.addReg(t1);
11119   (*MIB).addOperand(*argOpers[valArgIndx]);
11120   assert(argOpers[valArgIndx + 1]->isReg() ==
11121          argOpers[valArgIndx]->isReg());
11122   assert(argOpers[valArgIndx + 1]->isImm() ==
11123          argOpers[valArgIndx]->isImm());
11124   if (argOpers[valArgIndx + 1]->isReg())
11125     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11126   else
11127     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11128   if (regOpcH != X86::MOV32rr)
11129     MIB.addReg(t2);
11130   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11131
11132   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11133   MIB.addReg(t1);
11134   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11135   MIB.addReg(t2);
11136
11137   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11138   MIB.addReg(t5);
11139   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11140   MIB.addReg(t6);
11141
11142   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11143   for (int i=0; i <= lastAddrIndx; ++i)
11144     (*MIB).addOperand(*argOpers[i]);
11145
11146   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11147   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11148                     bInstr->memoperands_end());
11149
11150   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11151   MIB.addReg(X86::EAX);
11152   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11153   MIB.addReg(X86::EDX);
11154
11155   // insert branch
11156   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11157
11158   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11159   return nextMBB;
11160 }
11161
11162 // private utility function
11163 MachineBasicBlock *
11164 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11165                                                       MachineBasicBlock *MBB,
11166                                                       unsigned cmovOpc) const {
11167   // For the atomic min/max operator, we generate
11168   //   thisMBB:
11169   //   newMBB:
11170   //     ld t1 = [min/max.addr]
11171   //     mov t2 = [min/max.val]
11172   //     cmp  t1, t2
11173   //     cmov[cond] t2 = t1
11174   //     mov EAX = t1
11175   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11176   //     bz   newMBB
11177   //     fallthrough -->nextMBB
11178   //
11179   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11180   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11181   MachineFunction::iterator MBBIter = MBB;
11182   ++MBBIter;
11183
11184   /// First build the CFG
11185   MachineFunction *F = MBB->getParent();
11186   MachineBasicBlock *thisMBB = MBB;
11187   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11188   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11189   F->insert(MBBIter, newMBB);
11190   F->insert(MBBIter, nextMBB);
11191
11192   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11193   nextMBB->splice(nextMBB->begin(), thisMBB,
11194                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11195                   thisMBB->end());
11196   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11197
11198   // Update thisMBB to fall through to newMBB
11199   thisMBB->addSuccessor(newMBB);
11200
11201   // newMBB jumps to newMBB and fall through to nextMBB
11202   newMBB->addSuccessor(nextMBB);
11203   newMBB->addSuccessor(newMBB);
11204
11205   DebugLoc dl = mInstr->getDebugLoc();
11206   // Insert instructions into newMBB based on incoming instruction
11207   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11208          "unexpected number of operands");
11209   MachineOperand& destOper = mInstr->getOperand(0);
11210   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11211   int numArgs = mInstr->getNumOperands() - 1;
11212   for (int i=0; i < numArgs; ++i)
11213     argOpers[i] = &mInstr->getOperand(i+1);
11214
11215   // x86 address has 4 operands: base, index, scale, and displacement
11216   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11217   int valArgIndx = lastAddrIndx + 1;
11218
11219   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11220   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11221   for (int i=0; i <= lastAddrIndx; ++i)
11222     (*MIB).addOperand(*argOpers[i]);
11223
11224   // We only support register and immediate values
11225   assert((argOpers[valArgIndx]->isReg() ||
11226           argOpers[valArgIndx]->isImm()) &&
11227          "invalid operand");
11228
11229   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11230   if (argOpers[valArgIndx]->isReg())
11231     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11232   else
11233     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11234   (*MIB).addOperand(*argOpers[valArgIndx]);
11235
11236   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11237   MIB.addReg(t1);
11238
11239   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11240   MIB.addReg(t1);
11241   MIB.addReg(t2);
11242
11243   // Generate movc
11244   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11245   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11246   MIB.addReg(t2);
11247   MIB.addReg(t1);
11248
11249   // Cmp and exchange if none has modified the memory location
11250   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11251   for (int i=0; i <= lastAddrIndx; ++i)
11252     (*MIB).addOperand(*argOpers[i]);
11253   MIB.addReg(t3);
11254   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11255   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11256                     mInstr->memoperands_end());
11257
11258   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11259   MIB.addReg(X86::EAX);
11260
11261   // insert branch
11262   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11263
11264   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11265   return nextMBB;
11266 }
11267
11268 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11269 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11270 // in the .td file.
11271 MachineBasicBlock *
11272 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11273                             unsigned numArgs, bool memArg) const {
11274   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11275          "Target must have SSE4.2 or AVX features enabled");
11276
11277   DebugLoc dl = MI->getDebugLoc();
11278   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11279   unsigned Opc;
11280   if (!Subtarget->hasAVX()) {
11281     if (memArg)
11282       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11283     else
11284       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11285   } else {
11286     if (memArg)
11287       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11288     else
11289       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11290   }
11291
11292   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11293   for (unsigned i = 0; i < numArgs; ++i) {
11294     MachineOperand &Op = MI->getOperand(i+1);
11295     if (!(Op.isReg() && Op.isImplicit()))
11296       MIB.addOperand(Op);
11297   }
11298   BuildMI(*BB, MI, dl,
11299     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11300              MI->getOperand(0).getReg())
11301     .addReg(X86::XMM0);
11302
11303   MI->eraseFromParent();
11304   return BB;
11305 }
11306
11307 MachineBasicBlock *
11308 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11309   DebugLoc dl = MI->getDebugLoc();
11310   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11311
11312   // Address into RAX/EAX, other two args into ECX, EDX.
11313   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11314   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11315   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11316   for (int i = 0; i < X86::AddrNumOperands; ++i)
11317     MIB.addOperand(MI->getOperand(i));
11318
11319   unsigned ValOps = X86::AddrNumOperands;
11320   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11321     .addReg(MI->getOperand(ValOps).getReg());
11322   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11323     .addReg(MI->getOperand(ValOps+1).getReg());
11324
11325   // The instruction doesn't actually take any operands though.
11326   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11327
11328   MI->eraseFromParent(); // The pseudo is gone now.
11329   return BB;
11330 }
11331
11332 MachineBasicBlock *
11333 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11334   DebugLoc dl = MI->getDebugLoc();
11335   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11336
11337   // First arg in ECX, the second in EAX.
11338   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11339     .addReg(MI->getOperand(0).getReg());
11340   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11341     .addReg(MI->getOperand(1).getReg());
11342
11343   // The instruction doesn't actually take any operands though.
11344   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11345
11346   MI->eraseFromParent(); // The pseudo is gone now.
11347   return BB;
11348 }
11349
11350 MachineBasicBlock *
11351 X86TargetLowering::EmitVAARG64WithCustomInserter(
11352                    MachineInstr *MI,
11353                    MachineBasicBlock *MBB) const {
11354   // Emit va_arg instruction on X86-64.
11355
11356   // Operands to this pseudo-instruction:
11357   // 0  ) Output        : destination address (reg)
11358   // 1-5) Input         : va_list address (addr, i64mem)
11359   // 6  ) ArgSize       : Size (in bytes) of vararg type
11360   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11361   // 8  ) Align         : Alignment of type
11362   // 9  ) EFLAGS (implicit-def)
11363
11364   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11365   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11366
11367   unsigned DestReg = MI->getOperand(0).getReg();
11368   MachineOperand &Base = MI->getOperand(1);
11369   MachineOperand &Scale = MI->getOperand(2);
11370   MachineOperand &Index = MI->getOperand(3);
11371   MachineOperand &Disp = MI->getOperand(4);
11372   MachineOperand &Segment = MI->getOperand(5);
11373   unsigned ArgSize = MI->getOperand(6).getImm();
11374   unsigned ArgMode = MI->getOperand(7).getImm();
11375   unsigned Align = MI->getOperand(8).getImm();
11376
11377   // Memory Reference
11378   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11379   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11380   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11381
11382   // Machine Information
11383   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11384   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11385   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11386   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11387   DebugLoc DL = MI->getDebugLoc();
11388
11389   // struct va_list {
11390   //   i32   gp_offset
11391   //   i32   fp_offset
11392   //   i64   overflow_area (address)
11393   //   i64   reg_save_area (address)
11394   // }
11395   // sizeof(va_list) = 24
11396   // alignment(va_list) = 8
11397
11398   unsigned TotalNumIntRegs = 6;
11399   unsigned TotalNumXMMRegs = 8;
11400   bool UseGPOffset = (ArgMode == 1);
11401   bool UseFPOffset = (ArgMode == 2);
11402   unsigned MaxOffset = TotalNumIntRegs * 8 +
11403                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11404
11405   /* Align ArgSize to a multiple of 8 */
11406   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11407   bool NeedsAlign = (Align > 8);
11408
11409   MachineBasicBlock *thisMBB = MBB;
11410   MachineBasicBlock *overflowMBB;
11411   MachineBasicBlock *offsetMBB;
11412   MachineBasicBlock *endMBB;
11413
11414   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11415   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11416   unsigned OffsetReg = 0;
11417
11418   if (!UseGPOffset && !UseFPOffset) {
11419     // If we only pull from the overflow region, we don't create a branch.
11420     // We don't need to alter control flow.
11421     OffsetDestReg = 0; // unused
11422     OverflowDestReg = DestReg;
11423
11424     offsetMBB = NULL;
11425     overflowMBB = thisMBB;
11426     endMBB = thisMBB;
11427   } else {
11428     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11429     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11430     // If not, pull from overflow_area. (branch to overflowMBB)
11431     //
11432     //       thisMBB
11433     //         |     .
11434     //         |        .
11435     //     offsetMBB   overflowMBB
11436     //         |        .
11437     //         |     .
11438     //        endMBB
11439
11440     // Registers for the PHI in endMBB
11441     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11442     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11443
11444     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11445     MachineFunction *MF = MBB->getParent();
11446     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11447     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11448     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11449
11450     MachineFunction::iterator MBBIter = MBB;
11451     ++MBBIter;
11452
11453     // Insert the new basic blocks
11454     MF->insert(MBBIter, offsetMBB);
11455     MF->insert(MBBIter, overflowMBB);
11456     MF->insert(MBBIter, endMBB);
11457
11458     // Transfer the remainder of MBB and its successor edges to endMBB.
11459     endMBB->splice(endMBB->begin(), thisMBB,
11460                     llvm::next(MachineBasicBlock::iterator(MI)),
11461                     thisMBB->end());
11462     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11463
11464     // Make offsetMBB and overflowMBB successors of thisMBB
11465     thisMBB->addSuccessor(offsetMBB);
11466     thisMBB->addSuccessor(overflowMBB);
11467
11468     // endMBB is a successor of both offsetMBB and overflowMBB
11469     offsetMBB->addSuccessor(endMBB);
11470     overflowMBB->addSuccessor(endMBB);
11471
11472     // Load the offset value into a register
11473     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11474     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
11475       .addOperand(Base)
11476       .addOperand(Scale)
11477       .addOperand(Index)
11478       .addDisp(Disp, UseFPOffset ? 4 : 0)
11479       .addOperand(Segment)
11480       .setMemRefs(MMOBegin, MMOEnd);
11481
11482     // Check if there is enough room left to pull this argument.
11483     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
11484       .addReg(OffsetReg)
11485       .addImm(MaxOffset + 8 - ArgSizeA8);
11486
11487     // Branch to "overflowMBB" if offset >= max
11488     // Fall through to "offsetMBB" otherwise
11489     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
11490       .addMBB(overflowMBB);
11491   }
11492
11493   // In offsetMBB, emit code to use the reg_save_area.
11494   if (offsetMBB) {
11495     assert(OffsetReg != 0);
11496
11497     // Read the reg_save_area address.
11498     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
11499     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
11500       .addOperand(Base)
11501       .addOperand(Scale)
11502       .addOperand(Index)
11503       .addDisp(Disp, 16)
11504       .addOperand(Segment)
11505       .setMemRefs(MMOBegin, MMOEnd);
11506
11507     // Zero-extend the offset
11508     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
11509       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
11510         .addImm(0)
11511         .addReg(OffsetReg)
11512         .addImm(X86::sub_32bit);
11513
11514     // Add the offset to the reg_save_area to get the final address.
11515     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
11516       .addReg(OffsetReg64)
11517       .addReg(RegSaveReg);
11518
11519     // Compute the offset for the next argument
11520     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
11521     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
11522       .addReg(OffsetReg)
11523       .addImm(UseFPOffset ? 16 : 8);
11524
11525     // Store it back into the va_list.
11526     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
11527       .addOperand(Base)
11528       .addOperand(Scale)
11529       .addOperand(Index)
11530       .addDisp(Disp, UseFPOffset ? 4 : 0)
11531       .addOperand(Segment)
11532       .addReg(NextOffsetReg)
11533       .setMemRefs(MMOBegin, MMOEnd);
11534
11535     // Jump to endMBB
11536     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
11537       .addMBB(endMBB);
11538   }
11539
11540   //
11541   // Emit code to use overflow area
11542   //
11543
11544   // Load the overflow_area address into a register.
11545   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
11546   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
11547     .addOperand(Base)
11548     .addOperand(Scale)
11549     .addOperand(Index)
11550     .addDisp(Disp, 8)
11551     .addOperand(Segment)
11552     .setMemRefs(MMOBegin, MMOEnd);
11553
11554   // If we need to align it, do so. Otherwise, just copy the address
11555   // to OverflowDestReg.
11556   if (NeedsAlign) {
11557     // Align the overflow address
11558     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
11559     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
11560
11561     // aligned_addr = (addr + (align-1)) & ~(align-1)
11562     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
11563       .addReg(OverflowAddrReg)
11564       .addImm(Align-1);
11565
11566     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
11567       .addReg(TmpReg)
11568       .addImm(~(uint64_t)(Align-1));
11569   } else {
11570     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
11571       .addReg(OverflowAddrReg);
11572   }
11573
11574   // Compute the next overflow address after this argument.
11575   // (the overflow address should be kept 8-byte aligned)
11576   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
11577   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
11578     .addReg(OverflowDestReg)
11579     .addImm(ArgSizeA8);
11580
11581   // Store the new overflow address.
11582   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
11583     .addOperand(Base)
11584     .addOperand(Scale)
11585     .addOperand(Index)
11586     .addDisp(Disp, 8)
11587     .addOperand(Segment)
11588     .addReg(NextAddrReg)
11589     .setMemRefs(MMOBegin, MMOEnd);
11590
11591   // If we branched, emit the PHI to the front of endMBB.
11592   if (offsetMBB) {
11593     BuildMI(*endMBB, endMBB->begin(), DL,
11594             TII->get(X86::PHI), DestReg)
11595       .addReg(OffsetDestReg).addMBB(offsetMBB)
11596       .addReg(OverflowDestReg).addMBB(overflowMBB);
11597   }
11598
11599   // Erase the pseudo instruction
11600   MI->eraseFromParent();
11601
11602   return endMBB;
11603 }
11604
11605 MachineBasicBlock *
11606 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
11607                                                  MachineInstr *MI,
11608                                                  MachineBasicBlock *MBB) const {
11609   // Emit code to save XMM registers to the stack. The ABI says that the
11610   // number of registers to save is given in %al, so it's theoretically
11611   // possible to do an indirect jump trick to avoid saving all of them,
11612   // however this code takes a simpler approach and just executes all
11613   // of the stores if %al is non-zero. It's less code, and it's probably
11614   // easier on the hardware branch predictor, and stores aren't all that
11615   // expensive anyway.
11616
11617   // Create the new basic blocks. One block contains all the XMM stores,
11618   // and one block is the final destination regardless of whether any
11619   // stores were performed.
11620   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11621   MachineFunction *F = MBB->getParent();
11622   MachineFunction::iterator MBBIter = MBB;
11623   ++MBBIter;
11624   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
11625   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
11626   F->insert(MBBIter, XMMSaveMBB);
11627   F->insert(MBBIter, EndMBB);
11628
11629   // Transfer the remainder of MBB and its successor edges to EndMBB.
11630   EndMBB->splice(EndMBB->begin(), MBB,
11631                  llvm::next(MachineBasicBlock::iterator(MI)),
11632                  MBB->end());
11633   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
11634
11635   // The original block will now fall through to the XMM save block.
11636   MBB->addSuccessor(XMMSaveMBB);
11637   // The XMMSaveMBB will fall through to the end block.
11638   XMMSaveMBB->addSuccessor(EndMBB);
11639
11640   // Now add the instructions.
11641   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11642   DebugLoc DL = MI->getDebugLoc();
11643
11644   unsigned CountReg = MI->getOperand(0).getReg();
11645   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
11646   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
11647
11648   if (!Subtarget->isTargetWin64()) {
11649     // If %al is 0, branch around the XMM save block.
11650     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
11651     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
11652     MBB->addSuccessor(EndMBB);
11653   }
11654
11655   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
11656   // In the XMM save block, save all the XMM argument registers.
11657   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
11658     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
11659     MachineMemOperand *MMO =
11660       F->getMachineMemOperand(
11661           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
11662         MachineMemOperand::MOStore,
11663         /*Size=*/16, /*Align=*/16);
11664     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
11665       .addFrameIndex(RegSaveFrameIndex)
11666       .addImm(/*Scale=*/1)
11667       .addReg(/*IndexReg=*/0)
11668       .addImm(/*Disp=*/Offset)
11669       .addReg(/*Segment=*/0)
11670       .addReg(MI->getOperand(i).getReg())
11671       .addMemOperand(MMO);
11672   }
11673
11674   MI->eraseFromParent();   // The pseudo instruction is gone now.
11675
11676   return EndMBB;
11677 }
11678
11679 MachineBasicBlock *
11680 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
11681                                      MachineBasicBlock *BB) const {
11682   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11683   DebugLoc DL = MI->getDebugLoc();
11684
11685   // To "insert" a SELECT_CC instruction, we actually have to insert the
11686   // diamond control-flow pattern.  The incoming instruction knows the
11687   // destination vreg to set, the condition code register to branch on, the
11688   // true/false values to select between, and a branch opcode to use.
11689   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11690   MachineFunction::iterator It = BB;
11691   ++It;
11692
11693   //  thisMBB:
11694   //  ...
11695   //   TrueVal = ...
11696   //   cmpTY ccX, r1, r2
11697   //   bCC copy1MBB
11698   //   fallthrough --> copy0MBB
11699   MachineBasicBlock *thisMBB = BB;
11700   MachineFunction *F = BB->getParent();
11701   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11702   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11703   F->insert(It, copy0MBB);
11704   F->insert(It, sinkMBB);
11705
11706   // If the EFLAGS register isn't dead in the terminator, then claim that it's
11707   // live into the sink and copy blocks.
11708   if (!MI->killsRegister(X86::EFLAGS)) {
11709     copy0MBB->addLiveIn(X86::EFLAGS);
11710     sinkMBB->addLiveIn(X86::EFLAGS);
11711   }
11712
11713   // Transfer the remainder of BB and its successor edges to sinkMBB.
11714   sinkMBB->splice(sinkMBB->begin(), BB,
11715                   llvm::next(MachineBasicBlock::iterator(MI)),
11716                   BB->end());
11717   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11718
11719   // Add the true and fallthrough blocks as its successors.
11720   BB->addSuccessor(copy0MBB);
11721   BB->addSuccessor(sinkMBB);
11722
11723   // Create the conditional branch instruction.
11724   unsigned Opc =
11725     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
11726   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
11727
11728   //  copy0MBB:
11729   //   %FalseValue = ...
11730   //   # fallthrough to sinkMBB
11731   copy0MBB->addSuccessor(sinkMBB);
11732
11733   //  sinkMBB:
11734   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11735   //  ...
11736   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11737           TII->get(X86::PHI), MI->getOperand(0).getReg())
11738     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
11739     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
11740
11741   MI->eraseFromParent();   // The pseudo instruction is gone now.
11742   return sinkMBB;
11743 }
11744
11745 MachineBasicBlock *
11746 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
11747                                         bool Is64Bit) const {
11748   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11749   DebugLoc DL = MI->getDebugLoc();
11750   MachineFunction *MF = BB->getParent();
11751   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11752
11753   assert(EnableSegmentedStacks);
11754
11755   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
11756   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
11757
11758   // BB:
11759   //  ... [Till the alloca]
11760   // If stacklet is not large enough, jump to mallocMBB
11761   //
11762   // bumpMBB:
11763   //  Allocate by subtracting from RSP
11764   //  Jump to continueMBB
11765   //
11766   // mallocMBB:
11767   //  Allocate by call to runtime
11768   //
11769   // continueMBB:
11770   //  ...
11771   //  [rest of original BB]
11772   //
11773
11774   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11775   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11776   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11777
11778   MachineRegisterInfo &MRI = MF->getRegInfo();
11779   const TargetRegisterClass *AddrRegClass =
11780     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
11781
11782   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11783     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
11784     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
11785     sizeVReg = MI->getOperand(1).getReg(),
11786     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
11787
11788   MachineFunction::iterator MBBIter = BB;
11789   ++MBBIter;
11790
11791   MF->insert(MBBIter, bumpMBB);
11792   MF->insert(MBBIter, mallocMBB);
11793   MF->insert(MBBIter, continueMBB);
11794
11795   continueMBB->splice(continueMBB->begin(), BB, llvm::next
11796                       (MachineBasicBlock::iterator(MI)), BB->end());
11797   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
11798
11799   // Add code to the main basic block to check if the stack limit has been hit,
11800   // and if so, jump to mallocMBB otherwise to bumpMBB.
11801   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
11802   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), tmpSPVReg)
11803     .addReg(tmpSPVReg).addReg(sizeVReg);
11804   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
11805     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
11806     .addReg(tmpSPVReg);
11807   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
11808
11809   // bumpMBB simply decreases the stack pointer, since we know the current
11810   // stacklet has enough space.
11811   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
11812     .addReg(tmpSPVReg);
11813   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
11814     .addReg(tmpSPVReg);
11815   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11816
11817   // Calls into a routine in libgcc to allocate more space from the heap.
11818   if (Is64Bit) {
11819     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
11820       .addReg(sizeVReg);
11821     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
11822     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
11823   } else {
11824     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
11825       .addImm(12);
11826     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
11827     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
11828       .addExternalSymbol("__morestack_allocate_stack_space");
11829   }
11830
11831   if (!Is64Bit)
11832     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
11833       .addImm(16);
11834
11835   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
11836     .addReg(Is64Bit ? X86::RAX : X86::EAX);
11837   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
11838
11839   // Set up the CFG correctly.
11840   BB->addSuccessor(bumpMBB);
11841   BB->addSuccessor(mallocMBB);
11842   mallocMBB->addSuccessor(continueMBB);
11843   bumpMBB->addSuccessor(continueMBB);
11844
11845   // Take care of the PHI nodes.
11846   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
11847           MI->getOperand(0).getReg())
11848     .addReg(mallocPtrVReg).addMBB(mallocMBB)
11849     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
11850
11851   // Delete the original pseudo instruction.
11852   MI->eraseFromParent();
11853
11854   // And we're done.
11855   return continueMBB;
11856 }
11857
11858 MachineBasicBlock *
11859 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
11860                                           MachineBasicBlock *BB) const {
11861   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11862   DebugLoc DL = MI->getDebugLoc();
11863
11864   assert(!Subtarget->isTargetEnvMacho());
11865
11866   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
11867   // non-trivial part is impdef of ESP.
11868
11869   if (Subtarget->isTargetWin64()) {
11870     if (Subtarget->isTargetCygMing()) {
11871       // ___chkstk(Mingw64):
11872       // Clobbers R10, R11, RAX and EFLAGS.
11873       // Updates RSP.
11874       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11875         .addExternalSymbol("___chkstk")
11876         .addReg(X86::RAX, RegState::Implicit)
11877         .addReg(X86::RSP, RegState::Implicit)
11878         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
11879         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
11880         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11881     } else {
11882       // __chkstk(MSVCRT): does not update stack pointer.
11883       // Clobbers R10, R11 and EFLAGS.
11884       // FIXME: RAX(allocated size) might be reused and not killed.
11885       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
11886         .addExternalSymbol("__chkstk")
11887         .addReg(X86::RAX, RegState::Implicit)
11888         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11889       // RAX has the offset to subtracted from RSP.
11890       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
11891         .addReg(X86::RSP)
11892         .addReg(X86::RAX);
11893     }
11894   } else {
11895     const char *StackProbeSymbol =
11896       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
11897
11898     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
11899       .addExternalSymbol(StackProbeSymbol)
11900       .addReg(X86::EAX, RegState::Implicit)
11901       .addReg(X86::ESP, RegState::Implicit)
11902       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
11903       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
11904       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11905   }
11906
11907   MI->eraseFromParent();   // The pseudo instruction is gone now.
11908   return BB;
11909 }
11910
11911 MachineBasicBlock *
11912 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
11913                                       MachineBasicBlock *BB) const {
11914   // This is pretty easy.  We're taking the value that we received from
11915   // our load from the relocation, sticking it in either RDI (x86-64)
11916   // or EAX and doing an indirect call.  The return value will then
11917   // be in the normal return register.
11918   const X86InstrInfo *TII
11919     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
11920   DebugLoc DL = MI->getDebugLoc();
11921   MachineFunction *F = BB->getParent();
11922
11923   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
11924   assert(MI->getOperand(3).isGlobal() && "This should be a global");
11925
11926   if (Subtarget->is64Bit()) {
11927     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11928                                       TII->get(X86::MOV64rm), X86::RDI)
11929     .addReg(X86::RIP)
11930     .addImm(0).addReg(0)
11931     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11932                       MI->getOperand(3).getTargetFlags())
11933     .addReg(0);
11934     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
11935     addDirectMem(MIB, X86::RDI);
11936   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
11937     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11938                                       TII->get(X86::MOV32rm), X86::EAX)
11939     .addReg(0)
11940     .addImm(0).addReg(0)
11941     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11942                       MI->getOperand(3).getTargetFlags())
11943     .addReg(0);
11944     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11945     addDirectMem(MIB, X86::EAX);
11946   } else {
11947     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
11948                                       TII->get(X86::MOV32rm), X86::EAX)
11949     .addReg(TII->getGlobalBaseReg(F))
11950     .addImm(0).addReg(0)
11951     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
11952                       MI->getOperand(3).getTargetFlags())
11953     .addReg(0);
11954     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
11955     addDirectMem(MIB, X86::EAX);
11956   }
11957
11958   MI->eraseFromParent(); // The pseudo instruction is gone now.
11959   return BB;
11960 }
11961
11962 MachineBasicBlock *
11963 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
11964                                                MachineBasicBlock *BB) const {
11965   switch (MI->getOpcode()) {
11966   default: assert(0 && "Unexpected instr type to insert");
11967   case X86::TAILJMPd64:
11968   case X86::TAILJMPr64:
11969   case X86::TAILJMPm64:
11970     assert(0 && "TAILJMP64 would not be touched here.");
11971   case X86::TCRETURNdi64:
11972   case X86::TCRETURNri64:
11973   case X86::TCRETURNmi64:
11974     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
11975     // On AMD64, additional defs should be added before register allocation.
11976     if (!Subtarget->isTargetWin64()) {
11977       MI->addRegisterDefined(X86::RSI);
11978       MI->addRegisterDefined(X86::RDI);
11979       MI->addRegisterDefined(X86::XMM6);
11980       MI->addRegisterDefined(X86::XMM7);
11981       MI->addRegisterDefined(X86::XMM8);
11982       MI->addRegisterDefined(X86::XMM9);
11983       MI->addRegisterDefined(X86::XMM10);
11984       MI->addRegisterDefined(X86::XMM11);
11985       MI->addRegisterDefined(X86::XMM12);
11986       MI->addRegisterDefined(X86::XMM13);
11987       MI->addRegisterDefined(X86::XMM14);
11988       MI->addRegisterDefined(X86::XMM15);
11989     }
11990     return BB;
11991   case X86::WIN_ALLOCA:
11992     return EmitLoweredWinAlloca(MI, BB);
11993   case X86::SEG_ALLOCA_32:
11994     return EmitLoweredSegAlloca(MI, BB, false);
11995   case X86::SEG_ALLOCA_64:
11996     return EmitLoweredSegAlloca(MI, BB, true);
11997   case X86::TLSCall_32:
11998   case X86::TLSCall_64:
11999     return EmitLoweredTLSCall(MI, BB);
12000   case X86::CMOV_GR8:
12001   case X86::CMOV_FR32:
12002   case X86::CMOV_FR64:
12003   case X86::CMOV_V4F32:
12004   case X86::CMOV_V2F64:
12005   case X86::CMOV_V2I64:
12006   case X86::CMOV_V8F32:
12007   case X86::CMOV_V4F64:
12008   case X86::CMOV_V4I64:
12009   case X86::CMOV_GR16:
12010   case X86::CMOV_GR32:
12011   case X86::CMOV_RFP32:
12012   case X86::CMOV_RFP64:
12013   case X86::CMOV_RFP80:
12014     return EmitLoweredSelect(MI, BB);
12015
12016   case X86::FP32_TO_INT16_IN_MEM:
12017   case X86::FP32_TO_INT32_IN_MEM:
12018   case X86::FP32_TO_INT64_IN_MEM:
12019   case X86::FP64_TO_INT16_IN_MEM:
12020   case X86::FP64_TO_INT32_IN_MEM:
12021   case X86::FP64_TO_INT64_IN_MEM:
12022   case X86::FP80_TO_INT16_IN_MEM:
12023   case X86::FP80_TO_INT32_IN_MEM:
12024   case X86::FP80_TO_INT64_IN_MEM: {
12025     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12026     DebugLoc DL = MI->getDebugLoc();
12027
12028     // Change the floating point control register to use "round towards zero"
12029     // mode when truncating to an integer value.
12030     MachineFunction *F = BB->getParent();
12031     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12032     addFrameReference(BuildMI(*BB, MI, DL,
12033                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12034
12035     // Load the old value of the high byte of the control word...
12036     unsigned OldCW =
12037       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12038     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12039                       CWFrameIdx);
12040
12041     // Set the high part to be round to zero...
12042     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12043       .addImm(0xC7F);
12044
12045     // Reload the modified control word now...
12046     addFrameReference(BuildMI(*BB, MI, DL,
12047                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12048
12049     // Restore the memory image of control word to original value
12050     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12051       .addReg(OldCW);
12052
12053     // Get the X86 opcode to use.
12054     unsigned Opc;
12055     switch (MI->getOpcode()) {
12056     default: llvm_unreachable("illegal opcode!");
12057     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12058     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12059     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12060     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12061     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12062     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12063     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12064     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12065     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12066     }
12067
12068     X86AddressMode AM;
12069     MachineOperand &Op = MI->getOperand(0);
12070     if (Op.isReg()) {
12071       AM.BaseType = X86AddressMode::RegBase;
12072       AM.Base.Reg = Op.getReg();
12073     } else {
12074       AM.BaseType = X86AddressMode::FrameIndexBase;
12075       AM.Base.FrameIndex = Op.getIndex();
12076     }
12077     Op = MI->getOperand(1);
12078     if (Op.isImm())
12079       AM.Scale = Op.getImm();
12080     Op = MI->getOperand(2);
12081     if (Op.isImm())
12082       AM.IndexReg = Op.getImm();
12083     Op = MI->getOperand(3);
12084     if (Op.isGlobal()) {
12085       AM.GV = Op.getGlobal();
12086     } else {
12087       AM.Disp = Op.getImm();
12088     }
12089     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12090                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12091
12092     // Reload the original control word now.
12093     addFrameReference(BuildMI(*BB, MI, DL,
12094                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12095
12096     MI->eraseFromParent();   // The pseudo instruction is gone now.
12097     return BB;
12098   }
12099     // String/text processing lowering.
12100   case X86::PCMPISTRM128REG:
12101   case X86::VPCMPISTRM128REG:
12102     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12103   case X86::PCMPISTRM128MEM:
12104   case X86::VPCMPISTRM128MEM:
12105     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12106   case X86::PCMPESTRM128REG:
12107   case X86::VPCMPESTRM128REG:
12108     return EmitPCMP(MI, BB, 5, false /* in mem */);
12109   case X86::PCMPESTRM128MEM:
12110   case X86::VPCMPESTRM128MEM:
12111     return EmitPCMP(MI, BB, 5, true /* in mem */);
12112
12113     // Thread synchronization.
12114   case X86::MONITOR:
12115     return EmitMonitor(MI, BB);
12116   case X86::MWAIT:
12117     return EmitMwait(MI, BB);
12118
12119     // Atomic Lowering.
12120   case X86::ATOMAND32:
12121     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12122                                                X86::AND32ri, X86::MOV32rm,
12123                                                X86::LCMPXCHG32,
12124                                                X86::NOT32r, X86::EAX,
12125                                                X86::GR32RegisterClass);
12126   case X86::ATOMOR32:
12127     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12128                                                X86::OR32ri, X86::MOV32rm,
12129                                                X86::LCMPXCHG32,
12130                                                X86::NOT32r, X86::EAX,
12131                                                X86::GR32RegisterClass);
12132   case X86::ATOMXOR32:
12133     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12134                                                X86::XOR32ri, X86::MOV32rm,
12135                                                X86::LCMPXCHG32,
12136                                                X86::NOT32r, X86::EAX,
12137                                                X86::GR32RegisterClass);
12138   case X86::ATOMNAND32:
12139     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12140                                                X86::AND32ri, X86::MOV32rm,
12141                                                X86::LCMPXCHG32,
12142                                                X86::NOT32r, X86::EAX,
12143                                                X86::GR32RegisterClass, true);
12144   case X86::ATOMMIN32:
12145     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12146   case X86::ATOMMAX32:
12147     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12148   case X86::ATOMUMIN32:
12149     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12150   case X86::ATOMUMAX32:
12151     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12152
12153   case X86::ATOMAND16:
12154     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12155                                                X86::AND16ri, X86::MOV16rm,
12156                                                X86::LCMPXCHG16,
12157                                                X86::NOT16r, X86::AX,
12158                                                X86::GR16RegisterClass);
12159   case X86::ATOMOR16:
12160     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12161                                                X86::OR16ri, X86::MOV16rm,
12162                                                X86::LCMPXCHG16,
12163                                                X86::NOT16r, X86::AX,
12164                                                X86::GR16RegisterClass);
12165   case X86::ATOMXOR16:
12166     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12167                                                X86::XOR16ri, X86::MOV16rm,
12168                                                X86::LCMPXCHG16,
12169                                                X86::NOT16r, X86::AX,
12170                                                X86::GR16RegisterClass);
12171   case X86::ATOMNAND16:
12172     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12173                                                X86::AND16ri, X86::MOV16rm,
12174                                                X86::LCMPXCHG16,
12175                                                X86::NOT16r, X86::AX,
12176                                                X86::GR16RegisterClass, true);
12177   case X86::ATOMMIN16:
12178     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12179   case X86::ATOMMAX16:
12180     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12181   case X86::ATOMUMIN16:
12182     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12183   case X86::ATOMUMAX16:
12184     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12185
12186   case X86::ATOMAND8:
12187     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12188                                                X86::AND8ri, X86::MOV8rm,
12189                                                X86::LCMPXCHG8,
12190                                                X86::NOT8r, X86::AL,
12191                                                X86::GR8RegisterClass);
12192   case X86::ATOMOR8:
12193     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12194                                                X86::OR8ri, X86::MOV8rm,
12195                                                X86::LCMPXCHG8,
12196                                                X86::NOT8r, X86::AL,
12197                                                X86::GR8RegisterClass);
12198   case X86::ATOMXOR8:
12199     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12200                                                X86::XOR8ri, X86::MOV8rm,
12201                                                X86::LCMPXCHG8,
12202                                                X86::NOT8r, X86::AL,
12203                                                X86::GR8RegisterClass);
12204   case X86::ATOMNAND8:
12205     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12206                                                X86::AND8ri, X86::MOV8rm,
12207                                                X86::LCMPXCHG8,
12208                                                X86::NOT8r, X86::AL,
12209                                                X86::GR8RegisterClass, true);
12210   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12211   // This group is for 64-bit host.
12212   case X86::ATOMAND64:
12213     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12214                                                X86::AND64ri32, X86::MOV64rm,
12215                                                X86::LCMPXCHG64,
12216                                                X86::NOT64r, X86::RAX,
12217                                                X86::GR64RegisterClass);
12218   case X86::ATOMOR64:
12219     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12220                                                X86::OR64ri32, X86::MOV64rm,
12221                                                X86::LCMPXCHG64,
12222                                                X86::NOT64r, X86::RAX,
12223                                                X86::GR64RegisterClass);
12224   case X86::ATOMXOR64:
12225     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12226                                                X86::XOR64ri32, X86::MOV64rm,
12227                                                X86::LCMPXCHG64,
12228                                                X86::NOT64r, X86::RAX,
12229                                                X86::GR64RegisterClass);
12230   case X86::ATOMNAND64:
12231     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12232                                                X86::AND64ri32, X86::MOV64rm,
12233                                                X86::LCMPXCHG64,
12234                                                X86::NOT64r, X86::RAX,
12235                                                X86::GR64RegisterClass, true);
12236   case X86::ATOMMIN64:
12237     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12238   case X86::ATOMMAX64:
12239     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12240   case X86::ATOMUMIN64:
12241     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12242   case X86::ATOMUMAX64:
12243     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12244
12245   // This group does 64-bit operations on a 32-bit host.
12246   case X86::ATOMAND6432:
12247     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12248                                                X86::AND32rr, X86::AND32rr,
12249                                                X86::AND32ri, X86::AND32ri,
12250                                                false);
12251   case X86::ATOMOR6432:
12252     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12253                                                X86::OR32rr, X86::OR32rr,
12254                                                X86::OR32ri, X86::OR32ri,
12255                                                false);
12256   case X86::ATOMXOR6432:
12257     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12258                                                X86::XOR32rr, X86::XOR32rr,
12259                                                X86::XOR32ri, X86::XOR32ri,
12260                                                false);
12261   case X86::ATOMNAND6432:
12262     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12263                                                X86::AND32rr, X86::AND32rr,
12264                                                X86::AND32ri, X86::AND32ri,
12265                                                true);
12266   case X86::ATOMADD6432:
12267     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12268                                                X86::ADD32rr, X86::ADC32rr,
12269                                                X86::ADD32ri, X86::ADC32ri,
12270                                                false);
12271   case X86::ATOMSUB6432:
12272     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12273                                                X86::SUB32rr, X86::SBB32rr,
12274                                                X86::SUB32ri, X86::SBB32ri,
12275                                                false);
12276   case X86::ATOMSWAP6432:
12277     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12278                                                X86::MOV32rr, X86::MOV32rr,
12279                                                X86::MOV32ri, X86::MOV32ri,
12280                                                false);
12281   case X86::VASTART_SAVE_XMM_REGS:
12282     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12283
12284   case X86::VAARG_64:
12285     return EmitVAARG64WithCustomInserter(MI, BB);
12286   }
12287 }
12288
12289 //===----------------------------------------------------------------------===//
12290 //                           X86 Optimization Hooks
12291 //===----------------------------------------------------------------------===//
12292
12293 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12294                                                        const APInt &Mask,
12295                                                        APInt &KnownZero,
12296                                                        APInt &KnownOne,
12297                                                        const SelectionDAG &DAG,
12298                                                        unsigned Depth) const {
12299   unsigned Opc = Op.getOpcode();
12300   assert((Opc >= ISD::BUILTIN_OP_END ||
12301           Opc == ISD::INTRINSIC_WO_CHAIN ||
12302           Opc == ISD::INTRINSIC_W_CHAIN ||
12303           Opc == ISD::INTRINSIC_VOID) &&
12304          "Should use MaskedValueIsZero if you don't know whether Op"
12305          " is a target node!");
12306
12307   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12308   switch (Opc) {
12309   default: break;
12310   case X86ISD::ADD:
12311   case X86ISD::SUB:
12312   case X86ISD::ADC:
12313   case X86ISD::SBB:
12314   case X86ISD::SMUL:
12315   case X86ISD::UMUL:
12316   case X86ISD::INC:
12317   case X86ISD::DEC:
12318   case X86ISD::OR:
12319   case X86ISD::XOR:
12320   case X86ISD::AND:
12321     // These nodes' second result is a boolean.
12322     if (Op.getResNo() == 0)
12323       break;
12324     // Fallthrough
12325   case X86ISD::SETCC:
12326     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12327                                        Mask.getBitWidth() - 1);
12328     break;
12329   case ISD::INTRINSIC_WO_CHAIN: {
12330     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12331     unsigned NumLoBits = 0;
12332     switch (IntId) {
12333     default: break;
12334     case Intrinsic::x86_sse_movmsk_ps:
12335     case Intrinsic::x86_avx_movmsk_ps_256:
12336     case Intrinsic::x86_sse2_movmsk_pd:
12337     case Intrinsic::x86_avx_movmsk_pd_256:
12338     case Intrinsic::x86_mmx_pmovmskb:
12339     case Intrinsic::x86_sse2_pmovmskb_128: {
12340       // High bits of movmskp{s|d}, pmovmskb are known zero.
12341       switch (IntId) {
12342         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12343         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12344         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12345         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12346         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12347         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12348       }
12349       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12350                                         Mask.getBitWidth() - NumLoBits);
12351       break;
12352     }
12353     }
12354     break;
12355   }
12356   }
12357 }
12358
12359 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12360                                                          unsigned Depth) const {
12361   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12362   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12363     return Op.getValueType().getScalarType().getSizeInBits();
12364
12365   // Fallback case.
12366   return 1;
12367 }
12368
12369 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12370 /// node is a GlobalAddress + offset.
12371 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12372                                        const GlobalValue* &GA,
12373                                        int64_t &Offset) const {
12374   if (N->getOpcode() == X86ISD::Wrapper) {
12375     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12376       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12377       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12378       return true;
12379     }
12380   }
12381   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12382 }
12383
12384 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12385 /// same as extracting the high 128-bit part of 256-bit vector and then
12386 /// inserting the result into the low part of a new 256-bit vector
12387 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12388   EVT VT = SVOp->getValueType(0);
12389   int NumElems = VT.getVectorNumElements();
12390
12391   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12392   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12393     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12394         SVOp->getMaskElt(j) >= 0)
12395       return false;
12396
12397   return true;
12398 }
12399
12400 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12401 /// same as extracting the low 128-bit part of 256-bit vector and then
12402 /// inserting the result into the high part of a new 256-bit vector
12403 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12404   EVT VT = SVOp->getValueType(0);
12405   int NumElems = VT.getVectorNumElements();
12406
12407   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12408   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12409     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12410         SVOp->getMaskElt(j) >= 0)
12411       return false;
12412
12413   return true;
12414 }
12415
12416 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12417 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12418                                         TargetLowering::DAGCombinerInfo &DCI) {
12419   DebugLoc dl = N->getDebugLoc();
12420   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12421   SDValue V1 = SVOp->getOperand(0);
12422   SDValue V2 = SVOp->getOperand(1);
12423   EVT VT = SVOp->getValueType(0);
12424   int NumElems = VT.getVectorNumElements();
12425
12426   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12427       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12428     //
12429     //                   0,0,0,...
12430     //                      |
12431     //    V      UNDEF    BUILD_VECTOR    UNDEF
12432     //     \      /           \           /
12433     //  CONCAT_VECTOR         CONCAT_VECTOR
12434     //         \                  /
12435     //          \                /
12436     //          RESULT: V + zero extended
12437     //
12438     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12439         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12440         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12441       return SDValue();
12442
12443     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12444       return SDValue();
12445
12446     // To match the shuffle mask, the first half of the mask should
12447     // be exactly the first vector, and all the rest a splat with the
12448     // first element of the second one.
12449     for (int i = 0; i < NumElems/2; ++i)
12450       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
12451           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
12452         return SDValue();
12453
12454     // Emit a zeroed vector and insert the desired subvector on its
12455     // first half.
12456     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
12457     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
12458                          DAG.getConstant(0, MVT::i32), DAG, dl);
12459     return DCI.CombineTo(N, InsV);
12460   }
12461
12462   //===--------------------------------------------------------------------===//
12463   // Combine some shuffles into subvector extracts and inserts:
12464   //
12465
12466   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12467   if (isShuffleHigh128VectorInsertLow(SVOp)) {
12468     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
12469                                     DAG, dl);
12470     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12471                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
12472     return DCI.CombineTo(N, InsV);
12473   }
12474
12475   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12476   if (isShuffleLow128VectorInsertHigh(SVOp)) {
12477     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
12478     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
12479                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
12480     return DCI.CombineTo(N, InsV);
12481   }
12482
12483   return SDValue();
12484 }
12485
12486 /// PerformShuffleCombine - Performs several different shuffle combines.
12487 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
12488                                      TargetLowering::DAGCombinerInfo &DCI,
12489                                      const X86Subtarget *Subtarget) {
12490   DebugLoc dl = N->getDebugLoc();
12491   EVT VT = N->getValueType(0);
12492
12493   // Don't create instructions with illegal types after legalize types has run.
12494   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12495   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
12496     return SDValue();
12497
12498   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
12499   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
12500       N->getOpcode() == ISD::VECTOR_SHUFFLE)
12501     return PerformShuffleCombine256(N, DAG, DCI);
12502
12503   // Only handle 128 wide vector from here on.
12504   if (VT.getSizeInBits() != 128)
12505     return SDValue();
12506
12507   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
12508   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
12509   // consecutive, non-overlapping, and in the right order.
12510   SmallVector<SDValue, 16> Elts;
12511   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
12512     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
12513
12514   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
12515 }
12516
12517 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
12518 /// generation and convert it from being a bunch of shuffles and extracts
12519 /// to a simple store and scalar loads to extract the elements.
12520 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
12521                                                 const TargetLowering &TLI) {
12522   SDValue InputVector = N->getOperand(0);
12523
12524   // Only operate on vectors of 4 elements, where the alternative shuffling
12525   // gets to be more expensive.
12526   if (InputVector.getValueType() != MVT::v4i32)
12527     return SDValue();
12528
12529   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
12530   // single use which is a sign-extend or zero-extend, and all elements are
12531   // used.
12532   SmallVector<SDNode *, 4> Uses;
12533   unsigned ExtractedElements = 0;
12534   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
12535        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
12536     if (UI.getUse().getResNo() != InputVector.getResNo())
12537       return SDValue();
12538
12539     SDNode *Extract = *UI;
12540     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12541       return SDValue();
12542
12543     if (Extract->getValueType(0) != MVT::i32)
12544       return SDValue();
12545     if (!Extract->hasOneUse())
12546       return SDValue();
12547     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
12548         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
12549       return SDValue();
12550     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
12551       return SDValue();
12552
12553     // Record which element was extracted.
12554     ExtractedElements |=
12555       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
12556
12557     Uses.push_back(Extract);
12558   }
12559
12560   // If not all the elements were used, this may not be worthwhile.
12561   if (ExtractedElements != 15)
12562     return SDValue();
12563
12564   // Ok, we've now decided to do the transformation.
12565   DebugLoc dl = InputVector.getDebugLoc();
12566
12567   // Store the value to a temporary stack slot.
12568   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
12569   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
12570                             MachinePointerInfo(), false, false, 0);
12571
12572   // Replace each use (extract) with a load of the appropriate element.
12573   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
12574        UE = Uses.end(); UI != UE; ++UI) {
12575     SDNode *Extract = *UI;
12576
12577     // cOMpute the element's address.
12578     SDValue Idx = Extract->getOperand(1);
12579     unsigned EltSize =
12580         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
12581     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
12582     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
12583
12584     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
12585                                      StackPtr, OffsetVal);
12586
12587     // Load the scalar.
12588     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
12589                                      ScalarAddr, MachinePointerInfo(),
12590                                      false, false, 0);
12591
12592     // Replace the exact with the load.
12593     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
12594   }
12595
12596   // The replacement was made in place; don't return anything.
12597   return SDValue();
12598 }
12599
12600 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
12601 /// nodes.
12602 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
12603                                     const X86Subtarget *Subtarget) {
12604   DebugLoc DL = N->getDebugLoc();
12605   SDValue Cond = N->getOperand(0);
12606   // Get the LHS/RHS of the select.
12607   SDValue LHS = N->getOperand(1);
12608   SDValue RHS = N->getOperand(2);
12609   EVT VT = LHS.getValueType();
12610
12611   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
12612   // instructions match the semantics of the common C idiom x<y?x:y but not
12613   // x<=y?x:y, because of how they handle negative zero (which can be
12614   // ignored in unsafe-math mode).
12615   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
12616       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
12617       (Subtarget->hasXMMInt() ||
12618        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
12619     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
12620
12621     unsigned Opcode = 0;
12622     // Check for x CC y ? x : y.
12623     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
12624         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
12625       switch (CC) {
12626       default: break;
12627       case ISD::SETULT:
12628         // Converting this to a min would handle NaNs incorrectly, and swapping
12629         // the operands would cause it to handle comparisons between positive
12630         // and negative zero incorrectly.
12631         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12632           if (!UnsafeFPMath &&
12633               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12634             break;
12635           std::swap(LHS, RHS);
12636         }
12637         Opcode = X86ISD::FMIN;
12638         break;
12639       case ISD::SETOLE:
12640         // Converting this to a min would handle comparisons between positive
12641         // and negative zero incorrectly.
12642         if (!UnsafeFPMath &&
12643             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12644           break;
12645         Opcode = X86ISD::FMIN;
12646         break;
12647       case ISD::SETULE:
12648         // Converting this to a min would handle both negative zeros and NaNs
12649         // incorrectly, but we can swap the operands to fix both.
12650         std::swap(LHS, RHS);
12651       case ISD::SETOLT:
12652       case ISD::SETLT:
12653       case ISD::SETLE:
12654         Opcode = X86ISD::FMIN;
12655         break;
12656
12657       case ISD::SETOGE:
12658         // Converting this to a max would handle comparisons between positive
12659         // and negative zero incorrectly.
12660         if (!UnsafeFPMath &&
12661             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
12662           break;
12663         Opcode = X86ISD::FMAX;
12664         break;
12665       case ISD::SETUGT:
12666         // Converting this to a max would handle NaNs incorrectly, and swapping
12667         // the operands would cause it to handle comparisons between positive
12668         // and negative zero incorrectly.
12669         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
12670           if (!UnsafeFPMath &&
12671               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
12672             break;
12673           std::swap(LHS, RHS);
12674         }
12675         Opcode = X86ISD::FMAX;
12676         break;
12677       case ISD::SETUGE:
12678         // Converting this to a max would handle both negative zeros and NaNs
12679         // incorrectly, but we can swap the operands to fix both.
12680         std::swap(LHS, RHS);
12681       case ISD::SETOGT:
12682       case ISD::SETGT:
12683       case ISD::SETGE:
12684         Opcode = X86ISD::FMAX;
12685         break;
12686       }
12687     // Check for x CC y ? y : x -- a min/max with reversed arms.
12688     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
12689                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
12690       switch (CC) {
12691       default: break;
12692       case ISD::SETOGE:
12693         // Converting this to a min would handle comparisons between positive
12694         // and negative zero incorrectly, and swapping the operands would
12695         // cause it to handle NaNs incorrectly.
12696         if (!UnsafeFPMath &&
12697             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
12698           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12699             break;
12700           std::swap(LHS, RHS);
12701         }
12702         Opcode = X86ISD::FMIN;
12703         break;
12704       case ISD::SETUGT:
12705         // Converting this to a min would handle NaNs incorrectly.
12706         if (!UnsafeFPMath &&
12707             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
12708           break;
12709         Opcode = X86ISD::FMIN;
12710         break;
12711       case ISD::SETUGE:
12712         // Converting this to a min would handle both negative zeros and NaNs
12713         // incorrectly, but we can swap the operands to fix both.
12714         std::swap(LHS, RHS);
12715       case ISD::SETOGT:
12716       case ISD::SETGT:
12717       case ISD::SETGE:
12718         Opcode = X86ISD::FMIN;
12719         break;
12720
12721       case ISD::SETULT:
12722         // Converting this to a max would handle NaNs incorrectly.
12723         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12724           break;
12725         Opcode = X86ISD::FMAX;
12726         break;
12727       case ISD::SETOLE:
12728         // Converting this to a max would handle comparisons between positive
12729         // and negative zero incorrectly, and swapping the operands would
12730         // cause it to handle NaNs incorrectly.
12731         if (!UnsafeFPMath &&
12732             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
12733           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
12734             break;
12735           std::swap(LHS, RHS);
12736         }
12737         Opcode = X86ISD::FMAX;
12738         break;
12739       case ISD::SETULE:
12740         // Converting this to a max would handle both negative zeros and NaNs
12741         // incorrectly, but we can swap the operands to fix both.
12742         std::swap(LHS, RHS);
12743       case ISD::SETOLT:
12744       case ISD::SETLT:
12745       case ISD::SETLE:
12746         Opcode = X86ISD::FMAX;
12747         break;
12748       }
12749     }
12750
12751     if (Opcode)
12752       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
12753   }
12754
12755   // If this is a select between two integer constants, try to do some
12756   // optimizations.
12757   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
12758     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
12759       // Don't do this for crazy integer types.
12760       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
12761         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
12762         // so that TrueC (the true value) is larger than FalseC.
12763         bool NeedsCondInvert = false;
12764
12765         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
12766             // Efficiently invertible.
12767             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
12768              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
12769               isa<ConstantSDNode>(Cond.getOperand(1))))) {
12770           NeedsCondInvert = true;
12771           std::swap(TrueC, FalseC);
12772         }
12773
12774         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
12775         if (FalseC->getAPIntValue() == 0 &&
12776             TrueC->getAPIntValue().isPowerOf2()) {
12777           if (NeedsCondInvert) // Invert the condition if needed.
12778             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12779                                DAG.getConstant(1, Cond.getValueType()));
12780
12781           // Zero extend the condition if needed.
12782           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
12783
12784           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12785           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
12786                              DAG.getConstant(ShAmt, MVT::i8));
12787         }
12788
12789         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
12790         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12791           if (NeedsCondInvert) // Invert the condition if needed.
12792             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12793                                DAG.getConstant(1, Cond.getValueType()));
12794
12795           // Zero extend the condition if needed.
12796           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12797                              FalseC->getValueType(0), Cond);
12798           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12799                              SDValue(FalseC, 0));
12800         }
12801
12802         // Optimize cases that will turn into an LEA instruction.  This requires
12803         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12804         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12805           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12806           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12807
12808           bool isFastMultiplier = false;
12809           if (Diff < 10) {
12810             switch ((unsigned char)Diff) {
12811               default: break;
12812               case 1:  // result = add base, cond
12813               case 2:  // result = lea base(    , cond*2)
12814               case 3:  // result = lea base(cond, cond*2)
12815               case 4:  // result = lea base(    , cond*4)
12816               case 5:  // result = lea base(cond, cond*4)
12817               case 8:  // result = lea base(    , cond*8)
12818               case 9:  // result = lea base(cond, cond*8)
12819                 isFastMultiplier = true;
12820                 break;
12821             }
12822           }
12823
12824           if (isFastMultiplier) {
12825             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12826             if (NeedsCondInvert) // Invert the condition if needed.
12827               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
12828                                  DAG.getConstant(1, Cond.getValueType()));
12829
12830             // Zero extend the condition if needed.
12831             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12832                                Cond);
12833             // Scale the condition by the difference.
12834             if (Diff != 1)
12835               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12836                                  DAG.getConstant(Diff, Cond.getValueType()));
12837
12838             // Add the base if non-zero.
12839             if (FalseC->getAPIntValue() != 0)
12840               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12841                                  SDValue(FalseC, 0));
12842             return Cond;
12843           }
12844         }
12845       }
12846   }
12847
12848   return SDValue();
12849 }
12850
12851 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
12852 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
12853                                   TargetLowering::DAGCombinerInfo &DCI) {
12854   DebugLoc DL = N->getDebugLoc();
12855
12856   // If the flag operand isn't dead, don't touch this CMOV.
12857   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
12858     return SDValue();
12859
12860   SDValue FalseOp = N->getOperand(0);
12861   SDValue TrueOp = N->getOperand(1);
12862   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
12863   SDValue Cond = N->getOperand(3);
12864   if (CC == X86::COND_E || CC == X86::COND_NE) {
12865     switch (Cond.getOpcode()) {
12866     default: break;
12867     case X86ISD::BSR:
12868     case X86ISD::BSF:
12869       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
12870       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
12871         return (CC == X86::COND_E) ? FalseOp : TrueOp;
12872     }
12873   }
12874
12875   // If this is a select between two integer constants, try to do some
12876   // optimizations.  Note that the operands are ordered the opposite of SELECT
12877   // operands.
12878   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
12879     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
12880       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
12881       // larger than FalseC (the false value).
12882       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
12883         CC = X86::GetOppositeBranchCondition(CC);
12884         std::swap(TrueC, FalseC);
12885       }
12886
12887       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
12888       // This is efficient for any integer data type (including i8/i16) and
12889       // shift amount.
12890       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
12891         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12892                            DAG.getConstant(CC, MVT::i8), Cond);
12893
12894         // Zero extend the condition if needed.
12895         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
12896
12897         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
12898         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
12899                            DAG.getConstant(ShAmt, MVT::i8));
12900         if (N->getNumValues() == 2)  // Dead flag value?
12901           return DCI.CombineTo(N, Cond, SDValue());
12902         return Cond;
12903       }
12904
12905       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
12906       // for any integer data type, including i8/i16.
12907       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
12908         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12909                            DAG.getConstant(CC, MVT::i8), Cond);
12910
12911         // Zero extend the condition if needed.
12912         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
12913                            FalseC->getValueType(0), Cond);
12914         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12915                            SDValue(FalseC, 0));
12916
12917         if (N->getNumValues() == 2)  // Dead flag value?
12918           return DCI.CombineTo(N, Cond, SDValue());
12919         return Cond;
12920       }
12921
12922       // Optimize cases that will turn into an LEA instruction.  This requires
12923       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
12924       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
12925         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
12926         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
12927
12928         bool isFastMultiplier = false;
12929         if (Diff < 10) {
12930           switch ((unsigned char)Diff) {
12931           default: break;
12932           case 1:  // result = add base, cond
12933           case 2:  // result = lea base(    , cond*2)
12934           case 3:  // result = lea base(cond, cond*2)
12935           case 4:  // result = lea base(    , cond*4)
12936           case 5:  // result = lea base(cond, cond*4)
12937           case 8:  // result = lea base(    , cond*8)
12938           case 9:  // result = lea base(cond, cond*8)
12939             isFastMultiplier = true;
12940             break;
12941           }
12942         }
12943
12944         if (isFastMultiplier) {
12945           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
12946           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12947                              DAG.getConstant(CC, MVT::i8), Cond);
12948           // Zero extend the condition if needed.
12949           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
12950                              Cond);
12951           // Scale the condition by the difference.
12952           if (Diff != 1)
12953             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
12954                                DAG.getConstant(Diff, Cond.getValueType()));
12955
12956           // Add the base if non-zero.
12957           if (FalseC->getAPIntValue() != 0)
12958             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
12959                                SDValue(FalseC, 0));
12960           if (N->getNumValues() == 2)  // Dead flag value?
12961             return DCI.CombineTo(N, Cond, SDValue());
12962           return Cond;
12963         }
12964       }
12965     }
12966   }
12967   return SDValue();
12968 }
12969
12970
12971 /// PerformMulCombine - Optimize a single multiply with constant into two
12972 /// in order to implement it with two cheaper instructions, e.g.
12973 /// LEA + SHL, LEA + LEA.
12974 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
12975                                  TargetLowering::DAGCombinerInfo &DCI) {
12976   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12977     return SDValue();
12978
12979   EVT VT = N->getValueType(0);
12980   if (VT != MVT::i64)
12981     return SDValue();
12982
12983   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12984   if (!C)
12985     return SDValue();
12986   uint64_t MulAmt = C->getZExtValue();
12987   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
12988     return SDValue();
12989
12990   uint64_t MulAmt1 = 0;
12991   uint64_t MulAmt2 = 0;
12992   if ((MulAmt % 9) == 0) {
12993     MulAmt1 = 9;
12994     MulAmt2 = MulAmt / 9;
12995   } else if ((MulAmt % 5) == 0) {
12996     MulAmt1 = 5;
12997     MulAmt2 = MulAmt / 5;
12998   } else if ((MulAmt % 3) == 0) {
12999     MulAmt1 = 3;
13000     MulAmt2 = MulAmt / 3;
13001   }
13002   if (MulAmt2 &&
13003       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13004     DebugLoc DL = N->getDebugLoc();
13005
13006     if (isPowerOf2_64(MulAmt2) &&
13007         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13008       // If second multiplifer is pow2, issue it first. We want the multiply by
13009       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13010       // is an add.
13011       std::swap(MulAmt1, MulAmt2);
13012
13013     SDValue NewMul;
13014     if (isPowerOf2_64(MulAmt1))
13015       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13016                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13017     else
13018       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13019                            DAG.getConstant(MulAmt1, VT));
13020
13021     if (isPowerOf2_64(MulAmt2))
13022       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13023                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13024     else
13025       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13026                            DAG.getConstant(MulAmt2, VT));
13027
13028     // Do not add new nodes to DAG combiner worklist.
13029     DCI.CombineTo(N, NewMul, false);
13030   }
13031   return SDValue();
13032 }
13033
13034 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13035   SDValue N0 = N->getOperand(0);
13036   SDValue N1 = N->getOperand(1);
13037   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13038   EVT VT = N0.getValueType();
13039
13040   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13041   // since the result of setcc_c is all zero's or all ones.
13042   if (N1C && N0.getOpcode() == ISD::AND &&
13043       N0.getOperand(1).getOpcode() == ISD::Constant) {
13044     SDValue N00 = N0.getOperand(0);
13045     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13046         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13047           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13048          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13049       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13050       APInt ShAmt = N1C->getAPIntValue();
13051       Mask = Mask.shl(ShAmt);
13052       if (Mask != 0)
13053         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13054                            N00, DAG.getConstant(Mask, VT));
13055     }
13056   }
13057
13058   return SDValue();
13059 }
13060
13061 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13062 ///                       when possible.
13063 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13064                                    const X86Subtarget *Subtarget) {
13065   EVT VT = N->getValueType(0);
13066   if (!VT.isVector() && VT.isInteger() &&
13067       N->getOpcode() == ISD::SHL)
13068     return PerformSHLCombine(N, DAG);
13069
13070   // On X86 with SSE2 support, we can transform this to a vector shift if
13071   // all elements are shifted by the same amount.  We can't do this in legalize
13072   // because the a constant vector is typically transformed to a constant pool
13073   // so we have no knowledge of the shift amount.
13074   if (!Subtarget->hasXMMInt())
13075     return SDValue();
13076
13077   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
13078     return SDValue();
13079
13080   SDValue ShAmtOp = N->getOperand(1);
13081   EVT EltVT = VT.getVectorElementType();
13082   DebugLoc DL = N->getDebugLoc();
13083   SDValue BaseShAmt = SDValue();
13084   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13085     unsigned NumElts = VT.getVectorNumElements();
13086     unsigned i = 0;
13087     for (; i != NumElts; ++i) {
13088       SDValue Arg = ShAmtOp.getOperand(i);
13089       if (Arg.getOpcode() == ISD::UNDEF) continue;
13090       BaseShAmt = Arg;
13091       break;
13092     }
13093     for (; i != NumElts; ++i) {
13094       SDValue Arg = ShAmtOp.getOperand(i);
13095       if (Arg.getOpcode() == ISD::UNDEF) continue;
13096       if (Arg != BaseShAmt) {
13097         return SDValue();
13098       }
13099     }
13100   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13101              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13102     SDValue InVec = ShAmtOp.getOperand(0);
13103     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13104       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13105       unsigned i = 0;
13106       for (; i != NumElts; ++i) {
13107         SDValue Arg = InVec.getOperand(i);
13108         if (Arg.getOpcode() == ISD::UNDEF) continue;
13109         BaseShAmt = Arg;
13110         break;
13111       }
13112     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13113        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13114          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13115          if (C->getZExtValue() == SplatIdx)
13116            BaseShAmt = InVec.getOperand(1);
13117        }
13118     }
13119     if (BaseShAmt.getNode() == 0)
13120       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13121                               DAG.getIntPtrConstant(0));
13122   } else
13123     return SDValue();
13124
13125   // The shift amount is an i32.
13126   if (EltVT.bitsGT(MVT::i32))
13127     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13128   else if (EltVT.bitsLT(MVT::i32))
13129     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13130
13131   // The shift amount is identical so we can do a vector shift.
13132   SDValue  ValOp = N->getOperand(0);
13133   switch (N->getOpcode()) {
13134   default:
13135     llvm_unreachable("Unknown shift opcode!");
13136     break;
13137   case ISD::SHL:
13138     if (VT == MVT::v2i64)
13139       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13140                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13141                          ValOp, BaseShAmt);
13142     if (VT == MVT::v4i32)
13143       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13144                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13145                          ValOp, BaseShAmt);
13146     if (VT == MVT::v8i16)
13147       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13148                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13149                          ValOp, BaseShAmt);
13150     break;
13151   case ISD::SRA:
13152     if (VT == MVT::v4i32)
13153       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13154                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13155                          ValOp, BaseShAmt);
13156     if (VT == MVT::v8i16)
13157       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13158                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13159                          ValOp, BaseShAmt);
13160     break;
13161   case ISD::SRL:
13162     if (VT == MVT::v2i64)
13163       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13164                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13165                          ValOp, BaseShAmt);
13166     if (VT == MVT::v4i32)
13167       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13168                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13169                          ValOp, BaseShAmt);
13170     if (VT ==  MVT::v8i16)
13171       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13172                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13173                          ValOp, BaseShAmt);
13174     break;
13175   }
13176   return SDValue();
13177 }
13178
13179
13180 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13181 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13182 // and friends.  Likewise for OR -> CMPNEQSS.
13183 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13184                             TargetLowering::DAGCombinerInfo &DCI,
13185                             const X86Subtarget *Subtarget) {
13186   unsigned opcode;
13187
13188   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13189   // we're requiring SSE2 for both.
13190   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13191     SDValue N0 = N->getOperand(0);
13192     SDValue N1 = N->getOperand(1);
13193     SDValue CMP0 = N0->getOperand(1);
13194     SDValue CMP1 = N1->getOperand(1);
13195     DebugLoc DL = N->getDebugLoc();
13196
13197     // The SETCCs should both refer to the same CMP.
13198     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13199       return SDValue();
13200
13201     SDValue CMP00 = CMP0->getOperand(0);
13202     SDValue CMP01 = CMP0->getOperand(1);
13203     EVT     VT    = CMP00.getValueType();
13204
13205     if (VT == MVT::f32 || VT == MVT::f64) {
13206       bool ExpectingFlags = false;
13207       // Check for any users that want flags:
13208       for (SDNode::use_iterator UI = N->use_begin(),
13209              UE = N->use_end();
13210            !ExpectingFlags && UI != UE; ++UI)
13211         switch (UI->getOpcode()) {
13212         default:
13213         case ISD::BR_CC:
13214         case ISD::BRCOND:
13215         case ISD::SELECT:
13216           ExpectingFlags = true;
13217           break;
13218         case ISD::CopyToReg:
13219         case ISD::SIGN_EXTEND:
13220         case ISD::ZERO_EXTEND:
13221         case ISD::ANY_EXTEND:
13222           break;
13223         }
13224
13225       if (!ExpectingFlags) {
13226         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13227         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13228
13229         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13230           X86::CondCode tmp = cc0;
13231           cc0 = cc1;
13232           cc1 = tmp;
13233         }
13234
13235         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13236             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13237           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13238           X86ISD::NodeType NTOperator = is64BitFP ?
13239             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13240           // FIXME: need symbolic constants for these magic numbers.
13241           // See X86ATTInstPrinter.cpp:printSSECC().
13242           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13243           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13244                                               DAG.getConstant(x86cc, MVT::i8));
13245           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13246                                               OnesOrZeroesF);
13247           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13248                                       DAG.getConstant(1, MVT::i32));
13249           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13250           return OneBitOfTruth;
13251         }
13252       }
13253     }
13254   }
13255   return SDValue();
13256 }
13257
13258 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13259 /// so it can be folded inside ANDNP.
13260 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13261   EVT VT = N->getValueType(0);
13262
13263   // Match direct AllOnes for 128 and 256-bit vectors
13264   if (ISD::isBuildVectorAllOnes(N))
13265     return true;
13266
13267   // Look through a bit convert.
13268   if (N->getOpcode() == ISD::BITCAST)
13269     N = N->getOperand(0).getNode();
13270
13271   // Sometimes the operand may come from a insert_subvector building a 256-bit
13272   // allones vector
13273   if (VT.getSizeInBits() == 256 &&
13274       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13275     SDValue V1 = N->getOperand(0);
13276     SDValue V2 = N->getOperand(1);
13277
13278     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13279         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13280         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13281         ISD::isBuildVectorAllOnes(V2.getNode()))
13282       return true;
13283   }
13284
13285   return false;
13286 }
13287
13288 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13289                                  TargetLowering::DAGCombinerInfo &DCI,
13290                                  const X86Subtarget *Subtarget) {
13291   if (DCI.isBeforeLegalizeOps())
13292     return SDValue();
13293
13294   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13295   if (R.getNode())
13296     return R;
13297
13298   // Want to form ANDNP nodes:
13299   // 1) In the hopes of then easily combining them with OR and AND nodes
13300   //    to form PBLEND/PSIGN.
13301   // 2) To match ANDN packed intrinsics
13302   EVT VT = N->getValueType(0);
13303   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13304     return SDValue();
13305
13306   SDValue N0 = N->getOperand(0);
13307   SDValue N1 = N->getOperand(1);
13308   DebugLoc DL = N->getDebugLoc();
13309
13310   // Check LHS for vnot
13311   if (N0.getOpcode() == ISD::XOR &&
13312       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13313       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13314     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13315
13316   // Check RHS for vnot
13317   if (N1.getOpcode() == ISD::XOR &&
13318       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13319       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13320     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13321
13322   return SDValue();
13323 }
13324
13325 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13326                                 TargetLowering::DAGCombinerInfo &DCI,
13327                                 const X86Subtarget *Subtarget) {
13328   if (DCI.isBeforeLegalizeOps())
13329     return SDValue();
13330
13331   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13332   if (R.getNode())
13333     return R;
13334
13335   EVT VT = N->getValueType(0);
13336   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
13337     return SDValue();
13338
13339   SDValue N0 = N->getOperand(0);
13340   SDValue N1 = N->getOperand(1);
13341
13342   // look for psign/blend
13343   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
13344     if (VT == MVT::v2i64) {
13345       // Canonicalize pandn to RHS
13346       if (N0.getOpcode() == X86ISD::ANDNP)
13347         std::swap(N0, N1);
13348       // or (and (m, x), (pandn m, y))
13349       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13350         SDValue Mask = N1.getOperand(0);
13351         SDValue X    = N1.getOperand(1);
13352         SDValue Y;
13353         if (N0.getOperand(0) == Mask)
13354           Y = N0.getOperand(1);
13355         if (N0.getOperand(1) == Mask)
13356           Y = N0.getOperand(0);
13357
13358         // Check to see if the mask appeared in both the AND and ANDNP and
13359         if (!Y.getNode())
13360           return SDValue();
13361
13362         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
13363         if (Mask.getOpcode() != ISD::BITCAST ||
13364             X.getOpcode() != ISD::BITCAST ||
13365             Y.getOpcode() != ISD::BITCAST)
13366           return SDValue();
13367
13368         // Look through mask bitcast.
13369         Mask = Mask.getOperand(0);
13370         EVT MaskVT = Mask.getValueType();
13371
13372         // Validate that the Mask operand is a vector sra node.  The sra node
13373         // will be an intrinsic.
13374         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
13375           return SDValue();
13376
13377         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
13378         // there is no psrai.b
13379         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
13380         case Intrinsic::x86_sse2_psrai_w:
13381         case Intrinsic::x86_sse2_psrai_d:
13382           break;
13383         default: return SDValue();
13384         }
13385
13386         // Check that the SRA is all signbits.
13387         SDValue SraC = Mask.getOperand(2);
13388         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
13389         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
13390         if ((SraAmt + 1) != EltBits)
13391           return SDValue();
13392
13393         DebugLoc DL = N->getDebugLoc();
13394
13395         // Now we know we at least have a plendvb with the mask val.  See if
13396         // we can form a psignb/w/d.
13397         // psign = x.type == y.type == mask.type && y = sub(0, x);
13398         X = X.getOperand(0);
13399         Y = Y.getOperand(0);
13400         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
13401             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
13402             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
13403           unsigned Opc = 0;
13404           switch (EltBits) {
13405           case 8: Opc = X86ISD::PSIGNB; break;
13406           case 16: Opc = X86ISD::PSIGNW; break;
13407           case 32: Opc = X86ISD::PSIGND; break;
13408           default: break;
13409           }
13410           if (Opc) {
13411             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
13412             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
13413           }
13414         }
13415         // PBLENDVB only available on SSE 4.1
13416         if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
13417           return SDValue();
13418
13419         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
13420         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
13421         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
13422         Mask = DAG.getNode(ISD::VSELECT, DL, MVT::v16i8, Mask, X, Y);
13423         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
13424       }
13425     }
13426   }
13427
13428   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
13429   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
13430     std::swap(N0, N1);
13431   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
13432     return SDValue();
13433   if (!N0.hasOneUse() || !N1.hasOneUse())
13434     return SDValue();
13435
13436   SDValue ShAmt0 = N0.getOperand(1);
13437   if (ShAmt0.getValueType() != MVT::i8)
13438     return SDValue();
13439   SDValue ShAmt1 = N1.getOperand(1);
13440   if (ShAmt1.getValueType() != MVT::i8)
13441     return SDValue();
13442   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
13443     ShAmt0 = ShAmt0.getOperand(0);
13444   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
13445     ShAmt1 = ShAmt1.getOperand(0);
13446
13447   DebugLoc DL = N->getDebugLoc();
13448   unsigned Opc = X86ISD::SHLD;
13449   SDValue Op0 = N0.getOperand(0);
13450   SDValue Op1 = N1.getOperand(0);
13451   if (ShAmt0.getOpcode() == ISD::SUB) {
13452     Opc = X86ISD::SHRD;
13453     std::swap(Op0, Op1);
13454     std::swap(ShAmt0, ShAmt1);
13455   }
13456
13457   unsigned Bits = VT.getSizeInBits();
13458   if (ShAmt1.getOpcode() == ISD::SUB) {
13459     SDValue Sum = ShAmt1.getOperand(0);
13460     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
13461       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
13462       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
13463         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
13464       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
13465         return DAG.getNode(Opc, DL, VT,
13466                            Op0, Op1,
13467                            DAG.getNode(ISD::TRUNCATE, DL,
13468                                        MVT::i8, ShAmt0));
13469     }
13470   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
13471     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
13472     if (ShAmt0C &&
13473         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
13474       return DAG.getNode(Opc, DL, VT,
13475                          N0.getOperand(0), N1.getOperand(0),
13476                          DAG.getNode(ISD::TRUNCATE, DL,
13477                                        MVT::i8, ShAmt0));
13478   }
13479
13480   return SDValue();
13481 }
13482
13483 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
13484 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
13485                                    const X86Subtarget *Subtarget) {
13486   LoadSDNode *Ld = cast<LoadSDNode>(N);
13487   EVT RegVT = Ld->getValueType(0);
13488   EVT MemVT = Ld->getMemoryVT();
13489   DebugLoc dl = Ld->getDebugLoc();
13490   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13491
13492   ISD::LoadExtType Ext = Ld->getExtensionType();
13493
13494   // If this is a vector EXT Load then attempt to optimize it using a
13495   // shuffle. We need SSE4 for the shuffles.
13496   // TODO: It is possible to support ZExt by zeroing the undef values
13497   // during the shuffle phase or after the shuffle.
13498   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
13499     assert(MemVT != RegVT && "Cannot extend to the same type");
13500     assert(MemVT.isVector() && "Must load a vector from memory");
13501
13502     unsigned NumElems = RegVT.getVectorNumElements();
13503     unsigned RegSz = RegVT.getSizeInBits();
13504     unsigned MemSz = MemVT.getSizeInBits();
13505     assert(RegSz > MemSz && "Register size must be greater than the mem size");
13506     // All sizes must be a power of two
13507     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
13508
13509     // Attempt to load the original value using a single load op.
13510     // Find a scalar type which is equal to the loaded word size.
13511     MVT SclrLoadTy = MVT::i8;
13512     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13513          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13514       MVT Tp = (MVT::SimpleValueType)tp;
13515       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
13516         SclrLoadTy = Tp;
13517         break;
13518       }
13519     }
13520
13521     // Proceed if a load word is found.
13522     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
13523
13524     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
13525       RegSz/SclrLoadTy.getSizeInBits());
13526
13527     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13528                                   RegSz/MemVT.getScalarType().getSizeInBits());
13529     // Can't shuffle using an illegal type.
13530     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13531
13532     // Perform a single load.
13533     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
13534                                   Ld->getBasePtr(),
13535                                   Ld->getPointerInfo(), Ld->isVolatile(),
13536                                   Ld->isNonTemporal(), Ld->getAlignment());
13537
13538     // Insert the word loaded into a vector.
13539     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
13540       LoadUnitVecVT, ScalarLoad);
13541
13542     // Bitcast the loaded value to a vector of the original element type, in
13543     // the size of the target vector type.
13544     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
13545     unsigned SizeRatio = RegSz/MemSz;
13546
13547     // Redistribute the loaded elements into the different locations.
13548     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13549     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
13550
13551     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13552                                 DAG.getUNDEF(SlicedVec.getValueType()),
13553                                 ShuffleVec.data());
13554
13555     // Bitcast to the requested type.
13556     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13557     // Replace the original load with the new sequence
13558     // and return the new chain.
13559     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
13560     return SDValue(ScalarLoad.getNode(), 1);
13561   }
13562
13563   return SDValue();
13564 }
13565
13566 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
13567 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
13568                                    const X86Subtarget *Subtarget) {
13569   StoreSDNode *St = cast<StoreSDNode>(N);
13570   EVT VT = St->getValue().getValueType();
13571   EVT StVT = St->getMemoryVT();
13572   DebugLoc dl = St->getDebugLoc();
13573   SDValue StoredVal = St->getOperand(1);
13574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13575
13576   // If we are saving a concatination of two XMM registers, perform two stores.
13577   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
13578   // 128-bit ones. If in the future the cost becomes only one memory access the
13579   // first version would be better.
13580   if (VT.getSizeInBits() == 256 &&
13581     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
13582     StoredVal.getNumOperands() == 2) {
13583
13584     SDValue Value0 = StoredVal.getOperand(0);
13585     SDValue Value1 = StoredVal.getOperand(1);
13586
13587     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
13588     SDValue Ptr0 = St->getBasePtr();
13589     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
13590
13591     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
13592                                 St->getPointerInfo(), St->isVolatile(),
13593                                 St->isNonTemporal(), St->getAlignment());
13594     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
13595                                 St->getPointerInfo(), St->isVolatile(),
13596                                 St->isNonTemporal(), St->getAlignment());
13597     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
13598   }
13599
13600   // Optimize trunc store (of multiple scalars) to shuffle and store.
13601   // First, pack all of the elements in one place. Next, store to memory
13602   // in fewer chunks.
13603   if (St->isTruncatingStore() && VT.isVector()) {
13604     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13605     unsigned NumElems = VT.getVectorNumElements();
13606     assert(StVT != VT && "Cannot truncate to the same type");
13607     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
13608     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
13609
13610     // From, To sizes and ElemCount must be pow of two
13611     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
13612     // We are going to use the original vector elt for storing.
13613     // Accumulated smaller vector elements must be a multiple of the store size.
13614     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
13615
13616     unsigned SizeRatio  = FromSz / ToSz;
13617
13618     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
13619
13620     // Create a type on which we perform the shuffle
13621     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
13622             StVT.getScalarType(), NumElems*SizeRatio);
13623
13624     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13625
13626     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
13627     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13628     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
13629
13630     // Can't shuffle using an illegal type
13631     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
13632
13633     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
13634                                 DAG.getUNDEF(WideVec.getValueType()),
13635                                 ShuffleVec.data());
13636     // At this point all of the data is stored at the bottom of the
13637     // register. We now need to save it to mem.
13638
13639     // Find the largest store unit
13640     MVT StoreType = MVT::i8;
13641     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13642          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13643       MVT Tp = (MVT::SimpleValueType)tp;
13644       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
13645         StoreType = Tp;
13646     }
13647
13648     // Bitcast the original vector into a vector of store-size units
13649     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
13650             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
13651     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13652     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
13653     SmallVector<SDValue, 8> Chains;
13654     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
13655                                         TLI.getPointerTy());
13656     SDValue Ptr = St->getBasePtr();
13657
13658     // Perform one or more big stores into memory.
13659     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
13660       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
13661                                    StoreType, ShuffWide,
13662                                    DAG.getIntPtrConstant(i));
13663       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
13664                                 St->getPointerInfo(), St->isVolatile(),
13665                                 St->isNonTemporal(), St->getAlignment());
13666       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13667       Chains.push_back(Ch);
13668     }
13669
13670     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
13671                                Chains.size());
13672   }
13673
13674
13675   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
13676   // the FP state in cases where an emms may be missing.
13677   // A preferable solution to the general problem is to figure out the right
13678   // places to insert EMMS.  This qualifies as a quick hack.
13679
13680   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
13681   if (VT.getSizeInBits() != 64)
13682     return SDValue();
13683
13684   const Function *F = DAG.getMachineFunction().getFunction();
13685   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
13686   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
13687                      && Subtarget->hasXMMInt();
13688   if ((VT.isVector() ||
13689        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
13690       isa<LoadSDNode>(St->getValue()) &&
13691       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
13692       St->getChain().hasOneUse() && !St->isVolatile()) {
13693     SDNode* LdVal = St->getValue().getNode();
13694     LoadSDNode *Ld = 0;
13695     int TokenFactorIndex = -1;
13696     SmallVector<SDValue, 8> Ops;
13697     SDNode* ChainVal = St->getChain().getNode();
13698     // Must be a store of a load.  We currently handle two cases:  the load
13699     // is a direct child, and it's under an intervening TokenFactor.  It is
13700     // possible to dig deeper under nested TokenFactors.
13701     if (ChainVal == LdVal)
13702       Ld = cast<LoadSDNode>(St->getChain());
13703     else if (St->getValue().hasOneUse() &&
13704              ChainVal->getOpcode() == ISD::TokenFactor) {
13705       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
13706         if (ChainVal->getOperand(i).getNode() == LdVal) {
13707           TokenFactorIndex = i;
13708           Ld = cast<LoadSDNode>(St->getValue());
13709         } else
13710           Ops.push_back(ChainVal->getOperand(i));
13711       }
13712     }
13713
13714     if (!Ld || !ISD::isNormalLoad(Ld))
13715       return SDValue();
13716
13717     // If this is not the MMX case, i.e. we are just turning i64 load/store
13718     // into f64 load/store, avoid the transformation if there are multiple
13719     // uses of the loaded value.
13720     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
13721       return SDValue();
13722
13723     DebugLoc LdDL = Ld->getDebugLoc();
13724     DebugLoc StDL = N->getDebugLoc();
13725     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
13726     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
13727     // pair instead.
13728     if (Subtarget->is64Bit() || F64IsLegal) {
13729       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
13730       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
13731                                   Ld->getPointerInfo(), Ld->isVolatile(),
13732                                   Ld->isNonTemporal(), Ld->getAlignment());
13733       SDValue NewChain = NewLd.getValue(1);
13734       if (TokenFactorIndex != -1) {
13735         Ops.push_back(NewChain);
13736         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13737                                Ops.size());
13738       }
13739       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
13740                           St->getPointerInfo(),
13741                           St->isVolatile(), St->isNonTemporal(),
13742                           St->getAlignment());
13743     }
13744
13745     // Otherwise, lower to two pairs of 32-bit loads / stores.
13746     SDValue LoAddr = Ld->getBasePtr();
13747     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
13748                                  DAG.getConstant(4, MVT::i32));
13749
13750     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
13751                                Ld->getPointerInfo(),
13752                                Ld->isVolatile(), Ld->isNonTemporal(),
13753                                Ld->getAlignment());
13754     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
13755                                Ld->getPointerInfo().getWithOffset(4),
13756                                Ld->isVolatile(), Ld->isNonTemporal(),
13757                                MinAlign(Ld->getAlignment(), 4));
13758
13759     SDValue NewChain = LoLd.getValue(1);
13760     if (TokenFactorIndex != -1) {
13761       Ops.push_back(LoLd);
13762       Ops.push_back(HiLd);
13763       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
13764                              Ops.size());
13765     }
13766
13767     LoAddr = St->getBasePtr();
13768     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
13769                          DAG.getConstant(4, MVT::i32));
13770
13771     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
13772                                 St->getPointerInfo(),
13773                                 St->isVolatile(), St->isNonTemporal(),
13774                                 St->getAlignment());
13775     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
13776                                 St->getPointerInfo().getWithOffset(4),
13777                                 St->isVolatile(),
13778                                 St->isNonTemporal(),
13779                                 MinAlign(St->getAlignment(), 4));
13780     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
13781   }
13782   return SDValue();
13783 }
13784
13785 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
13786 /// and return the operands for the horizontal operation in LHS and RHS.  A
13787 /// horizontal operation performs the binary operation on successive elements
13788 /// of its first operand, then on successive elements of its second operand,
13789 /// returning the resulting values in a vector.  For example, if
13790 ///   A = < float a0, float a1, float a2, float a3 >
13791 /// and
13792 ///   B = < float b0, float b1, float b2, float b3 >
13793 /// then the result of doing a horizontal operation on A and B is
13794 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
13795 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
13796 /// A horizontal-op B, for some already available A and B, and if so then LHS is
13797 /// set to A, RHS to B, and the routine returns 'true'.
13798 /// Note that the binary operation should have the property that if one of the
13799 /// operands is UNDEF then the result is UNDEF.
13800 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
13801   // Look for the following pattern: if
13802   //   A = < float a0, float a1, float a2, float a3 >
13803   //   B = < float b0, float b1, float b2, float b3 >
13804   // and
13805   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
13806   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
13807   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
13808   // which is A horizontal-op B.
13809
13810   // At least one of the operands should be a vector shuffle.
13811   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13812       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
13813     return false;
13814
13815   EVT VT = LHS.getValueType();
13816   unsigned N = VT.getVectorNumElements();
13817
13818   // View LHS in the form
13819   //   LHS = VECTOR_SHUFFLE A, B, LMask
13820   // If LHS is not a shuffle then pretend it is the shuffle
13821   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
13822   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
13823   // type VT.
13824   SDValue A, B;
13825   SmallVector<int, 8> LMask(N);
13826   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13827     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
13828       A = LHS.getOperand(0);
13829     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
13830       B = LHS.getOperand(1);
13831     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
13832   } else {
13833     if (LHS.getOpcode() != ISD::UNDEF)
13834       A = LHS;
13835     for (unsigned i = 0; i != N; ++i)
13836       LMask[i] = i;
13837   }
13838
13839   // Likewise, view RHS in the form
13840   //   RHS = VECTOR_SHUFFLE C, D, RMask
13841   SDValue C, D;
13842   SmallVector<int, 8> RMask(N);
13843   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
13844     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
13845       C = RHS.getOperand(0);
13846     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
13847       D = RHS.getOperand(1);
13848     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
13849   } else {
13850     if (RHS.getOpcode() != ISD::UNDEF)
13851       C = RHS;
13852     for (unsigned i = 0; i != N; ++i)
13853       RMask[i] = i;
13854   }
13855
13856   // Check that the shuffles are both shuffling the same vectors.
13857   if (!(A == C && B == D) && !(A == D && B == C))
13858     return false;
13859
13860   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
13861   if (!A.getNode() && !B.getNode())
13862     return false;
13863
13864   // If A and B occur in reverse order in RHS, then "swap" them (which means
13865   // rewriting the mask).
13866   if (A != C)
13867     for (unsigned i = 0; i != N; ++i) {
13868       unsigned Idx = RMask[i];
13869       if (Idx < N)
13870         RMask[i] += N;
13871       else if (Idx < 2*N)
13872         RMask[i] -= N;
13873     }
13874
13875   // At this point LHS and RHS are equivalent to
13876   //   LHS = VECTOR_SHUFFLE A, B, LMask
13877   //   RHS = VECTOR_SHUFFLE A, B, RMask
13878   // Check that the masks correspond to performing a horizontal operation.
13879   for (unsigned i = 0; i != N; ++i) {
13880     unsigned LIdx = LMask[i], RIdx = RMask[i];
13881
13882     // Ignore any UNDEF components.
13883     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
13884         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
13885       continue;
13886
13887     // Check that successive elements are being operated on.  If not, this is
13888     // not a horizontal operation.
13889     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
13890         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
13891       return false;
13892   }
13893
13894   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
13895   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
13896   return true;
13897 }
13898
13899 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
13900 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
13901                                   const X86Subtarget *Subtarget) {
13902   EVT VT = N->getValueType(0);
13903   SDValue LHS = N->getOperand(0);
13904   SDValue RHS = N->getOperand(1);
13905
13906   // Try to synthesize horizontal adds from adds of shuffles.
13907   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13908       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13909       isHorizontalBinOp(LHS, RHS, true))
13910     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
13911   return SDValue();
13912 }
13913
13914 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
13915 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
13916                                   const X86Subtarget *Subtarget) {
13917   EVT VT = N->getValueType(0);
13918   SDValue LHS = N->getOperand(0);
13919   SDValue RHS = N->getOperand(1);
13920
13921   // Try to synthesize horizontal subs from subs of shuffles.
13922   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
13923       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
13924       isHorizontalBinOp(LHS, RHS, false))
13925     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
13926   return SDValue();
13927 }
13928
13929 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
13930 /// X86ISD::FXOR nodes.
13931 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
13932   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
13933   // F[X]OR(0.0, x) -> x
13934   // F[X]OR(x, 0.0) -> x
13935   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13936     if (C->getValueAPF().isPosZero())
13937       return N->getOperand(1);
13938   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13939     if (C->getValueAPF().isPosZero())
13940       return N->getOperand(0);
13941   return SDValue();
13942 }
13943
13944 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
13945 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
13946   // FAND(0.0, x) -> 0.0
13947   // FAND(x, 0.0) -> 0.0
13948   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
13949     if (C->getValueAPF().isPosZero())
13950       return N->getOperand(0);
13951   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
13952     if (C->getValueAPF().isPosZero())
13953       return N->getOperand(1);
13954   return SDValue();
13955 }
13956
13957 static SDValue PerformBTCombine(SDNode *N,
13958                                 SelectionDAG &DAG,
13959                                 TargetLowering::DAGCombinerInfo &DCI) {
13960   // BT ignores high bits in the bit index operand.
13961   SDValue Op1 = N->getOperand(1);
13962   if (Op1.hasOneUse()) {
13963     unsigned BitWidth = Op1.getValueSizeInBits();
13964     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
13965     APInt KnownZero, KnownOne;
13966     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
13967                                           !DCI.isBeforeLegalizeOps());
13968     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13969     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
13970         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
13971       DCI.CommitTargetLoweringOpt(TLO);
13972   }
13973   return SDValue();
13974 }
13975
13976 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
13977   SDValue Op = N->getOperand(0);
13978   if (Op.getOpcode() == ISD::BITCAST)
13979     Op = Op.getOperand(0);
13980   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
13981   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
13982       VT.getVectorElementType().getSizeInBits() ==
13983       OpVT.getVectorElementType().getSizeInBits()) {
13984     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
13985   }
13986   return SDValue();
13987 }
13988
13989 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
13990   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
13991   //           (and (i32 x86isd::setcc_carry), 1)
13992   // This eliminates the zext. This transformation is necessary because
13993   // ISD::SETCC is always legalized to i8.
13994   DebugLoc dl = N->getDebugLoc();
13995   SDValue N0 = N->getOperand(0);
13996   EVT VT = N->getValueType(0);
13997   if (N0.getOpcode() == ISD::AND &&
13998       N0.hasOneUse() &&
13999       N0.getOperand(0).hasOneUse()) {
14000     SDValue N00 = N0.getOperand(0);
14001     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14002       return SDValue();
14003     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14004     if (!C || C->getZExtValue() != 1)
14005       return SDValue();
14006     return DAG.getNode(ISD::AND, dl, VT,
14007                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14008                                    N00.getOperand(0), N00.getOperand(1)),
14009                        DAG.getConstant(1, VT));
14010   }
14011
14012   return SDValue();
14013 }
14014
14015 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14016 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14017   unsigned X86CC = N->getConstantOperandVal(0);
14018   SDValue EFLAG = N->getOperand(1);
14019   DebugLoc DL = N->getDebugLoc();
14020
14021   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14022   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14023   // cases.
14024   if (X86CC == X86::COND_B)
14025     return DAG.getNode(ISD::AND, DL, MVT::i8,
14026                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14027                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14028                        DAG.getConstant(1, MVT::i8));
14029
14030   return SDValue();
14031 }
14032
14033 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14034                                         const X86TargetLowering *XTLI) {
14035   SDValue Op0 = N->getOperand(0);
14036   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14037   // a 32-bit target where SSE doesn't support i64->FP operations.
14038   if (Op0.getOpcode() == ISD::LOAD) {
14039     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14040     EVT VT = Ld->getValueType(0);
14041     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14042         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14043         !XTLI->getSubtarget()->is64Bit() &&
14044         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14045       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14046                                           Ld->getChain(), Op0, DAG);
14047       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14048       return FILDChain;
14049     }
14050   }
14051   return SDValue();
14052 }
14053
14054 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14055 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14056                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14057   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14058   // the result is either zero or one (depending on the input carry bit).
14059   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14060   if (X86::isZeroNode(N->getOperand(0)) &&
14061       X86::isZeroNode(N->getOperand(1)) &&
14062       // We don't have a good way to replace an EFLAGS use, so only do this when
14063       // dead right now.
14064       SDValue(N, 1).use_empty()) {
14065     DebugLoc DL = N->getDebugLoc();
14066     EVT VT = N->getValueType(0);
14067     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14068     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14069                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14070                                            DAG.getConstant(X86::COND_B,MVT::i8),
14071                                            N->getOperand(2)),
14072                                DAG.getConstant(1, VT));
14073     return DCI.CombineTo(N, Res1, CarryOut);
14074   }
14075
14076   return SDValue();
14077 }
14078
14079 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14080 //      (add Y, (setne X, 0)) -> sbb -1, Y
14081 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14082 //      (sub (setne X, 0), Y) -> adc -1, Y
14083 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14084   DebugLoc DL = N->getDebugLoc();
14085
14086   // Look through ZExts.
14087   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14088   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14089     return SDValue();
14090
14091   SDValue SetCC = Ext.getOperand(0);
14092   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14093     return SDValue();
14094
14095   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14096   if (CC != X86::COND_E && CC != X86::COND_NE)
14097     return SDValue();
14098
14099   SDValue Cmp = SetCC.getOperand(1);
14100   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14101       !X86::isZeroNode(Cmp.getOperand(1)) ||
14102       !Cmp.getOperand(0).getValueType().isInteger())
14103     return SDValue();
14104
14105   SDValue CmpOp0 = Cmp.getOperand(0);
14106   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14107                                DAG.getConstant(1, CmpOp0.getValueType()));
14108
14109   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14110   if (CC == X86::COND_NE)
14111     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14112                        DL, OtherVal.getValueType(), OtherVal,
14113                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14114   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14115                      DL, OtherVal.getValueType(), OtherVal,
14116                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14117 }
14118
14119 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG) {
14120   SDValue Op0 = N->getOperand(0);
14121   SDValue Op1 = N->getOperand(1);
14122
14123   // X86 can't encode an immediate LHS of a sub. See if we can push the
14124   // negation into a preceding instruction.
14125   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14126     // If the RHS of the sub is a XOR with one use and a constant, invert the
14127     // immediate. Then add one to the LHS of the sub so we can turn
14128     // X-Y -> X+~Y+1, saving one register.
14129     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14130         isa<ConstantSDNode>(Op1.getOperand(1))) {
14131       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14132       EVT VT = Op0.getValueType();
14133       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14134                                    Op1.getOperand(0),
14135                                    DAG.getConstant(~XorC, VT));
14136       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14137                          DAG.getConstant(C->getAPIntValue()+1, VT));
14138     }
14139   }
14140
14141   return OptimizeConditionalInDecrement(N, DAG);
14142 }
14143
14144 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14145                                              DAGCombinerInfo &DCI) const {
14146   SelectionDAG &DAG = DCI.DAG;
14147   switch (N->getOpcode()) {
14148   default: break;
14149   case ISD::EXTRACT_VECTOR_ELT:
14150     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14151   case ISD::VSELECT:
14152   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14153   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14154   case ISD::ADD:            return OptimizeConditionalInDecrement(N, DAG);
14155   case ISD::SUB:            return PerformSubCombine(N, DAG);
14156   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14157   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14158   case ISD::SHL:
14159   case ISD::SRA:
14160   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14161   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14162   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14163   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14164   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14165   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14166   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14167   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14168   case X86ISD::FXOR:
14169   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14170   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14171   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14172   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14173   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14174   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14175   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14176   case X86ISD::SHUFPD:
14177   case X86ISD::PALIGN:
14178   case X86ISD::PUNPCKHBW:
14179   case X86ISD::PUNPCKHWD:
14180   case X86ISD::PUNPCKHDQ:
14181   case X86ISD::PUNPCKHQDQ:
14182   case X86ISD::UNPCKHPS:
14183   case X86ISD::UNPCKHPD:
14184   case X86ISD::VUNPCKHPSY:
14185   case X86ISD::VUNPCKHPDY:
14186   case X86ISD::PUNPCKLBW:
14187   case X86ISD::PUNPCKLWD:
14188   case X86ISD::PUNPCKLDQ:
14189   case X86ISD::PUNPCKLQDQ:
14190   case X86ISD::UNPCKLPS:
14191   case X86ISD::UNPCKLPD:
14192   case X86ISD::VUNPCKLPSY:
14193   case X86ISD::VUNPCKLPDY:
14194   case X86ISD::MOVHLPS:
14195   case X86ISD::MOVLHPS:
14196   case X86ISD::PSHUFD:
14197   case X86ISD::PSHUFHW:
14198   case X86ISD::PSHUFLW:
14199   case X86ISD::MOVSS:
14200   case X86ISD::MOVSD:
14201   case X86ISD::VPERMILPS:
14202   case X86ISD::VPERMILPSY:
14203   case X86ISD::VPERMILPD:
14204   case X86ISD::VPERMILPDY:
14205   case X86ISD::VPERM2F128:
14206   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14207   }
14208
14209   return SDValue();
14210 }
14211
14212 /// isTypeDesirableForOp - Return true if the target has native support for
14213 /// the specified value type and it is 'desirable' to use the type for the
14214 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14215 /// instruction encodings are longer and some i16 instructions are slow.
14216 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14217   if (!isTypeLegal(VT))
14218     return false;
14219   if (VT != MVT::i16)
14220     return true;
14221
14222   switch (Opc) {
14223   default:
14224     return true;
14225   case ISD::LOAD:
14226   case ISD::SIGN_EXTEND:
14227   case ISD::ZERO_EXTEND:
14228   case ISD::ANY_EXTEND:
14229   case ISD::SHL:
14230   case ISD::SRL:
14231   case ISD::SUB:
14232   case ISD::ADD:
14233   case ISD::MUL:
14234   case ISD::AND:
14235   case ISD::OR:
14236   case ISD::XOR:
14237     return false;
14238   }
14239 }
14240
14241 /// IsDesirableToPromoteOp - This method query the target whether it is
14242 /// beneficial for dag combiner to promote the specified node. If true, it
14243 /// should return the desired promotion type by reference.
14244 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14245   EVT VT = Op.getValueType();
14246   if (VT != MVT::i16)
14247     return false;
14248
14249   bool Promote = false;
14250   bool Commute = false;
14251   switch (Op.getOpcode()) {
14252   default: break;
14253   case ISD::LOAD: {
14254     LoadSDNode *LD = cast<LoadSDNode>(Op);
14255     // If the non-extending load has a single use and it's not live out, then it
14256     // might be folded.
14257     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14258                                                      Op.hasOneUse()*/) {
14259       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14260              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14261         // The only case where we'd want to promote LOAD (rather then it being
14262         // promoted as an operand is when it's only use is liveout.
14263         if (UI->getOpcode() != ISD::CopyToReg)
14264           return false;
14265       }
14266     }
14267     Promote = true;
14268     break;
14269   }
14270   case ISD::SIGN_EXTEND:
14271   case ISD::ZERO_EXTEND:
14272   case ISD::ANY_EXTEND:
14273     Promote = true;
14274     break;
14275   case ISD::SHL:
14276   case ISD::SRL: {
14277     SDValue N0 = Op.getOperand(0);
14278     // Look out for (store (shl (load), x)).
14279     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14280       return false;
14281     Promote = true;
14282     break;
14283   }
14284   case ISD::ADD:
14285   case ISD::MUL:
14286   case ISD::AND:
14287   case ISD::OR:
14288   case ISD::XOR:
14289     Commute = true;
14290     // fallthrough
14291   case ISD::SUB: {
14292     SDValue N0 = Op.getOperand(0);
14293     SDValue N1 = Op.getOperand(1);
14294     if (!Commute && MayFoldLoad(N1))
14295       return false;
14296     // Avoid disabling potential load folding opportunities.
14297     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
14298       return false;
14299     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
14300       return false;
14301     Promote = true;
14302   }
14303   }
14304
14305   PVT = MVT::i32;
14306   return Promote;
14307 }
14308
14309 //===----------------------------------------------------------------------===//
14310 //                           X86 Inline Assembly Support
14311 //===----------------------------------------------------------------------===//
14312
14313 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
14314   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
14315
14316   std::string AsmStr = IA->getAsmString();
14317
14318   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
14319   SmallVector<StringRef, 4> AsmPieces;
14320   SplitString(AsmStr, AsmPieces, ";\n");
14321
14322   switch (AsmPieces.size()) {
14323   default: return false;
14324   case 1:
14325     AsmStr = AsmPieces[0];
14326     AsmPieces.clear();
14327     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
14328
14329     // FIXME: this should verify that we are targeting a 486 or better.  If not,
14330     // we will turn this bswap into something that will be lowered to logical ops
14331     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
14332     // so don't worry about this.
14333     // bswap $0
14334     if (AsmPieces.size() == 2 &&
14335         (AsmPieces[0] == "bswap" ||
14336          AsmPieces[0] == "bswapq" ||
14337          AsmPieces[0] == "bswapl") &&
14338         (AsmPieces[1] == "$0" ||
14339          AsmPieces[1] == "${0:q}")) {
14340       // No need to check constraints, nothing other than the equivalent of
14341       // "=r,0" would be valid here.
14342       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14343       if (!Ty || Ty->getBitWidth() % 16 != 0)
14344         return false;
14345       return IntrinsicLowering::LowerToByteSwap(CI);
14346     }
14347     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
14348     if (CI->getType()->isIntegerTy(16) &&
14349         AsmPieces.size() == 3 &&
14350         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
14351         AsmPieces[1] == "$$8," &&
14352         AsmPieces[2] == "${0:w}" &&
14353         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14354       AsmPieces.clear();
14355       const std::string &ConstraintsStr = IA->getConstraintString();
14356       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14357       std::sort(AsmPieces.begin(), AsmPieces.end());
14358       if (AsmPieces.size() == 4 &&
14359           AsmPieces[0] == "~{cc}" &&
14360           AsmPieces[1] == "~{dirflag}" &&
14361           AsmPieces[2] == "~{flags}" &&
14362           AsmPieces[3] == "~{fpsr}") {
14363         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14364         if (!Ty || Ty->getBitWidth() % 16 != 0)
14365           return false;
14366         return IntrinsicLowering::LowerToByteSwap(CI);
14367       }
14368     }
14369     break;
14370   case 3:
14371     if (CI->getType()->isIntegerTy(32) &&
14372         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
14373       SmallVector<StringRef, 4> Words;
14374       SplitString(AsmPieces[0], Words, " \t,");
14375       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14376           Words[2] == "${0:w}") {
14377         Words.clear();
14378         SplitString(AsmPieces[1], Words, " \t,");
14379         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
14380             Words[2] == "$0") {
14381           Words.clear();
14382           SplitString(AsmPieces[2], Words, " \t,");
14383           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
14384               Words[2] == "${0:w}") {
14385             AsmPieces.clear();
14386             const std::string &ConstraintsStr = IA->getConstraintString();
14387             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
14388             std::sort(AsmPieces.begin(), AsmPieces.end());
14389             if (AsmPieces.size() == 4 &&
14390                 AsmPieces[0] == "~{cc}" &&
14391                 AsmPieces[1] == "~{dirflag}" &&
14392                 AsmPieces[2] == "~{flags}" &&
14393                 AsmPieces[3] == "~{fpsr}") {
14394               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14395               if (!Ty || Ty->getBitWidth() % 16 != 0)
14396                 return false;
14397               return IntrinsicLowering::LowerToByteSwap(CI);
14398             }
14399           }
14400         }
14401       }
14402     }
14403
14404     if (CI->getType()->isIntegerTy(64)) {
14405       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
14406       if (Constraints.size() >= 2 &&
14407           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
14408           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
14409         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
14410         SmallVector<StringRef, 4> Words;
14411         SplitString(AsmPieces[0], Words, " \t");
14412         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
14413           Words.clear();
14414           SplitString(AsmPieces[1], Words, " \t");
14415           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
14416             Words.clear();
14417             SplitString(AsmPieces[2], Words, " \t,");
14418             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
14419                 Words[2] == "%edx") {
14420               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
14421               if (!Ty || Ty->getBitWidth() % 16 != 0)
14422                 return false;
14423               return IntrinsicLowering::LowerToByteSwap(CI);
14424             }
14425           }
14426         }
14427       }
14428     }
14429     break;
14430   }
14431   return false;
14432 }
14433
14434
14435
14436 /// getConstraintType - Given a constraint letter, return the type of
14437 /// constraint it is for this target.
14438 X86TargetLowering::ConstraintType
14439 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
14440   if (Constraint.size() == 1) {
14441     switch (Constraint[0]) {
14442     case 'R':
14443     case 'q':
14444     case 'Q':
14445     case 'f':
14446     case 't':
14447     case 'u':
14448     case 'y':
14449     case 'x':
14450     case 'Y':
14451     case 'l':
14452       return C_RegisterClass;
14453     case 'a':
14454     case 'b':
14455     case 'c':
14456     case 'd':
14457     case 'S':
14458     case 'D':
14459     case 'A':
14460       return C_Register;
14461     case 'I':
14462     case 'J':
14463     case 'K':
14464     case 'L':
14465     case 'M':
14466     case 'N':
14467     case 'G':
14468     case 'C':
14469     case 'e':
14470     case 'Z':
14471       return C_Other;
14472     default:
14473       break;
14474     }
14475   }
14476   return TargetLowering::getConstraintType(Constraint);
14477 }
14478
14479 /// Examine constraint type and operand type and determine a weight value.
14480 /// This object must already have been set up with the operand type
14481 /// and the current alternative constraint selected.
14482 TargetLowering::ConstraintWeight
14483   X86TargetLowering::getSingleConstraintMatchWeight(
14484     AsmOperandInfo &info, const char *constraint) const {
14485   ConstraintWeight weight = CW_Invalid;
14486   Value *CallOperandVal = info.CallOperandVal;
14487     // If we don't have a value, we can't do a match,
14488     // but allow it at the lowest weight.
14489   if (CallOperandVal == NULL)
14490     return CW_Default;
14491   Type *type = CallOperandVal->getType();
14492   // Look at the constraint type.
14493   switch (*constraint) {
14494   default:
14495     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14496   case 'R':
14497   case 'q':
14498   case 'Q':
14499   case 'a':
14500   case 'b':
14501   case 'c':
14502   case 'd':
14503   case 'S':
14504   case 'D':
14505   case 'A':
14506     if (CallOperandVal->getType()->isIntegerTy())
14507       weight = CW_SpecificReg;
14508     break;
14509   case 'f':
14510   case 't':
14511   case 'u':
14512       if (type->isFloatingPointTy())
14513         weight = CW_SpecificReg;
14514       break;
14515   case 'y':
14516       if (type->isX86_MMXTy() && Subtarget->hasMMX())
14517         weight = CW_SpecificReg;
14518       break;
14519   case 'x':
14520   case 'Y':
14521     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
14522       weight = CW_Register;
14523     break;
14524   case 'I':
14525     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
14526       if (C->getZExtValue() <= 31)
14527         weight = CW_Constant;
14528     }
14529     break;
14530   case 'J':
14531     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14532       if (C->getZExtValue() <= 63)
14533         weight = CW_Constant;
14534     }
14535     break;
14536   case 'K':
14537     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14538       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
14539         weight = CW_Constant;
14540     }
14541     break;
14542   case 'L':
14543     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14544       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
14545         weight = CW_Constant;
14546     }
14547     break;
14548   case 'M':
14549     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14550       if (C->getZExtValue() <= 3)
14551         weight = CW_Constant;
14552     }
14553     break;
14554   case 'N':
14555     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14556       if (C->getZExtValue() <= 0xff)
14557         weight = CW_Constant;
14558     }
14559     break;
14560   case 'G':
14561   case 'C':
14562     if (dyn_cast<ConstantFP>(CallOperandVal)) {
14563       weight = CW_Constant;
14564     }
14565     break;
14566   case 'e':
14567     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14568       if ((C->getSExtValue() >= -0x80000000LL) &&
14569           (C->getSExtValue() <= 0x7fffffffLL))
14570         weight = CW_Constant;
14571     }
14572     break;
14573   case 'Z':
14574     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
14575       if (C->getZExtValue() <= 0xffffffff)
14576         weight = CW_Constant;
14577     }
14578     break;
14579   }
14580   return weight;
14581 }
14582
14583 /// LowerXConstraint - try to replace an X constraint, which matches anything,
14584 /// with another that has more specific requirements based on the type of the
14585 /// corresponding operand.
14586 const char *X86TargetLowering::
14587 LowerXConstraint(EVT ConstraintVT) const {
14588   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
14589   // 'f' like normal targets.
14590   if (ConstraintVT.isFloatingPoint()) {
14591     if (Subtarget->hasXMMInt())
14592       return "Y";
14593     if (Subtarget->hasXMM())
14594       return "x";
14595   }
14596
14597   return TargetLowering::LowerXConstraint(ConstraintVT);
14598 }
14599
14600 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14601 /// vector.  If it is invalid, don't add anything to Ops.
14602 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14603                                                      std::string &Constraint,
14604                                                      std::vector<SDValue>&Ops,
14605                                                      SelectionDAG &DAG) const {
14606   SDValue Result(0, 0);
14607
14608   // Only support length 1 constraints for now.
14609   if (Constraint.length() > 1) return;
14610
14611   char ConstraintLetter = Constraint[0];
14612   switch (ConstraintLetter) {
14613   default: break;
14614   case 'I':
14615     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14616       if (C->getZExtValue() <= 31) {
14617         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14618         break;
14619       }
14620     }
14621     return;
14622   case 'J':
14623     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14624       if (C->getZExtValue() <= 63) {
14625         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14626         break;
14627       }
14628     }
14629     return;
14630   case 'K':
14631     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14632       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
14633         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14634         break;
14635       }
14636     }
14637     return;
14638   case 'N':
14639     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14640       if (C->getZExtValue() <= 255) {
14641         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14642         break;
14643       }
14644     }
14645     return;
14646   case 'e': {
14647     // 32-bit signed value
14648     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14649       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14650                                            C->getSExtValue())) {
14651         // Widen to 64 bits here to get it sign extended.
14652         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
14653         break;
14654       }
14655     // FIXME gcc accepts some relocatable values here too, but only in certain
14656     // memory models; it's complicated.
14657     }
14658     return;
14659   }
14660   case 'Z': {
14661     // 32-bit unsigned value
14662     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
14663       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
14664                                            C->getZExtValue())) {
14665         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
14666         break;
14667       }
14668     }
14669     // FIXME gcc accepts some relocatable values here too, but only in certain
14670     // memory models; it's complicated.
14671     return;
14672   }
14673   case 'i': {
14674     // Literal immediates are always ok.
14675     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
14676       // Widen to 64 bits here to get it sign extended.
14677       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
14678       break;
14679     }
14680
14681     // In any sort of PIC mode addresses need to be computed at runtime by
14682     // adding in a register or some sort of table lookup.  These can't
14683     // be used as immediates.
14684     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
14685       return;
14686
14687     // If we are in non-pic codegen mode, we allow the address of a global (with
14688     // an optional displacement) to be used with 'i'.
14689     GlobalAddressSDNode *GA = 0;
14690     int64_t Offset = 0;
14691
14692     // Match either (GA), (GA+C), (GA+C1+C2), etc.
14693     while (1) {
14694       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
14695         Offset += GA->getOffset();
14696         break;
14697       } else if (Op.getOpcode() == ISD::ADD) {
14698         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14699           Offset += C->getZExtValue();
14700           Op = Op.getOperand(0);
14701           continue;
14702         }
14703       } else if (Op.getOpcode() == ISD::SUB) {
14704         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
14705           Offset += -C->getZExtValue();
14706           Op = Op.getOperand(0);
14707           continue;
14708         }
14709       }
14710
14711       // Otherwise, this isn't something we can handle, reject it.
14712       return;
14713     }
14714
14715     const GlobalValue *GV = GA->getGlobal();
14716     // If we require an extra load to get this address, as in PIC mode, we
14717     // can't accept it.
14718     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
14719                                                         getTargetMachine())))
14720       return;
14721
14722     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
14723                                         GA->getValueType(0), Offset);
14724     break;
14725   }
14726   }
14727
14728   if (Result.getNode()) {
14729     Ops.push_back(Result);
14730     return;
14731   }
14732   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14733 }
14734
14735 std::pair<unsigned, const TargetRegisterClass*>
14736 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
14737                                                 EVT VT) const {
14738   // First, see if this is a constraint that directly corresponds to an LLVM
14739   // register class.
14740   if (Constraint.size() == 1) {
14741     // GCC Constraint Letters
14742     switch (Constraint[0]) {
14743     default: break;
14744       // TODO: Slight differences here in allocation order and leaving
14745       // RIP in the class. Do they matter any more here than they do
14746       // in the normal allocation?
14747     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
14748       if (Subtarget->is64Bit()) {
14749         if (VT == MVT::i32 || VT == MVT::f32)
14750           return std::make_pair(0U, X86::GR32RegisterClass);
14751         else if (VT == MVT::i16)
14752           return std::make_pair(0U, X86::GR16RegisterClass);
14753         else if (VT == MVT::i8 || VT == MVT::i1)
14754           return std::make_pair(0U, X86::GR8RegisterClass);
14755         else if (VT == MVT::i64 || VT == MVT::f64)
14756           return std::make_pair(0U, X86::GR64RegisterClass);
14757         break;
14758       }
14759       // 32-bit fallthrough
14760     case 'Q':   // Q_REGS
14761       if (VT == MVT::i32 || VT == MVT::f32)
14762         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
14763       else if (VT == MVT::i16)
14764         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
14765       else if (VT == MVT::i8 || VT == MVT::i1)
14766         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
14767       else if (VT == MVT::i64)
14768         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
14769       break;
14770     case 'r':   // GENERAL_REGS
14771     case 'l':   // INDEX_REGS
14772       if (VT == MVT::i8 || VT == MVT::i1)
14773         return std::make_pair(0U, X86::GR8RegisterClass);
14774       if (VT == MVT::i16)
14775         return std::make_pair(0U, X86::GR16RegisterClass);
14776       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
14777         return std::make_pair(0U, X86::GR32RegisterClass);
14778       return std::make_pair(0U, X86::GR64RegisterClass);
14779     case 'R':   // LEGACY_REGS
14780       if (VT == MVT::i8 || VT == MVT::i1)
14781         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
14782       if (VT == MVT::i16)
14783         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
14784       if (VT == MVT::i32 || !Subtarget->is64Bit())
14785         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
14786       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
14787     case 'f':  // FP Stack registers.
14788       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
14789       // value to the correct fpstack register class.
14790       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
14791         return std::make_pair(0U, X86::RFP32RegisterClass);
14792       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
14793         return std::make_pair(0U, X86::RFP64RegisterClass);
14794       return std::make_pair(0U, X86::RFP80RegisterClass);
14795     case 'y':   // MMX_REGS if MMX allowed.
14796       if (!Subtarget->hasMMX()) break;
14797       return std::make_pair(0U, X86::VR64RegisterClass);
14798     case 'Y':   // SSE_REGS if SSE2 allowed
14799       if (!Subtarget->hasXMMInt()) break;
14800       // FALL THROUGH.
14801     case 'x':   // SSE_REGS if SSE1 allowed
14802       if (!Subtarget->hasXMM()) break;
14803
14804       switch (VT.getSimpleVT().SimpleTy) {
14805       default: break;
14806       // Scalar SSE types.
14807       case MVT::f32:
14808       case MVT::i32:
14809         return std::make_pair(0U, X86::FR32RegisterClass);
14810       case MVT::f64:
14811       case MVT::i64:
14812         return std::make_pair(0U, X86::FR64RegisterClass);
14813       // Vector types.
14814       case MVT::v16i8:
14815       case MVT::v8i16:
14816       case MVT::v4i32:
14817       case MVT::v2i64:
14818       case MVT::v4f32:
14819       case MVT::v2f64:
14820         return std::make_pair(0U, X86::VR128RegisterClass);
14821       }
14822       break;
14823     }
14824   }
14825
14826   // Use the default implementation in TargetLowering to convert the register
14827   // constraint into a member of a register class.
14828   std::pair<unsigned, const TargetRegisterClass*> Res;
14829   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
14830
14831   // Not found as a standard register?
14832   if (Res.second == 0) {
14833     // Map st(0) -> st(7) -> ST0
14834     if (Constraint.size() == 7 && Constraint[0] == '{' &&
14835         tolower(Constraint[1]) == 's' &&
14836         tolower(Constraint[2]) == 't' &&
14837         Constraint[3] == '(' &&
14838         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
14839         Constraint[5] == ')' &&
14840         Constraint[6] == '}') {
14841
14842       Res.first = X86::ST0+Constraint[4]-'0';
14843       Res.second = X86::RFP80RegisterClass;
14844       return Res;
14845     }
14846
14847     // GCC allows "st(0)" to be called just plain "st".
14848     if (StringRef("{st}").equals_lower(Constraint)) {
14849       Res.first = X86::ST0;
14850       Res.second = X86::RFP80RegisterClass;
14851       return Res;
14852     }
14853
14854     // flags -> EFLAGS
14855     if (StringRef("{flags}").equals_lower(Constraint)) {
14856       Res.first = X86::EFLAGS;
14857       Res.second = X86::CCRRegisterClass;
14858       return Res;
14859     }
14860
14861     // 'A' means EAX + EDX.
14862     if (Constraint == "A") {
14863       Res.first = X86::EAX;
14864       Res.second = X86::GR32_ADRegisterClass;
14865       return Res;
14866     }
14867     return Res;
14868   }
14869
14870   // Otherwise, check to see if this is a register class of the wrong value
14871   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
14872   // turn into {ax},{dx}.
14873   if (Res.second->hasType(VT))
14874     return Res;   // Correct type already, nothing to do.
14875
14876   // All of the single-register GCC register classes map their values onto
14877   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
14878   // really want an 8-bit or 32-bit register, map to the appropriate register
14879   // class and return the appropriate register.
14880   if (Res.second == X86::GR16RegisterClass) {
14881     if (VT == MVT::i8) {
14882       unsigned DestReg = 0;
14883       switch (Res.first) {
14884       default: break;
14885       case X86::AX: DestReg = X86::AL; break;
14886       case X86::DX: DestReg = X86::DL; break;
14887       case X86::CX: DestReg = X86::CL; break;
14888       case X86::BX: DestReg = X86::BL; break;
14889       }
14890       if (DestReg) {
14891         Res.first = DestReg;
14892         Res.second = X86::GR8RegisterClass;
14893       }
14894     } else if (VT == MVT::i32) {
14895       unsigned DestReg = 0;
14896       switch (Res.first) {
14897       default: break;
14898       case X86::AX: DestReg = X86::EAX; break;
14899       case X86::DX: DestReg = X86::EDX; break;
14900       case X86::CX: DestReg = X86::ECX; break;
14901       case X86::BX: DestReg = X86::EBX; break;
14902       case X86::SI: DestReg = X86::ESI; break;
14903       case X86::DI: DestReg = X86::EDI; break;
14904       case X86::BP: DestReg = X86::EBP; break;
14905       case X86::SP: DestReg = X86::ESP; break;
14906       }
14907       if (DestReg) {
14908         Res.first = DestReg;
14909         Res.second = X86::GR32RegisterClass;
14910       }
14911     } else if (VT == MVT::i64) {
14912       unsigned DestReg = 0;
14913       switch (Res.first) {
14914       default: break;
14915       case X86::AX: DestReg = X86::RAX; break;
14916       case X86::DX: DestReg = X86::RDX; break;
14917       case X86::CX: DestReg = X86::RCX; break;
14918       case X86::BX: DestReg = X86::RBX; break;
14919       case X86::SI: DestReg = X86::RSI; break;
14920       case X86::DI: DestReg = X86::RDI; break;
14921       case X86::BP: DestReg = X86::RBP; break;
14922       case X86::SP: DestReg = X86::RSP; break;
14923       }
14924       if (DestReg) {
14925         Res.first = DestReg;
14926         Res.second = X86::GR64RegisterClass;
14927       }
14928     }
14929   } else if (Res.second == X86::FR32RegisterClass ||
14930              Res.second == X86::FR64RegisterClass ||
14931              Res.second == X86::VR128RegisterClass) {
14932     // Handle references to XMM physical registers that got mapped into the
14933     // wrong class.  This can happen with constraints like {xmm0} where the
14934     // target independent register mapper will just pick the first match it can
14935     // find, ignoring the required type.
14936     if (VT == MVT::f32)
14937       Res.second = X86::FR32RegisterClass;
14938     else if (VT == MVT::f64)
14939       Res.second = X86::FR64RegisterClass;
14940     else if (X86::VR128RegisterClass->hasType(VT))
14941       Res.second = X86::VR128RegisterClass;
14942   }
14943
14944   return Res;
14945 }