Use movups to lower memcpy and memset even if it's not fast (like corei7).
[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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.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/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
60                        SDValue V2);
61
62 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
63
64   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
65
66   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
67     if (is64Bit)
68       return new X8664_MachoTargetObjectFile();
69     return new TargetLoweringObjectFileMachO();
70   }
71   
72   if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73     if (is64Bit)
74       return new X8664_ELFTargetObjectFile(TM);
75     return new X8632_ELFTargetObjectFile(TM);
76   }
77   if (TM.getSubtarget<X86Subtarget>().isTargetCOFF())
78     return new TargetLoweringObjectFileCOFF();
79   llvm_unreachable("unknown subtarget type");
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasXMMInt();
86   X86ScalarSSEf32 = Subtarget->hasXMM();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
94
95   // X86 is weird, it always uses i8 for shift amounts and setcc results.
96   setShiftAmountType(MVT::i8);
97   setBooleanContents(ZeroOrOneBooleanContent);
98   setSchedulingPreference(Sched::RegPressure);
99   setStackPointerRegisterToSaveRestore(X86StackPtr);
100
101   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
102     // Setup Windows compiler runtime calls.
103     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
104     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
105     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
106     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
107     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
108     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
109     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
110     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
111   }
112
113   if (Subtarget->isTargetDarwin()) {
114     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
115     setUseUnderscoreSetJmp(false);
116     setUseUnderscoreLongJmp(false);
117   } else if (Subtarget->isTargetMingw()) {
118     // MS runtime is weird: it exports _setjmp, but longjmp!
119     setUseUnderscoreSetJmp(true);
120     setUseUnderscoreLongJmp(false);
121   } else {
122     setUseUnderscoreSetJmp(true);
123     setUseUnderscoreLongJmp(true);
124   }
125
126   // Set up the register classes.
127   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
128   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
129   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
130   if (Subtarget->is64Bit())
131     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
132
133   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134
135   // We don't accept any truncstore of integer registers.
136   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
137   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
138   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
139   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
140   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
141   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
142
143   // SETOEQ and SETUNE require checking two conditions.
144   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
145   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
146   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
147   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
148   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
149   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
150
151   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
152   // operation.
153   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
154   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
155   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
156
157   if (Subtarget->is64Bit()) {
158     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
159     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
160   } else if (!UseSoftFloat) {
161     // We have an algorithm for SSE2->double, and we turn this into a
162     // 64-bit FILD followed by conditional FADD for other targets.
163     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
164     // We have an algorithm for SSE2, and we turn this into a 64-bit
165     // FILD for other targets.
166     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
167   }
168
169   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
170   // this operation.
171   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
172   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
173
174   if (!UseSoftFloat) {
175     // SSE has no i16 to fp conversion, only i32
176     if (X86ScalarSSEf32) {
177       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
178       // f32 and f64 cases are Legal, f80 case is not
179       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
180     } else {
181       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
182       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
183     }
184   } else {
185     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
186     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
187   }
188
189   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
190   // are Legal, f80 is custom lowered.
191   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
192   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
193
194   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
195   // this operation.
196   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
197   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
198
199   if (X86ScalarSSEf32) {
200     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
201     // f32 and f64 cases are Legal, f80 case is not
202     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
203   } else {
204     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
205     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
206   }
207
208   // Handle FP_TO_UINT by promoting the destination to a larger signed
209   // conversion.
210   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
211   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
212   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
213
214   if (Subtarget->is64Bit()) {
215     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
216     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
217   } else if (!UseSoftFloat) {
218     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
219       // Expand FP_TO_UINT into a select.
220       // FIXME: We would like to use a Custom expander here eventually to do
221       // the optimal thing for SSE vs. the default expansion in the legalizer.
222       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
223     else
224       // With SSE3 we can use fisttpll to convert to a signed i64; without
225       // SSE, we're stuck with a fistpll.
226       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
227   }
228
229   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
230   if (!X86ScalarSSEf64) {
231     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
232     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
233     if (Subtarget->is64Bit()) {
234       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
235       // Without SSE, i64->f64 goes through memory.
236       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
237     }
238   }
239
240   // Scalar integer divide and remainder are lowered to use operations that
241   // produce two results, to match the available instructions. This exposes
242   // the two-result form to trivial CSE, which is able to combine x/y and x%y
243   // into a single instruction.
244   //
245   // Scalar integer multiply-high is also lowered to use two-result
246   // operations, to match the available instructions. However, plain multiply
247   // (low) operations are left as Legal, as there are single-result
248   // instructions for this in x86. Using the two-result multiply instructions
249   // when both high and low results are needed must be arranged by dagcombine.
250   for (unsigned i = 0, e = 4; i != e; ++i) {
251     MVT VT = IntVTs[i];
252     setOperationAction(ISD::MULHS, VT, Expand);
253     setOperationAction(ISD::MULHU, VT, Expand);
254     setOperationAction(ISD::SDIV, VT, Expand);
255     setOperationAction(ISD::UDIV, VT, Expand);
256     setOperationAction(ISD::SREM, VT, Expand);
257     setOperationAction(ISD::UREM, VT, Expand);
258     
259     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
260     setOperationAction(ISD::ADDC, VT, Custom);
261     setOperationAction(ISD::ADDE, VT, Custom);
262     setOperationAction(ISD::SUBC, VT, Custom);
263     setOperationAction(ISD::SUBE, VT, Custom);
264   }
265
266   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
267   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
269   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
270   if (Subtarget->is64Bit())
271     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
272   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
273   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
274   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
275   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
276   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
277   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
278   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
279   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
280
281   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
282   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
283   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
284   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
285   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
286   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
287   if (Subtarget->is64Bit()) {
288     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
289     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
290   }
291
292   if (Subtarget->hasPOPCNT()) {
293     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
294   } else {
295     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
296     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
297     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
298     if (Subtarget->is64Bit())
299       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
300   }
301
302   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
303   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
304
305   // These should be promoted to a larger select which is supported.
306   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
307   // X86 wants to expand cmov itself.
308   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
309   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
310   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
311   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
312   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
313   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
314   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
315   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
316   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
317   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
318   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
320   if (Subtarget->is64Bit()) {
321     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
322     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
323   }
324   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
325
326   // Darwin ABI issue.
327   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
328   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
329   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
330   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
331   if (Subtarget->is64Bit())
332     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
333   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
334   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
335   if (Subtarget->is64Bit()) {
336     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
337     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
338     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
339     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
340     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
341   }
342   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
343   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
344   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
345   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
346   if (Subtarget->is64Bit()) {
347     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
348     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
349     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
350   }
351
352   if (Subtarget->hasXMM())
353     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
354
355   // We may not have a libcall for MEMBARRIER so we should lower this.
356   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
357
358   // On X86 and X86-64, atomic operations are lowered to locked instructions.
359   // Locked instructions, in turn, have implicit fence semantics (all memory
360   // operations are flushed before issuing the locked instruction, and they
361   // are not buffered), so we can fold away the common pattern of
362   // fence-atomic-fence.
363   setShouldFoldAtomicFences(true);
364
365   // Expand certain atomics
366   for (unsigned i = 0, e = 4; i != e; ++i) {
367     MVT VT = IntVTs[i];
368     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
369     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
370   }
371     
372   if (!Subtarget->is64Bit()) {
373     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
376     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
377     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
378     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
380   }
381
382   // FIXME - use subtarget debug flags
383   if (!Subtarget->isTargetDarwin() &&
384       !Subtarget->isTargetELF() &&
385       !Subtarget->isTargetCygMing()) {
386     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
387   }
388
389   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
390   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
391   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
392   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
393   if (Subtarget->is64Bit()) {
394     setExceptionPointerRegister(X86::RAX);
395     setExceptionSelectorRegister(X86::RDX);
396   } else {
397     setExceptionPointerRegister(X86::EAX);
398     setExceptionSelectorRegister(X86::EDX);
399   }
400   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
401   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
402
403   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
404
405   setOperationAction(ISD::TRAP, MVT::Other, Legal);
406
407   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
408   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
409   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
410   if (Subtarget->is64Bit()) {
411     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
412     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
413   } else {
414     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
415     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
416   }
417
418   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
419   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
420   if (Subtarget->is64Bit())
421     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
422   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
423     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
424   else
425     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
426
427   if (!UseSoftFloat && X86ScalarSSEf64) {
428     // f32 and f64 use SSE.
429     // Set up the FP register classes.
430     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
431     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
432
433     // Use ANDPD to simulate FABS.
434     setOperationAction(ISD::FABS , MVT::f64, Custom);
435     setOperationAction(ISD::FABS , MVT::f32, Custom);
436
437     // Use XORP to simulate FNEG.
438     setOperationAction(ISD::FNEG , MVT::f64, Custom);
439     setOperationAction(ISD::FNEG , MVT::f32, Custom);
440
441     // Use ANDPD and ORPD to simulate FCOPYSIGN.
442     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
443     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
444
445     // We don't support sin/cos/fmod
446     setOperationAction(ISD::FSIN , MVT::f64, Expand);
447     setOperationAction(ISD::FCOS , MVT::f64, Expand);
448     setOperationAction(ISD::FSIN , MVT::f32, Expand);
449     setOperationAction(ISD::FCOS , MVT::f32, Expand);
450
451     // Expand FP immediates into loads from the stack, except for the special
452     // cases we handle.
453     addLegalFPImmediate(APFloat(+0.0)); // xorpd
454     addLegalFPImmediate(APFloat(+0.0f)); // xorps
455   } else if (!UseSoftFloat && X86ScalarSSEf32) {
456     // Use SSE for f32, x87 for f64.
457     // Set up the FP register classes.
458     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
459     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
460
461     // Use ANDPS to simulate FABS.
462     setOperationAction(ISD::FABS , MVT::f32, Custom);
463
464     // Use XORP to simulate FNEG.
465     setOperationAction(ISD::FNEG , MVT::f32, Custom);
466
467     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
468
469     // Use ANDPS and ORPS to simulate FCOPYSIGN.
470     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
471     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
472
473     // We don't support sin/cos/fmod
474     setOperationAction(ISD::FSIN , MVT::f32, Expand);
475     setOperationAction(ISD::FCOS , MVT::f32, Expand);
476
477     // Special cases we handle for FP constants.
478     addLegalFPImmediate(APFloat(+0.0f)); // xorps
479     addLegalFPImmediate(APFloat(+0.0)); // FLD0
480     addLegalFPImmediate(APFloat(+1.0)); // FLD1
481     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
482     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
483
484     if (!UnsafeFPMath) {
485       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
486       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
487     }
488   } else if (!UseSoftFloat) {
489     // f32 and f64 in x87.
490     // Set up the FP register classes.
491     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
492     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
493
494     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
495     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
496     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
497     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
498
499     if (!UnsafeFPMath) {
500       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
501       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
502     }
503     addLegalFPImmediate(APFloat(+0.0)); // FLD0
504     addLegalFPImmediate(APFloat(+1.0)); // FLD1
505     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
506     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
507     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
508     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
509     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
510     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
511   }
512
513   // Long double always uses X87.
514   if (!UseSoftFloat) {
515     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
516     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
517     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
518     {
519       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
520       addLegalFPImmediate(TmpFlt);  // FLD0
521       TmpFlt.changeSign();
522       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
523
524       bool ignored;
525       APFloat TmpFlt2(+1.0);
526       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527                       &ignored);
528       addLegalFPImmediate(TmpFlt2);  // FLD1
529       TmpFlt2.changeSign();
530       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
531     }
532
533     if (!UnsafeFPMath) {
534       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
535       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
536     }
537   }
538
539   // Always use a library call for pow.
540   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
541   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
542   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
543
544   setOperationAction(ISD::FLOG, MVT::f80, Expand);
545   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
546   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
547   setOperationAction(ISD::FEXP, MVT::f80, Expand);
548   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
549
550   // First set operation action for all vector types to either promote
551   // (for widening) or expand (for scalarization). Then we will selectively
552   // turn on ones that can be effectively codegen'd.
553   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
554        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
555     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
570     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
571     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
604     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
608     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
609          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
610       setTruncStoreAction((MVT::SimpleValueType)VT,
611                           (MVT::SimpleValueType)InnerVT, Expand);
612     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
614     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
615   }
616
617   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
618   // with -msoft-float, disable use of MMX as well.
619   if (!UseSoftFloat && Subtarget->hasMMX()) {
620     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
621     // No operations on x86mmx supported, everything uses intrinsics.
622   }
623
624   // MMX-sized vectors (other than x86mmx) are expected to be expanded
625   // into smaller operations.
626   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
627   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
628   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
629   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
630   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
631   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
632   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
633   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
634   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
635   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
636   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
637   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
638   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
639   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
640   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
641   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
642   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
643   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
644   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
645   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
646   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
647   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
648   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
649   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
650   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
651   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
652   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
653   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
654   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
655
656   if (!UseSoftFloat && Subtarget->hasXMM()) {
657     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
658
659     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
660     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
661     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
662     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
663     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
664     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
665     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
666     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
667     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
668     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
669     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
670     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
671   }
672
673   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
674     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
675
676     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
677     // registers cannot be used even for integer operations.
678     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
679     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
680     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
681     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
682
683     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
684     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
685     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
686     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
687     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
688     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
689     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
690     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
691     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
692     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
693     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
694     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
695     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
696     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
697     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
698     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
699
700     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
701     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
702     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
703     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
704
705     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
706     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
707     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
708     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
709     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
710
711     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
712     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
713     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
714     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
715     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
716
717     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
718     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
719       EVT VT = (MVT::SimpleValueType)i;
720       // Do not attempt to custom lower non-power-of-2 vectors
721       if (!isPowerOf2_32(VT.getVectorNumElements()))
722         continue;
723       // Do not attempt to custom lower non-128-bit vectors
724       if (!VT.is128BitVector())
725         continue;
726       setOperationAction(ISD::BUILD_VECTOR,
727                          VT.getSimpleVT().SimpleTy, Custom);
728       setOperationAction(ISD::VECTOR_SHUFFLE,
729                          VT.getSimpleVT().SimpleTy, Custom);
730       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
731                          VT.getSimpleVT().SimpleTy, Custom);
732     }
733
734     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
735     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
736     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
737     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
738     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
739     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
740
741     if (Subtarget->is64Bit()) {
742       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
743       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
744     }
745
746     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
747     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
748       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
749       EVT VT = SVT;
750
751       // Do not attempt to promote non-128-bit vectors
752       if (!VT.is128BitVector())
753         continue;
754
755       setOperationAction(ISD::AND,    SVT, Promote);
756       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
757       setOperationAction(ISD::OR,     SVT, Promote);
758       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
759       setOperationAction(ISD::XOR,    SVT, Promote);
760       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
761       setOperationAction(ISD::LOAD,   SVT, Promote);
762       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
763       setOperationAction(ISD::SELECT, SVT, Promote);
764       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
765     }
766
767     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
768
769     // Custom lower v2i64 and v2f64 selects.
770     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
771     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
772     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
773     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
774
775     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
776     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
777   }
778
779   if (Subtarget->hasSSE41()) {
780     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
781     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
782     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
783     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
784     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
785     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
786     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
787     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
788     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
789     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
790
791     // FIXME: Do we need to handle scalar-to-vector here?
792     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
793
794     // Can turn SHL into an integer multiply.
795     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
796     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
797
798     // i8 and i16 vectors are custom , because the source register and source
799     // source memory operand types are not the same width.  f32 vectors are
800     // custom since the immediate controlling the insert encodes additional
801     // information.
802     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
803     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
804     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
805     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
806
807     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
809     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
810     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
811
812     if (Subtarget->is64Bit()) {
813       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
814       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
815     }
816   }
817
818   if (Subtarget->hasSSE42())
819     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
820
821   if (!UseSoftFloat && Subtarget->hasAVX()) {
822     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
823     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
824     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
825     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
826     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
827
828     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
829     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
830     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
831     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
832     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
833     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
834     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
835     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
836     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
837     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
838     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
839     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
840     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
841     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
842     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
843
844     // Operations to consider commented out -v16i16 v32i8
845     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
846     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
847     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
848     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
849     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
850     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
851     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
852     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
853     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
854     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
855     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
856     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
857     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
858     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
859
860     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
861     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
862     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
863     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
864
865     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
866     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
867     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
868     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
869     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
870
871     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
872     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
873     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
874     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
876     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
877
878 #if 0
879     // Not sure we want to do this since there are no 256-bit integer
880     // operations in AVX
881
882     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
883     // This includes 256-bit vectors
884     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
885       EVT VT = (MVT::SimpleValueType)i;
886
887       // Do not attempt to custom lower non-power-of-2 vectors
888       if (!isPowerOf2_32(VT.getVectorNumElements()))
889         continue;
890
891       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
892       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
893       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
894     }
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
899     }
900 #endif
901
902 #if 0
903     // Not sure we want to do this since there are no 256-bit integer
904     // operations in AVX
905
906     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
907     // Including 256-bit vectors
908     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
909       EVT VT = (MVT::SimpleValueType)i;
910
911       if (!VT.is256BitVector()) {
912         continue;
913       }
914       setOperationAction(ISD::AND,    VT, Promote);
915       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
916       setOperationAction(ISD::OR,     VT, Promote);
917       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
918       setOperationAction(ISD::XOR,    VT, Promote);
919       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
920       setOperationAction(ISD::LOAD,   VT, Promote);
921       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
922       setOperationAction(ISD::SELECT, VT, Promote);
923       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
924     }
925
926     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
927 #endif
928   }
929
930   // We want to custom lower some of our intrinsics.
931   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
932
933     
934   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
935   // handle type legalization for these operations here.
936   //
937   // FIXME: We really should do custom legalization for addition and
938   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
939   // than generic legalization for 64-bit multiplication-with-overflow, though.
940   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
941     // Add/Sub/Mul with overflow operations are custom lowered.
942     MVT VT = IntVTs[i];
943     setOperationAction(ISD::SADDO, VT, Custom);
944     setOperationAction(ISD::UADDO, VT, Custom);
945     setOperationAction(ISD::SSUBO, VT, Custom);
946     setOperationAction(ISD::USUBO, VT, Custom);
947     setOperationAction(ISD::SMULO, VT, Custom);
948     setOperationAction(ISD::UMULO, VT, Custom);
949   }
950     
951   // There are no 8-bit 3-address imul/mul instructions
952   setOperationAction(ISD::SMULO, MVT::i8, Expand);
953   setOperationAction(ISD::UMULO, MVT::i8, Expand);
954
955   if (!Subtarget->is64Bit()) {
956     // These libcalls are not available in 32-bit.
957     setLibcallName(RTLIB::SHL_I128, 0);
958     setLibcallName(RTLIB::SRL_I128, 0);
959     setLibcallName(RTLIB::SRA_I128, 0);
960   }
961
962   // We have target-specific dag combine patterns for the following nodes:
963   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
964   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
965   setTargetDAGCombine(ISD::BUILD_VECTOR);
966   setTargetDAGCombine(ISD::SELECT);
967   setTargetDAGCombine(ISD::SHL);
968   setTargetDAGCombine(ISD::SRA);
969   setTargetDAGCombine(ISD::SRL);
970   setTargetDAGCombine(ISD::OR);
971   setTargetDAGCombine(ISD::AND);
972   setTargetDAGCombine(ISD::ADD);
973   setTargetDAGCombine(ISD::SUB);
974   setTargetDAGCombine(ISD::STORE);
975   setTargetDAGCombine(ISD::ZERO_EXTEND);
976   if (Subtarget->is64Bit())
977     setTargetDAGCombine(ISD::MUL);
978
979   computeRegisterProperties();
980
981   // On Darwin, -Os means optimize for size without hurting performance,
982   // do not reduce the limit.
983   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
984   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
985   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
986   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
987   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
988   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
989   setPrefLoopAlignment(16);
990   benefitFromCodePlacementOpt = true;
991 }
992
993
994 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
995   return MVT::i8;
996 }
997
998
999 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1000 /// the desired ByVal argument alignment.
1001 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1002   if (MaxAlign == 16)
1003     return;
1004   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1005     if (VTy->getBitWidth() == 128)
1006       MaxAlign = 16;
1007   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1008     unsigned EltAlign = 0;
1009     getMaxByValAlign(ATy->getElementType(), EltAlign);
1010     if (EltAlign > MaxAlign)
1011       MaxAlign = EltAlign;
1012   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1013     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1014       unsigned EltAlign = 0;
1015       getMaxByValAlign(STy->getElementType(i), EltAlign);
1016       if (EltAlign > MaxAlign)
1017         MaxAlign = EltAlign;
1018       if (MaxAlign == 16)
1019         break;
1020     }
1021   }
1022   return;
1023 }
1024
1025 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1026 /// function arguments in the caller parameter area. For X86, aggregates
1027 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1028 /// are at 4-byte boundaries.
1029 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1030   if (Subtarget->is64Bit()) {
1031     // Max of 8 and alignment of type.
1032     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1033     if (TyAlign > 8)
1034       return TyAlign;
1035     return 8;
1036   }
1037
1038   unsigned Align = 4;
1039   if (Subtarget->hasXMM())
1040     getMaxByValAlign(Ty, Align);
1041   return Align;
1042 }
1043
1044 /// getOptimalMemOpType - Returns the target specific optimal type for load
1045 /// and store operations as a result of memset, memcpy, and memmove
1046 /// lowering. If DstAlign is zero that means it's safe to destination
1047 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1048 /// means there isn't a need to check it against alignment requirement,
1049 /// probably because the source does not need to be loaded. If
1050 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1051 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1052 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1053 /// constant so it does not need to be loaded.
1054 /// It returns EVT::Other if the type should be determined using generic
1055 /// target-independent logic.
1056 EVT
1057 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1058                                        unsigned DstAlign, unsigned SrcAlign,
1059                                        bool NonScalarIntSafe,
1060                                        bool MemcpyStrSrc,
1061                                        MachineFunction &MF) const {
1062   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1063   // linux.  This is because the stack realignment code can't handle certain
1064   // cases like PR2962.  This should be removed when PR2962 is fixed.
1065   const Function *F = MF.getFunction();
1066   if (NonScalarIntSafe && !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1067     if (Size >= 16 &&
1068         Subtarget->getStackAlignment() >= 16) {
1069       if (Subtarget->hasSSE2())
1070         return MVT::v4i32;
1071       if (Subtarget->hasSSE1())
1072         return MVT::v4f32;
1073     } else if (!MemcpyStrSrc && Size >= 8 &&
1074                !Subtarget->is64Bit() &&
1075                Subtarget->getStackAlignment() >= 8 &&
1076                Subtarget->hasXMMInt()) {
1077       // Do not use f64 to lower memcpy if source is string constant. It's
1078       // better to use i32 to avoid the loads.
1079       return MVT::f64;
1080     }
1081   }
1082   if (Subtarget->is64Bit() && Size >= 8)
1083     return MVT::i64;
1084   return MVT::i32;
1085 }
1086
1087 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1088 /// current function.  The returned value is a member of the
1089 /// MachineJumpTableInfo::JTEntryKind enum.
1090 unsigned X86TargetLowering::getJumpTableEncoding() const {
1091   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1092   // symbol.
1093   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1094       Subtarget->isPICStyleGOT())
1095     return MachineJumpTableInfo::EK_Custom32;
1096
1097   // Otherwise, use the normal jump table encoding heuristics.
1098   return TargetLowering::getJumpTableEncoding();
1099 }
1100
1101 const MCExpr *
1102 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1103                                              const MachineBasicBlock *MBB,
1104                                              unsigned uid,MCContext &Ctx) const{
1105   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1106          Subtarget->isPICStyleGOT());
1107   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1108   // entries.
1109   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1110                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1111 }
1112
1113 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1114 /// jumptable.
1115 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1116                                                     SelectionDAG &DAG) const {
1117   if (!Subtarget->is64Bit())
1118     // This doesn't have DebugLoc associated with it, but is not really the
1119     // same as a Register.
1120     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1121   return Table;
1122 }
1123
1124 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1125 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1126 /// MCExpr.
1127 const MCExpr *X86TargetLowering::
1128 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1129                              MCContext &Ctx) const {
1130   // X86-64 uses RIP relative addressing based on the jump table label.
1131   if (Subtarget->isPICStyleRIPRel())
1132     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1133
1134   // Otherwise, the reference is relative to the PIC base.
1135   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1136 }
1137
1138 /// getFunctionAlignment - Return the Log2 alignment of this function.
1139 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1140   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1141 }
1142
1143 std::pair<const TargetRegisterClass*, uint8_t>
1144 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1145   const TargetRegisterClass *RRC = 0;
1146   uint8_t Cost = 1;
1147   switch (VT.getSimpleVT().SimpleTy) {
1148   default:
1149     return TargetLowering::findRepresentativeClass(VT);
1150   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1151     RRC = (Subtarget->is64Bit()
1152            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1153     break;
1154   case MVT::x86mmx:
1155     RRC = X86::VR64RegisterClass;
1156     break;
1157   case MVT::f32: case MVT::f64:
1158   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1159   case MVT::v4f32: case MVT::v2f64:
1160   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1161   case MVT::v4f64:
1162     RRC = X86::VR128RegisterClass;
1163     break;
1164   }
1165   return std::make_pair(RRC, Cost);
1166 }
1167
1168 unsigned
1169 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1170                                        MachineFunction &MF) const {
1171   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1172
1173   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1174   switch (RC->getID()) {
1175   default:
1176     return 0;
1177   case X86::GR32RegClassID:
1178     return 4 - FPDiff;
1179   case X86::GR64RegClassID:
1180     return 8 - FPDiff;
1181   case X86::VR128RegClassID:
1182     return Subtarget->is64Bit() ? 10 : 4;
1183   case X86::VR64RegClassID:
1184     return 4;
1185   }
1186 }
1187
1188 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1189                                                unsigned &Offset) const {
1190   if (!Subtarget->isTargetLinux())
1191     return false;
1192
1193   if (Subtarget->is64Bit()) {
1194     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1195     Offset = 0x28;
1196     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1197       AddressSpace = 256;
1198     else
1199       AddressSpace = 257;
1200   } else {
1201     // %gs:0x14 on i386
1202     Offset = 0x14;
1203     AddressSpace = 256;
1204   }
1205   return true;
1206 }
1207
1208
1209 //===----------------------------------------------------------------------===//
1210 //               Return Value Calling Convention Implementation
1211 //===----------------------------------------------------------------------===//
1212
1213 #include "X86GenCallingConv.inc"
1214
1215 bool
1216 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1217                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1218                         LLVMContext &Context) const {
1219   SmallVector<CCValAssign, 16> RVLocs;
1220   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1221                  RVLocs, Context);
1222   return CCInfo.CheckReturn(Outs, RetCC_X86);
1223 }
1224
1225 SDValue
1226 X86TargetLowering::LowerReturn(SDValue Chain,
1227                                CallingConv::ID CallConv, bool isVarArg,
1228                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1229                                const SmallVectorImpl<SDValue> &OutVals,
1230                                DebugLoc dl, SelectionDAG &DAG) const {
1231   MachineFunction &MF = DAG.getMachineFunction();
1232   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1233
1234   SmallVector<CCValAssign, 16> RVLocs;
1235   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1236                  RVLocs, *DAG.getContext());
1237   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1238
1239   // Add the regs to the liveout set for the function.
1240   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1241   for (unsigned i = 0; i != RVLocs.size(); ++i)
1242     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1243       MRI.addLiveOut(RVLocs[i].getLocReg());
1244
1245   SDValue Flag;
1246
1247   SmallVector<SDValue, 6> RetOps;
1248   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1249   // Operand #1 = Bytes To Pop
1250   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1251                    MVT::i16));
1252
1253   // Copy the result values into the output registers.
1254   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1255     CCValAssign &VA = RVLocs[i];
1256     assert(VA.isRegLoc() && "Can only return in registers!");
1257     SDValue ValToCopy = OutVals[i];
1258     EVT ValVT = ValToCopy.getValueType();
1259
1260     // If this is x86-64, and we disabled SSE, we can't return FP values,
1261     // or SSE or MMX vectors.
1262     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1263          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1264           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1265       report_fatal_error("SSE register return with SSE disabled");
1266     }
1267     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1268     // llvm-gcc has never done it right and no one has noticed, so this
1269     // should be OK for now.
1270     if (ValVT == MVT::f64 &&
1271         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1272       report_fatal_error("SSE2 register return with SSE2 disabled");
1273
1274     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1275     // the RET instruction and handled by the FP Stackifier.
1276     if (VA.getLocReg() == X86::ST0 ||
1277         VA.getLocReg() == X86::ST1) {
1278       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1279       // change the value to the FP stack register class.
1280       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1281         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1282       RetOps.push_back(ValToCopy);
1283       // Don't emit a copytoreg.
1284       continue;
1285     }
1286
1287     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1288     // which is returned in RAX / RDX.
1289     if (Subtarget->is64Bit()) {
1290       if (ValVT == MVT::x86mmx) {
1291         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1292           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1293           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1294                                   ValToCopy);
1295           // If we don't have SSE2 available, convert to v4f32 so the generated
1296           // register is legal.
1297           if (!Subtarget->hasSSE2())
1298             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1299         }
1300       }
1301     }
1302
1303     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1304     Flag = Chain.getValue(1);
1305   }
1306
1307   // The x86-64 ABI for returning structs by value requires that we copy
1308   // the sret argument into %rax for the return. We saved the argument into
1309   // a virtual register in the entry block, so now we copy the value out
1310   // and into %rax.
1311   if (Subtarget->is64Bit() &&
1312       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1313     MachineFunction &MF = DAG.getMachineFunction();
1314     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1315     unsigned Reg = FuncInfo->getSRetReturnReg();
1316     assert(Reg &&
1317            "SRetReturnReg should have been set in LowerFormalArguments().");
1318     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1319
1320     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1321     Flag = Chain.getValue(1);
1322
1323     // RAX now acts like a return value.
1324     MRI.addLiveOut(X86::RAX);
1325   }
1326
1327   RetOps[0] = Chain;  // Update chain.
1328
1329   // Add the flag if we have it.
1330   if (Flag.getNode())
1331     RetOps.push_back(Flag);
1332
1333   return DAG.getNode(X86ISD::RET_FLAG, dl,
1334                      MVT::Other, &RetOps[0], RetOps.size());
1335 }
1336
1337 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1338   if (N->getNumValues() != 1)
1339     return false;
1340   if (!N->hasNUsesOfValue(1, 0))
1341     return false;
1342
1343   SDNode *Copy = *N->use_begin();
1344   if (Copy->getOpcode() != ISD::CopyToReg &&
1345       Copy->getOpcode() != ISD::FP_EXTEND)
1346     return false;
1347
1348   bool HasRet = false;
1349   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1350        UI != UE; ++UI) {
1351     if (UI->getOpcode() != X86ISD::RET_FLAG)
1352       return false;
1353     HasRet = true;
1354   }
1355
1356   return HasRet;
1357 }
1358
1359 /// LowerCallResult - Lower the result values of a call into the
1360 /// appropriate copies out of appropriate physical registers.
1361 ///
1362 SDValue
1363 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1364                                    CallingConv::ID CallConv, bool isVarArg,
1365                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1366                                    DebugLoc dl, SelectionDAG &DAG,
1367                                    SmallVectorImpl<SDValue> &InVals) const {
1368
1369   // Assign locations to each value returned by this call.
1370   SmallVector<CCValAssign, 16> RVLocs;
1371   bool Is64Bit = Subtarget->is64Bit();
1372   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1373                  RVLocs, *DAG.getContext());
1374   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1375
1376   // Copy all of the result registers out of their specified physreg.
1377   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1378     CCValAssign &VA = RVLocs[i];
1379     EVT CopyVT = VA.getValVT();
1380
1381     // If this is x86-64, and we disabled SSE, we can't return FP values
1382     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1383         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1384       report_fatal_error("SSE register return with SSE disabled");
1385     }
1386
1387     SDValue Val;
1388
1389     // If this is a call to a function that returns an fp value on the floating
1390     // point stack, we must guarantee the the value is popped from the stack, so
1391     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1392     // if the return value is not used. We use the FpGET_ST0 instructions
1393     // instead.
1394     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1395       // If we prefer to use the value in xmm registers, copy it out as f80 and
1396       // use a truncate to move it from fp stack reg to xmm reg.
1397       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1398       bool isST0 = VA.getLocReg() == X86::ST0;
1399       unsigned Opc = 0;
1400       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1401       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1402       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1403       SDValue Ops[] = { Chain, InFlag };
1404       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1405                                          Ops, 2), 1);
1406       Val = Chain.getValue(0);
1407
1408       // Round the f80 to the right size, which also moves it to the appropriate
1409       // xmm register.
1410       if (CopyVT != VA.getValVT())
1411         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1412                           // This truncation won't change the value.
1413                           DAG.getIntPtrConstant(1));
1414     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1415       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1416       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1417         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1418                                    MVT::v2i64, InFlag).getValue(1);
1419         Val = Chain.getValue(0);
1420         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1421                           Val, DAG.getConstant(0, MVT::i64));
1422       } else {
1423         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1424                                    MVT::i64, InFlag).getValue(1);
1425         Val = Chain.getValue(0);
1426       }
1427       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1428     } else {
1429       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1430                                  CopyVT, InFlag).getValue(1);
1431       Val = Chain.getValue(0);
1432     }
1433     InFlag = Chain.getValue(2);
1434     InVals.push_back(Val);
1435   }
1436
1437   return Chain;
1438 }
1439
1440
1441 //===----------------------------------------------------------------------===//
1442 //                C & StdCall & Fast Calling Convention implementation
1443 //===----------------------------------------------------------------------===//
1444 //  StdCall calling convention seems to be standard for many Windows' API
1445 //  routines and around. It differs from C calling convention just a little:
1446 //  callee should clean up the stack, not caller. Symbols should be also
1447 //  decorated in some fancy way :) It doesn't support any vector arguments.
1448 //  For info on fast calling convention see Fast Calling Convention (tail call)
1449 //  implementation LowerX86_32FastCCCallTo.
1450
1451 /// CallIsStructReturn - Determines whether a call uses struct return
1452 /// semantics.
1453 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1454   if (Outs.empty())
1455     return false;
1456
1457   return Outs[0].Flags.isSRet();
1458 }
1459
1460 /// ArgsAreStructReturn - Determines whether a function uses struct
1461 /// return semantics.
1462 static bool
1463 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1464   if (Ins.empty())
1465     return false;
1466
1467   return Ins[0].Flags.isSRet();
1468 }
1469
1470 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1471 /// by "Src" to address "Dst" with size and alignment information specified by
1472 /// the specific parameter attribute. The copy will be passed as a byval
1473 /// function parameter.
1474 static SDValue
1475 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1476                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1477                           DebugLoc dl) {
1478   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1479
1480   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1481                        /*isVolatile*/false, /*AlwaysInline=*/true,
1482                        MachinePointerInfo(), MachinePointerInfo());
1483 }
1484
1485 /// IsTailCallConvention - Return true if the calling convention is one that
1486 /// supports tail call optimization.
1487 static bool IsTailCallConvention(CallingConv::ID CC) {
1488   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1489 }
1490
1491 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1492 /// a tailcall target by changing its ABI.
1493 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1494   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1495 }
1496
1497 SDValue
1498 X86TargetLowering::LowerMemArgument(SDValue Chain,
1499                                     CallingConv::ID CallConv,
1500                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1501                                     DebugLoc dl, SelectionDAG &DAG,
1502                                     const CCValAssign &VA,
1503                                     MachineFrameInfo *MFI,
1504                                     unsigned i) const {
1505   // Create the nodes corresponding to a load from this parameter slot.
1506   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1507   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1508   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1509   EVT ValVT;
1510
1511   // If value is passed by pointer we have address passed instead of the value
1512   // itself.
1513   if (VA.getLocInfo() == CCValAssign::Indirect)
1514     ValVT = VA.getLocVT();
1515   else
1516     ValVT = VA.getValVT();
1517
1518   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1519   // changed with more analysis.
1520   // In case of tail call optimization mark all arguments mutable. Since they
1521   // could be overwritten by lowering of arguments in case of a tail call.
1522   if (Flags.isByVal()) {
1523     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1524                                     VA.getLocMemOffset(), isImmutable);
1525     return DAG.getFrameIndex(FI, getPointerTy());
1526   } else {
1527     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1528                                     VA.getLocMemOffset(), isImmutable);
1529     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1530     return DAG.getLoad(ValVT, dl, Chain, FIN,
1531                        MachinePointerInfo::getFixedStack(FI),
1532                        false, false, 0);
1533   }
1534 }
1535
1536 SDValue
1537 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1538                                         CallingConv::ID CallConv,
1539                                         bool isVarArg,
1540                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1541                                         DebugLoc dl,
1542                                         SelectionDAG &DAG,
1543                                         SmallVectorImpl<SDValue> &InVals)
1544                                           const {
1545   MachineFunction &MF = DAG.getMachineFunction();
1546   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1547
1548   const Function* Fn = MF.getFunction();
1549   if (Fn->hasExternalLinkage() &&
1550       Subtarget->isTargetCygMing() &&
1551       Fn->getName() == "main")
1552     FuncInfo->setForceFramePointer(true);
1553
1554   MachineFrameInfo *MFI = MF.getFrameInfo();
1555   bool Is64Bit = Subtarget->is64Bit();
1556   bool IsWin64 = Subtarget->isTargetWin64();
1557
1558   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1559          "Var args not supported with calling convention fastcc or ghc");
1560
1561   // Assign locations to all of the incoming arguments.
1562   SmallVector<CCValAssign, 16> ArgLocs;
1563   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1564                  ArgLocs, *DAG.getContext());
1565   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1566
1567   unsigned LastVal = ~0U;
1568   SDValue ArgValue;
1569   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1570     CCValAssign &VA = ArgLocs[i];
1571     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1572     // places.
1573     assert(VA.getValNo() != LastVal &&
1574            "Don't support value assigned to multiple locs yet");
1575     LastVal = VA.getValNo();
1576
1577     if (VA.isRegLoc()) {
1578       EVT RegVT = VA.getLocVT();
1579       TargetRegisterClass *RC = NULL;
1580       if (RegVT == MVT::i32)
1581         RC = X86::GR32RegisterClass;
1582       else if (Is64Bit && RegVT == MVT::i64)
1583         RC = X86::GR64RegisterClass;
1584       else if (RegVT == MVT::f32)
1585         RC = X86::FR32RegisterClass;
1586       else if (RegVT == MVT::f64)
1587         RC = X86::FR64RegisterClass;
1588       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1589         RC = X86::VR256RegisterClass;
1590       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1591         RC = X86::VR128RegisterClass;
1592       else if (RegVT == MVT::x86mmx)
1593         RC = X86::VR64RegisterClass;
1594       else
1595         llvm_unreachable("Unknown argument type!");
1596
1597       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1598       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1599
1600       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1601       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1602       // right size.
1603       if (VA.getLocInfo() == CCValAssign::SExt)
1604         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1605                                DAG.getValueType(VA.getValVT()));
1606       else if (VA.getLocInfo() == CCValAssign::ZExt)
1607         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1608                                DAG.getValueType(VA.getValVT()));
1609       else if (VA.getLocInfo() == CCValAssign::BCvt)
1610         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1611
1612       if (VA.isExtInLoc()) {
1613         // Handle MMX values passed in XMM regs.
1614         if (RegVT.isVector()) {
1615           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1616                                  ArgValue);
1617         } else
1618           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1619       }
1620     } else {
1621       assert(VA.isMemLoc());
1622       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1623     }
1624
1625     // If value is passed via pointer - do a load.
1626     if (VA.getLocInfo() == CCValAssign::Indirect)
1627       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1628                              MachinePointerInfo(), false, false, 0);
1629
1630     InVals.push_back(ArgValue);
1631   }
1632
1633   // The x86-64 ABI for returning structs by value requires that we copy
1634   // the sret argument into %rax for the return. Save the argument into
1635   // a virtual register so that we can access it from the return points.
1636   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1637     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1638     unsigned Reg = FuncInfo->getSRetReturnReg();
1639     if (!Reg) {
1640       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1641       FuncInfo->setSRetReturnReg(Reg);
1642     }
1643     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1644     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1645   }
1646
1647   unsigned StackSize = CCInfo.getNextStackOffset();
1648   // Align stack specially for tail calls.
1649   if (FuncIsMadeTailCallSafe(CallConv))
1650     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1651
1652   // If the function takes variable number of arguments, make a frame index for
1653   // the start of the first vararg value... for expansion of llvm.va_start.
1654   if (isVarArg) {
1655     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1656                     CallConv != CallingConv::X86_ThisCall))) {
1657       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1658     }
1659     if (Is64Bit) {
1660       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1661
1662       // FIXME: We should really autogenerate these arrays
1663       static const unsigned GPR64ArgRegsWin64[] = {
1664         X86::RCX, X86::RDX, X86::R8,  X86::R9
1665       };
1666       static const unsigned GPR64ArgRegs64Bit[] = {
1667         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1668       };
1669       static const unsigned XMMArgRegs64Bit[] = {
1670         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1671         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1672       };
1673       const unsigned *GPR64ArgRegs;
1674       unsigned NumXMMRegs = 0;
1675
1676       if (IsWin64) {
1677         // The XMM registers which might contain var arg parameters are shadowed
1678         // in their paired GPR.  So we only need to save the GPR to their home
1679         // slots.
1680         TotalNumIntRegs = 4;
1681         GPR64ArgRegs = GPR64ArgRegsWin64;
1682       } else {
1683         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1684         GPR64ArgRegs = GPR64ArgRegs64Bit;
1685
1686         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1687       }
1688       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1689                                                        TotalNumIntRegs);
1690
1691       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1692       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1693              "SSE register cannot be used when SSE is disabled!");
1694       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1695              "SSE register cannot be used when SSE is disabled!");
1696       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1697         // Kernel mode asks for SSE to be disabled, so don't push them
1698         // on the stack.
1699         TotalNumXMMRegs = 0;
1700
1701       if (IsWin64) {
1702         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1703         // Get to the caller-allocated home save location.  Add 8 to account
1704         // for the return address.
1705         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1706         FuncInfo->setRegSaveFrameIndex(
1707           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1708         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1709       } else {
1710         // For X86-64, if there are vararg parameters that are passed via
1711         // registers, then we must store them to their spots on the stack so they
1712         // may be loaded by deferencing the result of va_next.
1713         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1714         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1715         FuncInfo->setRegSaveFrameIndex(
1716           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1717                                false));
1718       }
1719
1720       // Store the integer parameter registers.
1721       SmallVector<SDValue, 8> MemOps;
1722       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1723                                         getPointerTy());
1724       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1725       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1726         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1727                                   DAG.getIntPtrConstant(Offset));
1728         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1729                                      X86::GR64RegisterClass);
1730         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1731         SDValue Store =
1732           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1733                        MachinePointerInfo::getFixedStack(
1734                          FuncInfo->getRegSaveFrameIndex(), Offset),
1735                        false, false, 0);
1736         MemOps.push_back(Store);
1737         Offset += 8;
1738       }
1739
1740       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1741         // Now store the XMM (fp + vector) parameter registers.
1742         SmallVector<SDValue, 11> SaveXMMOps;
1743         SaveXMMOps.push_back(Chain);
1744
1745         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1746         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1747         SaveXMMOps.push_back(ALVal);
1748
1749         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1750                                FuncInfo->getRegSaveFrameIndex()));
1751         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1752                                FuncInfo->getVarArgsFPOffset()));
1753
1754         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1755           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1756                                        X86::VR128RegisterClass);
1757           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1758           SaveXMMOps.push_back(Val);
1759         }
1760         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1761                                      MVT::Other,
1762                                      &SaveXMMOps[0], SaveXMMOps.size()));
1763       }
1764
1765       if (!MemOps.empty())
1766         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1767                             &MemOps[0], MemOps.size());
1768     }
1769   }
1770
1771   // Some CCs need callee pop.
1772   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1773     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1774   } else {
1775     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1776     // If this is an sret function, the return should pop the hidden pointer.
1777     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1778       FuncInfo->setBytesToPopOnReturn(4);
1779   }
1780
1781   if (!Is64Bit) {
1782     // RegSaveFrameIndex is X86-64 only.
1783     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1784     if (CallConv == CallingConv::X86_FastCall ||
1785         CallConv == CallingConv::X86_ThisCall)
1786       // fastcc functions can't have varargs.
1787       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1788   }
1789
1790   return Chain;
1791 }
1792
1793 SDValue
1794 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1795                                     SDValue StackPtr, SDValue Arg,
1796                                     DebugLoc dl, SelectionDAG &DAG,
1797                                     const CCValAssign &VA,
1798                                     ISD::ArgFlagsTy Flags) const {
1799   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1800   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1801   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1802   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1803   if (Flags.isByVal())
1804     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1805
1806   return DAG.getStore(Chain, dl, Arg, PtrOff,
1807                       MachinePointerInfo::getStack(LocMemOffset),
1808                       false, false, 0);
1809 }
1810
1811 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1812 /// optimization is performed and it is required.
1813 SDValue
1814 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1815                                            SDValue &OutRetAddr, SDValue Chain,
1816                                            bool IsTailCall, bool Is64Bit,
1817                                            int FPDiff, DebugLoc dl) const {
1818   // Adjust the Return address stack slot.
1819   EVT VT = getPointerTy();
1820   OutRetAddr = getReturnAddressFrameIndex(DAG);
1821
1822   // Load the "old" Return address.
1823   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1824                            false, false, 0);
1825   return SDValue(OutRetAddr.getNode(), 1);
1826 }
1827
1828 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1829 /// optimization is performed and it is required (FPDiff!=0).
1830 static SDValue
1831 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1832                          SDValue Chain, SDValue RetAddrFrIdx,
1833                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1834   // Store the return address to the appropriate stack slot.
1835   if (!FPDiff) return Chain;
1836   // Calculate the new stack slot for the return address.
1837   int SlotSize = Is64Bit ? 8 : 4;
1838   int NewReturnAddrFI =
1839     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1840   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1841   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1842   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1843                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1844                        false, false, 0);
1845   return Chain;
1846 }
1847
1848 SDValue
1849 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1850                              CallingConv::ID CallConv, bool isVarArg,
1851                              bool &isTailCall,
1852                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1853                              const SmallVectorImpl<SDValue> &OutVals,
1854                              const SmallVectorImpl<ISD::InputArg> &Ins,
1855                              DebugLoc dl, SelectionDAG &DAG,
1856                              SmallVectorImpl<SDValue> &InVals) const {
1857   MachineFunction &MF = DAG.getMachineFunction();
1858   bool Is64Bit        = Subtarget->is64Bit();
1859   bool IsStructRet    = CallIsStructReturn(Outs);
1860   bool IsSibcall      = false;
1861
1862   if (isTailCall) {
1863     // Check if it's really possible to do a tail call.
1864     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1865                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1866                                                    Outs, OutVals, Ins, DAG);
1867
1868     // Sibcalls are automatically detected tailcalls which do not require
1869     // ABI changes.
1870     if (!GuaranteedTailCallOpt && isTailCall)
1871       IsSibcall = true;
1872
1873     if (isTailCall)
1874       ++NumTailCalls;
1875   }
1876
1877   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1878          "Var args not supported with calling convention fastcc or ghc");
1879
1880   // Analyze operands of the call, assigning locations to each operand.
1881   SmallVector<CCValAssign, 16> ArgLocs;
1882   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1883                  ArgLocs, *DAG.getContext());
1884   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1885
1886   // Get a count of how many bytes are to be pushed on the stack.
1887   unsigned NumBytes = CCInfo.getNextStackOffset();
1888   if (IsSibcall)
1889     // This is a sibcall. The memory operands are available in caller's
1890     // own caller's stack.
1891     NumBytes = 0;
1892   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1893     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1894
1895   int FPDiff = 0;
1896   if (isTailCall && !IsSibcall) {
1897     // Lower arguments at fp - stackoffset + fpdiff.
1898     unsigned NumBytesCallerPushed =
1899       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1900     FPDiff = NumBytesCallerPushed - NumBytes;
1901
1902     // Set the delta of movement of the returnaddr stackslot.
1903     // But only set if delta is greater than previous delta.
1904     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1905       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1906   }
1907
1908   if (!IsSibcall)
1909     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1910
1911   SDValue RetAddrFrIdx;
1912   // Load return adress for tail calls.
1913   if (isTailCall && FPDiff)
1914     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1915                                     Is64Bit, FPDiff, dl);
1916
1917   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1918   SmallVector<SDValue, 8> MemOpChains;
1919   SDValue StackPtr;
1920
1921   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1922   // of tail call optimization arguments are handle later.
1923   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1924     CCValAssign &VA = ArgLocs[i];
1925     EVT RegVT = VA.getLocVT();
1926     SDValue Arg = OutVals[i];
1927     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1928     bool isByVal = Flags.isByVal();
1929
1930     // Promote the value if needed.
1931     switch (VA.getLocInfo()) {
1932     default: llvm_unreachable("Unknown loc info!");
1933     case CCValAssign::Full: break;
1934     case CCValAssign::SExt:
1935       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1936       break;
1937     case CCValAssign::ZExt:
1938       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1939       break;
1940     case CCValAssign::AExt:
1941       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1942         // Special case: passing MMX values in XMM registers.
1943         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1944         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1945         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1946       } else
1947         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1948       break;
1949     case CCValAssign::BCvt:
1950       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1951       break;
1952     case CCValAssign::Indirect: {
1953       // Store the argument.
1954       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1955       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1956       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1957                            MachinePointerInfo::getFixedStack(FI),
1958                            false, false, 0);
1959       Arg = SpillSlot;
1960       break;
1961     }
1962     }
1963
1964     if (VA.isRegLoc()) {
1965       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1966       if (isVarArg && Subtarget->isTargetWin64()) {
1967         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1968         // shadow reg if callee is a varargs function.
1969         unsigned ShadowReg = 0;
1970         switch (VA.getLocReg()) {
1971         case X86::XMM0: ShadowReg = X86::RCX; break;
1972         case X86::XMM1: ShadowReg = X86::RDX; break;
1973         case X86::XMM2: ShadowReg = X86::R8; break;
1974         case X86::XMM3: ShadowReg = X86::R9; break;
1975         }
1976         if (ShadowReg)
1977           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1978       }
1979     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1980       assert(VA.isMemLoc());
1981       if (StackPtr.getNode() == 0)
1982         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1983       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1984                                              dl, DAG, VA, Flags));
1985     }
1986   }
1987
1988   if (!MemOpChains.empty())
1989     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1990                         &MemOpChains[0], MemOpChains.size());
1991
1992   // Build a sequence of copy-to-reg nodes chained together with token chain
1993   // and flag operands which copy the outgoing args into registers.
1994   SDValue InFlag;
1995   // Tail call byval lowering might overwrite argument registers so in case of
1996   // tail call optimization the copies to registers are lowered later.
1997   if (!isTailCall)
1998     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1999       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2000                                RegsToPass[i].second, InFlag);
2001       InFlag = Chain.getValue(1);
2002     }
2003
2004   if (Subtarget->isPICStyleGOT()) {
2005     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2006     // GOT pointer.
2007     if (!isTailCall) {
2008       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2009                                DAG.getNode(X86ISD::GlobalBaseReg,
2010                                            DebugLoc(), getPointerTy()),
2011                                InFlag);
2012       InFlag = Chain.getValue(1);
2013     } else {
2014       // If we are tail calling and generating PIC/GOT style code load the
2015       // address of the callee into ECX. The value in ecx is used as target of
2016       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2017       // for tail calls on PIC/GOT architectures. Normally we would just put the
2018       // address of GOT into ebx and then call target@PLT. But for tail calls
2019       // ebx would be restored (since ebx is callee saved) before jumping to the
2020       // target@PLT.
2021
2022       // Note: The actual moving to ECX is done further down.
2023       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2024       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2025           !G->getGlobal()->hasProtectedVisibility())
2026         Callee = LowerGlobalAddress(Callee, DAG);
2027       else if (isa<ExternalSymbolSDNode>(Callee))
2028         Callee = LowerExternalSymbol(Callee, DAG);
2029     }
2030   }
2031
2032   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2033     // From AMD64 ABI document:
2034     // For calls that may call functions that use varargs or stdargs
2035     // (prototype-less calls or calls to functions containing ellipsis (...) in
2036     // the declaration) %al is used as hidden argument to specify the number
2037     // of SSE registers used. The contents of %al do not need to match exactly
2038     // the number of registers, but must be an ubound on the number of SSE
2039     // registers used and is in the range 0 - 8 inclusive.
2040
2041     // Count the number of XMM registers allocated.
2042     static const unsigned XMMArgRegs[] = {
2043       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2044       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2045     };
2046     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2047     assert((Subtarget->hasXMM() || !NumXMMRegs)
2048            && "SSE registers cannot be used when SSE is disabled");
2049
2050     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2051                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2052     InFlag = Chain.getValue(1);
2053   }
2054
2055
2056   // For tail calls lower the arguments to the 'real' stack slot.
2057   if (isTailCall) {
2058     // Force all the incoming stack arguments to be loaded from the stack
2059     // before any new outgoing arguments are stored to the stack, because the
2060     // outgoing stack slots may alias the incoming argument stack slots, and
2061     // the alias isn't otherwise explicit. This is slightly more conservative
2062     // than necessary, because it means that each store effectively depends
2063     // on every argument instead of just those arguments it would clobber.
2064     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2065
2066     SmallVector<SDValue, 8> MemOpChains2;
2067     SDValue FIN;
2068     int FI = 0;
2069     // Do not flag preceeding copytoreg stuff together with the following stuff.
2070     InFlag = SDValue();
2071     if (GuaranteedTailCallOpt) {
2072       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2073         CCValAssign &VA = ArgLocs[i];
2074         if (VA.isRegLoc())
2075           continue;
2076         assert(VA.isMemLoc());
2077         SDValue Arg = OutVals[i];
2078         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2079         // Create frame index.
2080         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2081         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2082         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2083         FIN = DAG.getFrameIndex(FI, getPointerTy());
2084
2085         if (Flags.isByVal()) {
2086           // Copy relative to framepointer.
2087           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2088           if (StackPtr.getNode() == 0)
2089             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2090                                           getPointerTy());
2091           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2092
2093           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2094                                                            ArgChain,
2095                                                            Flags, DAG, dl));
2096         } else {
2097           // Store relative to framepointer.
2098           MemOpChains2.push_back(
2099             DAG.getStore(ArgChain, dl, Arg, FIN,
2100                          MachinePointerInfo::getFixedStack(FI),
2101                          false, false, 0));
2102         }
2103       }
2104     }
2105
2106     if (!MemOpChains2.empty())
2107       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2108                           &MemOpChains2[0], MemOpChains2.size());
2109
2110     // Copy arguments to their registers.
2111     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2112       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2113                                RegsToPass[i].second, InFlag);
2114       InFlag = Chain.getValue(1);
2115     }
2116     InFlag =SDValue();
2117
2118     // Store the return address to the appropriate stack slot.
2119     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2120                                      FPDiff, dl);
2121   }
2122
2123   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2124     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2125     // In the 64-bit large code model, we have to make all calls
2126     // through a register, since the call instruction's 32-bit
2127     // pc-relative offset may not be large enough to hold the whole
2128     // address.
2129   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2130     // If the callee is a GlobalAddress node (quite common, every direct call
2131     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2132     // it.
2133
2134     // We should use extra load for direct calls to dllimported functions in
2135     // non-JIT mode.
2136     const GlobalValue *GV = G->getGlobal();
2137     if (!GV->hasDLLImportLinkage()) {
2138       unsigned char OpFlags = 0;
2139
2140       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2141       // external symbols most go through the PLT in PIC mode.  If the symbol
2142       // has hidden or protected visibility, or if it is static or local, then
2143       // we don't need to use the PLT - we can directly call it.
2144       if (Subtarget->isTargetELF() &&
2145           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2146           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2147         OpFlags = X86II::MO_PLT;
2148       } else if (Subtarget->isPICStyleStubAny() &&
2149                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2150                  Subtarget->getDarwinVers() < 9) {
2151         // PC-relative references to external symbols should go through $stub,
2152         // unless we're building with the leopard linker or later, which
2153         // automatically synthesizes these stubs.
2154         OpFlags = X86II::MO_DARWIN_STUB;
2155       }
2156
2157       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2158                                           G->getOffset(), OpFlags);
2159     }
2160   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2161     unsigned char OpFlags = 0;
2162
2163     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2164     // external symbols should go through the PLT.
2165     if (Subtarget->isTargetELF() &&
2166         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2167       OpFlags = X86II::MO_PLT;
2168     } else if (Subtarget->isPICStyleStubAny() &&
2169                Subtarget->getDarwinVers() < 9) {
2170       // PC-relative references to external symbols should go through $stub,
2171       // unless we're building with the leopard linker or later, which
2172       // automatically synthesizes these stubs.
2173       OpFlags = X86II::MO_DARWIN_STUB;
2174     }
2175
2176     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2177                                          OpFlags);
2178   }
2179
2180   // Returns a chain & a flag for retval copy to use.
2181   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2182   SmallVector<SDValue, 8> Ops;
2183
2184   if (!IsSibcall && isTailCall) {
2185     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2186                            DAG.getIntPtrConstant(0, true), InFlag);
2187     InFlag = Chain.getValue(1);
2188   }
2189
2190   Ops.push_back(Chain);
2191   Ops.push_back(Callee);
2192
2193   if (isTailCall)
2194     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2195
2196   // Add argument registers to the end of the list so that they are known live
2197   // into the call.
2198   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2199     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2200                                   RegsToPass[i].second.getValueType()));
2201
2202   // Add an implicit use GOT pointer in EBX.
2203   if (!isTailCall && Subtarget->isPICStyleGOT())
2204     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2205
2206   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2207   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2208     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2209
2210   if (InFlag.getNode())
2211     Ops.push_back(InFlag);
2212
2213   if (isTailCall) {
2214     // We used to do:
2215     //// If this is the first return lowered for this function, add the regs
2216     //// to the liveout set for the function.
2217     // This isn't right, although it's probably harmless on x86; liveouts
2218     // should be computed from returns not tail calls.  Consider a void
2219     // function making a tail call to a function returning int.
2220     return DAG.getNode(X86ISD::TC_RETURN, dl,
2221                        NodeTys, &Ops[0], Ops.size());
2222   }
2223
2224   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2225   InFlag = Chain.getValue(1);
2226
2227   // Create the CALLSEQ_END node.
2228   unsigned NumBytesForCalleeToPush;
2229   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2230     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2231   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2232     // If this is a call to a struct-return function, the callee
2233     // pops the hidden struct pointer, so we have to push it back.
2234     // This is common for Darwin/X86, Linux & Mingw32 targets.
2235     NumBytesForCalleeToPush = 4;
2236   else
2237     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2238
2239   // Returns a flag for retval copy to use.
2240   if (!IsSibcall) {
2241     Chain = DAG.getCALLSEQ_END(Chain,
2242                                DAG.getIntPtrConstant(NumBytes, true),
2243                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2244                                                      true),
2245                                InFlag);
2246     InFlag = Chain.getValue(1);
2247   }
2248
2249   // Handle result values, copying them out of physregs into vregs that we
2250   // return.
2251   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2252                          Ins, dl, DAG, InVals);
2253 }
2254
2255
2256 //===----------------------------------------------------------------------===//
2257 //                Fast Calling Convention (tail call) implementation
2258 //===----------------------------------------------------------------------===//
2259
2260 //  Like std call, callee cleans arguments, convention except that ECX is
2261 //  reserved for storing the tail called function address. Only 2 registers are
2262 //  free for argument passing (inreg). Tail call optimization is performed
2263 //  provided:
2264 //                * tailcallopt is enabled
2265 //                * caller/callee are fastcc
2266 //  On X86_64 architecture with GOT-style position independent code only local
2267 //  (within module) calls are supported at the moment.
2268 //  To keep the stack aligned according to platform abi the function
2269 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2270 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2271 //  If a tail called function callee has more arguments than the caller the
2272 //  caller needs to make sure that there is room to move the RETADDR to. This is
2273 //  achieved by reserving an area the size of the argument delta right after the
2274 //  original REtADDR, but before the saved framepointer or the spilled registers
2275 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2276 //  stack layout:
2277 //    arg1
2278 //    arg2
2279 //    RETADDR
2280 //    [ new RETADDR
2281 //      move area ]
2282 //    (possible EBP)
2283 //    ESI
2284 //    EDI
2285 //    local1 ..
2286
2287 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2288 /// for a 16 byte align requirement.
2289 unsigned
2290 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2291                                                SelectionDAG& DAG) const {
2292   MachineFunction &MF = DAG.getMachineFunction();
2293   const TargetMachine &TM = MF.getTarget();
2294   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2295   unsigned StackAlignment = TFI.getStackAlignment();
2296   uint64_t AlignMask = StackAlignment - 1;
2297   int64_t Offset = StackSize;
2298   uint64_t SlotSize = TD->getPointerSize();
2299   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2300     // Number smaller than 12 so just add the difference.
2301     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2302   } else {
2303     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2304     Offset = ((~AlignMask) & Offset) + StackAlignment +
2305       (StackAlignment-SlotSize);
2306   }
2307   return Offset;
2308 }
2309
2310 /// MatchingStackOffset - Return true if the given stack call argument is
2311 /// already available in the same position (relatively) of the caller's
2312 /// incoming argument stack.
2313 static
2314 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2315                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2316                          const X86InstrInfo *TII) {
2317   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2318   int FI = INT_MAX;
2319   if (Arg.getOpcode() == ISD::CopyFromReg) {
2320     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2321     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2322       return false;
2323     MachineInstr *Def = MRI->getVRegDef(VR);
2324     if (!Def)
2325       return false;
2326     if (!Flags.isByVal()) {
2327       if (!TII->isLoadFromStackSlot(Def, FI))
2328         return false;
2329     } else {
2330       unsigned Opcode = Def->getOpcode();
2331       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2332           Def->getOperand(1).isFI()) {
2333         FI = Def->getOperand(1).getIndex();
2334         Bytes = Flags.getByValSize();
2335       } else
2336         return false;
2337     }
2338   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2339     if (Flags.isByVal())
2340       // ByVal argument is passed in as a pointer but it's now being
2341       // dereferenced. e.g.
2342       // define @foo(%struct.X* %A) {
2343       //   tail call @bar(%struct.X* byval %A)
2344       // }
2345       return false;
2346     SDValue Ptr = Ld->getBasePtr();
2347     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2348     if (!FINode)
2349       return false;
2350     FI = FINode->getIndex();
2351   } else
2352     return false;
2353
2354   assert(FI != INT_MAX);
2355   if (!MFI->isFixedObjectIndex(FI))
2356     return false;
2357   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2358 }
2359
2360 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2361 /// for tail call optimization. Targets which want to do tail call
2362 /// optimization should implement this function.
2363 bool
2364 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2365                                                      CallingConv::ID CalleeCC,
2366                                                      bool isVarArg,
2367                                                      bool isCalleeStructRet,
2368                                                      bool isCallerStructRet,
2369                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2370                                     const SmallVectorImpl<SDValue> &OutVals,
2371                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2372                                                      SelectionDAG& DAG) const {
2373   if (!IsTailCallConvention(CalleeCC) &&
2374       CalleeCC != CallingConv::C)
2375     return false;
2376
2377   // If -tailcallopt is specified, make fastcc functions tail-callable.
2378   const MachineFunction &MF = DAG.getMachineFunction();
2379   const Function *CallerF = DAG.getMachineFunction().getFunction();
2380   CallingConv::ID CallerCC = CallerF->getCallingConv();
2381   bool CCMatch = CallerCC == CalleeCC;
2382
2383   if (GuaranteedTailCallOpt) {
2384     if (IsTailCallConvention(CalleeCC) && CCMatch)
2385       return true;
2386     return false;
2387   }
2388
2389   // Look for obvious safe cases to perform tail call optimization that do not
2390   // require ABI changes. This is what gcc calls sibcall.
2391
2392   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2393   // emit a special epilogue.
2394   if (RegInfo->needsStackRealignment(MF))
2395     return false;
2396
2397   // Do not sibcall optimize vararg calls unless the call site is not passing
2398   // any arguments.
2399   if (isVarArg && !Outs.empty())
2400     return false;
2401
2402   // Also avoid sibcall optimization if either caller or callee uses struct
2403   // return semantics.
2404   if (isCalleeStructRet || isCallerStructRet)
2405     return false;
2406
2407   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2408   // Therefore if it's not used by the call it is not safe to optimize this into
2409   // a sibcall.
2410   bool Unused = false;
2411   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2412     if (!Ins[i].Used) {
2413       Unused = true;
2414       break;
2415     }
2416   }
2417   if (Unused) {
2418     SmallVector<CCValAssign, 16> RVLocs;
2419     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2420                    RVLocs, *DAG.getContext());
2421     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2422     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2423       CCValAssign &VA = RVLocs[i];
2424       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2425         return false;
2426     }
2427   }
2428
2429   // If the calling conventions do not match, then we'd better make sure the
2430   // results are returned in the same way as what the caller expects.
2431   if (!CCMatch) {
2432     SmallVector<CCValAssign, 16> RVLocs1;
2433     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2434                     RVLocs1, *DAG.getContext());
2435     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2436
2437     SmallVector<CCValAssign, 16> RVLocs2;
2438     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2439                     RVLocs2, *DAG.getContext());
2440     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2441
2442     if (RVLocs1.size() != RVLocs2.size())
2443       return false;
2444     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2445       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2446         return false;
2447       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2448         return false;
2449       if (RVLocs1[i].isRegLoc()) {
2450         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2451           return false;
2452       } else {
2453         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2454           return false;
2455       }
2456     }
2457   }
2458
2459   // If the callee takes no arguments then go on to check the results of the
2460   // call.
2461   if (!Outs.empty()) {
2462     // Check if stack adjustment is needed. For now, do not do this if any
2463     // argument is passed on the stack.
2464     SmallVector<CCValAssign, 16> ArgLocs;
2465     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2466                    ArgLocs, *DAG.getContext());
2467     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2468     if (CCInfo.getNextStackOffset()) {
2469       MachineFunction &MF = DAG.getMachineFunction();
2470       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2471         return false;
2472       if (Subtarget->isTargetWin64())
2473         // Win64 ABI has additional complications.
2474         return false;
2475
2476       // Check if the arguments are already laid out in the right way as
2477       // the caller's fixed stack objects.
2478       MachineFrameInfo *MFI = MF.getFrameInfo();
2479       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2480       const X86InstrInfo *TII =
2481         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2482       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2483         CCValAssign &VA = ArgLocs[i];
2484         SDValue Arg = OutVals[i];
2485         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2486         if (VA.getLocInfo() == CCValAssign::Indirect)
2487           return false;
2488         if (!VA.isRegLoc()) {
2489           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2490                                    MFI, MRI, TII))
2491             return false;
2492         }
2493       }
2494     }
2495
2496     // If the tailcall address may be in a register, then make sure it's
2497     // possible to register allocate for it. In 32-bit, the call address can
2498     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2499     // callee-saved registers are restored. These happen to be the same
2500     // registers used to pass 'inreg' arguments so watch out for those.
2501     if (!Subtarget->is64Bit() &&
2502         !isa<GlobalAddressSDNode>(Callee) &&
2503         !isa<ExternalSymbolSDNode>(Callee)) {
2504       unsigned NumInRegs = 0;
2505       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2506         CCValAssign &VA = ArgLocs[i];
2507         if (!VA.isRegLoc())
2508           continue;
2509         unsigned Reg = VA.getLocReg();
2510         switch (Reg) {
2511         default: break;
2512         case X86::EAX: case X86::EDX: case X86::ECX:
2513           if (++NumInRegs == 3)
2514             return false;
2515           break;
2516         }
2517       }
2518     }
2519   }
2520
2521   // An stdcall caller is expected to clean up its arguments; the callee
2522   // isn't going to do that.
2523   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2524     return false;
2525
2526   return true;
2527 }
2528
2529 FastISel *
2530 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2531   return X86::createFastISel(funcInfo);
2532 }
2533
2534
2535 //===----------------------------------------------------------------------===//
2536 //                           Other Lowering Hooks
2537 //===----------------------------------------------------------------------===//
2538
2539 static bool MayFoldLoad(SDValue Op) {
2540   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2541 }
2542
2543 static bool MayFoldIntoStore(SDValue Op) {
2544   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2545 }
2546
2547 static bool isTargetShuffle(unsigned Opcode) {
2548   switch(Opcode) {
2549   default: return false;
2550   case X86ISD::PSHUFD:
2551   case X86ISD::PSHUFHW:
2552   case X86ISD::PSHUFLW:
2553   case X86ISD::SHUFPD:
2554   case X86ISD::PALIGN:
2555   case X86ISD::SHUFPS:
2556   case X86ISD::MOVLHPS:
2557   case X86ISD::MOVLHPD:
2558   case X86ISD::MOVHLPS:
2559   case X86ISD::MOVLPS:
2560   case X86ISD::MOVLPD:
2561   case X86ISD::MOVSHDUP:
2562   case X86ISD::MOVSLDUP:
2563   case X86ISD::MOVDDUP:
2564   case X86ISD::MOVSS:
2565   case X86ISD::MOVSD:
2566   case X86ISD::UNPCKLPS:
2567   case X86ISD::UNPCKLPD:
2568   case X86ISD::PUNPCKLWD:
2569   case X86ISD::PUNPCKLBW:
2570   case X86ISD::PUNPCKLDQ:
2571   case X86ISD::PUNPCKLQDQ:
2572   case X86ISD::UNPCKHPS:
2573   case X86ISD::UNPCKHPD:
2574   case X86ISD::PUNPCKHWD:
2575   case X86ISD::PUNPCKHBW:
2576   case X86ISD::PUNPCKHDQ:
2577   case X86ISD::PUNPCKHQDQ:
2578     return true;
2579   }
2580   return false;
2581 }
2582
2583 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2584                                                SDValue V1, SelectionDAG &DAG) {
2585   switch(Opc) {
2586   default: llvm_unreachable("Unknown x86 shuffle node");
2587   case X86ISD::MOVSHDUP:
2588   case X86ISD::MOVSLDUP:
2589   case X86ISD::MOVDDUP:
2590     return DAG.getNode(Opc, dl, VT, V1);
2591   }
2592
2593   return SDValue();
2594 }
2595
2596 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2597                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2598   switch(Opc) {
2599   default: llvm_unreachable("Unknown x86 shuffle node");
2600   case X86ISD::PSHUFD:
2601   case X86ISD::PSHUFHW:
2602   case X86ISD::PSHUFLW:
2603     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2604   }
2605
2606   return SDValue();
2607 }
2608
2609 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2610                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2611   switch(Opc) {
2612   default: llvm_unreachable("Unknown x86 shuffle node");
2613   case X86ISD::PALIGN:
2614   case X86ISD::SHUFPD:
2615   case X86ISD::SHUFPS:
2616     return DAG.getNode(Opc, dl, VT, V1, V2,
2617                        DAG.getConstant(TargetMask, MVT::i8));
2618   }
2619   return SDValue();
2620 }
2621
2622 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2623                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2624   switch(Opc) {
2625   default: llvm_unreachable("Unknown x86 shuffle node");
2626   case X86ISD::MOVLHPS:
2627   case X86ISD::MOVLHPD:
2628   case X86ISD::MOVHLPS:
2629   case X86ISD::MOVLPS:
2630   case X86ISD::MOVLPD:
2631   case X86ISD::MOVSS:
2632   case X86ISD::MOVSD:
2633   case X86ISD::UNPCKLPS:
2634   case X86ISD::UNPCKLPD:
2635   case X86ISD::PUNPCKLWD:
2636   case X86ISD::PUNPCKLBW:
2637   case X86ISD::PUNPCKLDQ:
2638   case X86ISD::PUNPCKLQDQ:
2639   case X86ISD::UNPCKHPS:
2640   case X86ISD::UNPCKHPD:
2641   case X86ISD::PUNPCKHWD:
2642   case X86ISD::PUNPCKHBW:
2643   case X86ISD::PUNPCKHDQ:
2644   case X86ISD::PUNPCKHQDQ:
2645     return DAG.getNode(Opc, dl, VT, V1, V2);
2646   }
2647   return SDValue();
2648 }
2649
2650 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2651   MachineFunction &MF = DAG.getMachineFunction();
2652   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2653   int ReturnAddrIndex = FuncInfo->getRAIndex();
2654
2655   if (ReturnAddrIndex == 0) {
2656     // Set up a frame object for the return address.
2657     uint64_t SlotSize = TD->getPointerSize();
2658     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2659                                                            false);
2660     FuncInfo->setRAIndex(ReturnAddrIndex);
2661   }
2662
2663   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2664 }
2665
2666
2667 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2668                                        bool hasSymbolicDisplacement) {
2669   // Offset should fit into 32 bit immediate field.
2670   if (!isInt<32>(Offset))
2671     return false;
2672
2673   // If we don't have a symbolic displacement - we don't have any extra
2674   // restrictions.
2675   if (!hasSymbolicDisplacement)
2676     return true;
2677
2678   // FIXME: Some tweaks might be needed for medium code model.
2679   if (M != CodeModel::Small && M != CodeModel::Kernel)
2680     return false;
2681
2682   // For small code model we assume that latest object is 16MB before end of 31
2683   // bits boundary. We may also accept pretty large negative constants knowing
2684   // that all objects are in the positive half of address space.
2685   if (M == CodeModel::Small && Offset < 16*1024*1024)
2686     return true;
2687
2688   // For kernel code model we know that all object resist in the negative half
2689   // of 32bits address space. We may not accept negative offsets, since they may
2690   // be just off and we may accept pretty large positive ones.
2691   if (M == CodeModel::Kernel && Offset > 0)
2692     return true;
2693
2694   return false;
2695 }
2696
2697 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2698 /// specific condition code, returning the condition code and the LHS/RHS of the
2699 /// comparison to make.
2700 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2701                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2702   if (!isFP) {
2703     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2704       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2705         // X > -1   -> X == 0, jump !sign.
2706         RHS = DAG.getConstant(0, RHS.getValueType());
2707         return X86::COND_NS;
2708       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2709         // X < 0   -> X == 0, jump on sign.
2710         return X86::COND_S;
2711       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2712         // X < 1   -> X <= 0
2713         RHS = DAG.getConstant(0, RHS.getValueType());
2714         return X86::COND_LE;
2715       }
2716     }
2717
2718     switch (SetCCOpcode) {
2719     default: llvm_unreachable("Invalid integer condition!");
2720     case ISD::SETEQ:  return X86::COND_E;
2721     case ISD::SETGT:  return X86::COND_G;
2722     case ISD::SETGE:  return X86::COND_GE;
2723     case ISD::SETLT:  return X86::COND_L;
2724     case ISD::SETLE:  return X86::COND_LE;
2725     case ISD::SETNE:  return X86::COND_NE;
2726     case ISD::SETULT: return X86::COND_B;
2727     case ISD::SETUGT: return X86::COND_A;
2728     case ISD::SETULE: return X86::COND_BE;
2729     case ISD::SETUGE: return X86::COND_AE;
2730     }
2731   }
2732
2733   // First determine if it is required or is profitable to flip the operands.
2734
2735   // If LHS is a foldable load, but RHS is not, flip the condition.
2736   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2737       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2738     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2739     std::swap(LHS, RHS);
2740   }
2741
2742   switch (SetCCOpcode) {
2743   default: break;
2744   case ISD::SETOLT:
2745   case ISD::SETOLE:
2746   case ISD::SETUGT:
2747   case ISD::SETUGE:
2748     std::swap(LHS, RHS);
2749     break;
2750   }
2751
2752   // On a floating point condition, the flags are set as follows:
2753   // ZF  PF  CF   op
2754   //  0 | 0 | 0 | X > Y
2755   //  0 | 0 | 1 | X < Y
2756   //  1 | 0 | 0 | X == Y
2757   //  1 | 1 | 1 | unordered
2758   switch (SetCCOpcode) {
2759   default: llvm_unreachable("Condcode should be pre-legalized away");
2760   case ISD::SETUEQ:
2761   case ISD::SETEQ:   return X86::COND_E;
2762   case ISD::SETOLT:              // flipped
2763   case ISD::SETOGT:
2764   case ISD::SETGT:   return X86::COND_A;
2765   case ISD::SETOLE:              // flipped
2766   case ISD::SETOGE:
2767   case ISD::SETGE:   return X86::COND_AE;
2768   case ISD::SETUGT:              // flipped
2769   case ISD::SETULT:
2770   case ISD::SETLT:   return X86::COND_B;
2771   case ISD::SETUGE:              // flipped
2772   case ISD::SETULE:
2773   case ISD::SETLE:   return X86::COND_BE;
2774   case ISD::SETONE:
2775   case ISD::SETNE:   return X86::COND_NE;
2776   case ISD::SETUO:   return X86::COND_P;
2777   case ISD::SETO:    return X86::COND_NP;
2778   case ISD::SETOEQ:
2779   case ISD::SETUNE:  return X86::COND_INVALID;
2780   }
2781 }
2782
2783 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2784 /// code. Current x86 isa includes the following FP cmov instructions:
2785 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2786 static bool hasFPCMov(unsigned X86CC) {
2787   switch (X86CC) {
2788   default:
2789     return false;
2790   case X86::COND_B:
2791   case X86::COND_BE:
2792   case X86::COND_E:
2793   case X86::COND_P:
2794   case X86::COND_A:
2795   case X86::COND_AE:
2796   case X86::COND_NE:
2797   case X86::COND_NP:
2798     return true;
2799   }
2800 }
2801
2802 /// isFPImmLegal - Returns true if the target can instruction select the
2803 /// specified FP immediate natively. If false, the legalizer will
2804 /// materialize the FP immediate as a load from a constant pool.
2805 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2806   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2807     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2808       return true;
2809   }
2810   return false;
2811 }
2812
2813 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2814 /// the specified range (L, H].
2815 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2816   return (Val < 0) || (Val >= Low && Val < Hi);
2817 }
2818
2819 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2820 /// specified value.
2821 static bool isUndefOrEqual(int Val, int CmpVal) {
2822   if (Val < 0 || Val == CmpVal)
2823     return true;
2824   return false;
2825 }
2826
2827 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2828 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2829 /// the second operand.
2830 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2831   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2832     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2833   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2834     return (Mask[0] < 2 && Mask[1] < 2);
2835   return false;
2836 }
2837
2838 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2839   SmallVector<int, 8> M;
2840   N->getMask(M);
2841   return ::isPSHUFDMask(M, N->getValueType(0));
2842 }
2843
2844 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2845 /// is suitable for input to PSHUFHW.
2846 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2847   if (VT != MVT::v8i16)
2848     return false;
2849
2850   // Lower quadword copied in order or undef.
2851   for (int i = 0; i != 4; ++i)
2852     if (Mask[i] >= 0 && Mask[i] != i)
2853       return false;
2854
2855   // Upper quadword shuffled.
2856   for (int i = 4; i != 8; ++i)
2857     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2858       return false;
2859
2860   return true;
2861 }
2862
2863 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2864   SmallVector<int, 8> M;
2865   N->getMask(M);
2866   return ::isPSHUFHWMask(M, N->getValueType(0));
2867 }
2868
2869 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2870 /// is suitable for input to PSHUFLW.
2871 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2872   if (VT != MVT::v8i16)
2873     return false;
2874
2875   // Upper quadword copied in order.
2876   for (int i = 4; i != 8; ++i)
2877     if (Mask[i] >= 0 && Mask[i] != i)
2878       return false;
2879
2880   // Lower quadword shuffled.
2881   for (int i = 0; i != 4; ++i)
2882     if (Mask[i] >= 4)
2883       return false;
2884
2885   return true;
2886 }
2887
2888 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2889   SmallVector<int, 8> M;
2890   N->getMask(M);
2891   return ::isPSHUFLWMask(M, N->getValueType(0));
2892 }
2893
2894 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2895 /// is suitable for input to PALIGNR.
2896 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2897                           bool hasSSSE3) {
2898   int i, e = VT.getVectorNumElements();
2899
2900   // Do not handle v2i64 / v2f64 shuffles with palignr.
2901   if (e < 4 || !hasSSSE3)
2902     return false;
2903
2904   for (i = 0; i != e; ++i)
2905     if (Mask[i] >= 0)
2906       break;
2907
2908   // All undef, not a palignr.
2909   if (i == e)
2910     return false;
2911
2912   // Determine if it's ok to perform a palignr with only the LHS, since we
2913   // don't have access to the actual shuffle elements to see if RHS is undef.
2914   bool Unary = Mask[i] < (int)e;
2915   bool NeedsUnary = false;
2916
2917   int s = Mask[i] - i;
2918
2919   // Check the rest of the elements to see if they are consecutive.
2920   for (++i; i != e; ++i) {
2921     int m = Mask[i];
2922     if (m < 0)
2923       continue;
2924
2925     Unary = Unary && (m < (int)e);
2926     NeedsUnary = NeedsUnary || (m < s);
2927
2928     if (NeedsUnary && !Unary)
2929       return false;
2930     if (Unary && m != ((s+i) & (e-1)))
2931       return false;
2932     if (!Unary && m != (s+i))
2933       return false;
2934   }
2935   return true;
2936 }
2937
2938 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2939   SmallVector<int, 8> M;
2940   N->getMask(M);
2941   return ::isPALIGNRMask(M, N->getValueType(0), true);
2942 }
2943
2944 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2945 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2946 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2947   int NumElems = VT.getVectorNumElements();
2948   if (NumElems != 2 && NumElems != 4)
2949     return false;
2950
2951   int Half = NumElems / 2;
2952   for (int i = 0; i < Half; ++i)
2953     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2954       return false;
2955   for (int i = Half; i < NumElems; ++i)
2956     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2957       return false;
2958
2959   return true;
2960 }
2961
2962 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2963   SmallVector<int, 8> M;
2964   N->getMask(M);
2965   return ::isSHUFPMask(M, N->getValueType(0));
2966 }
2967
2968 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2969 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2970 /// half elements to come from vector 1 (which would equal the dest.) and
2971 /// the upper half to come from vector 2.
2972 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973   int NumElems = VT.getVectorNumElements();
2974
2975   if (NumElems != 2 && NumElems != 4)
2976     return false;
2977
2978   int Half = NumElems / 2;
2979   for (int i = 0; i < Half; ++i)
2980     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2981       return false;
2982   for (int i = Half; i < NumElems; ++i)
2983     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2984       return false;
2985   return true;
2986 }
2987
2988 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2989   SmallVector<int, 8> M;
2990   N->getMask(M);
2991   return isCommutedSHUFPMask(M, N->getValueType(0));
2992 }
2993
2994 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2995 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2996 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2997   if (N->getValueType(0).getVectorNumElements() != 4)
2998     return false;
2999
3000   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3001   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3002          isUndefOrEqual(N->getMaskElt(1), 7) &&
3003          isUndefOrEqual(N->getMaskElt(2), 2) &&
3004          isUndefOrEqual(N->getMaskElt(3), 3);
3005 }
3006
3007 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3008 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3009 /// <2, 3, 2, 3>
3010 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3011   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3012
3013   if (NumElems != 4)
3014     return false;
3015
3016   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3017   isUndefOrEqual(N->getMaskElt(1), 3) &&
3018   isUndefOrEqual(N->getMaskElt(2), 2) &&
3019   isUndefOrEqual(N->getMaskElt(3), 3);
3020 }
3021
3022 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3023 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3024 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3025   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3026
3027   if (NumElems != 2 && NumElems != 4)
3028     return false;
3029
3030   for (unsigned i = 0; i < NumElems/2; ++i)
3031     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3032       return false;
3033
3034   for (unsigned i = NumElems/2; i < NumElems; ++i)
3035     if (!isUndefOrEqual(N->getMaskElt(i), i))
3036       return false;
3037
3038   return true;
3039 }
3040
3041 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3042 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3043 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3044   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3045
3046   if (NumElems != 2 && NumElems != 4)
3047     return false;
3048
3049   for (unsigned i = 0; i < NumElems/2; ++i)
3050     if (!isUndefOrEqual(N->getMaskElt(i), i))
3051       return false;
3052
3053   for (unsigned i = 0; i < NumElems/2; ++i)
3054     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3055       return false;
3056
3057   return true;
3058 }
3059
3060 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3061 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3062 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3063                          bool V2IsSplat = false) {
3064   int NumElts = VT.getVectorNumElements();
3065   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3066     return false;
3067
3068   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3069     int BitI  = Mask[i];
3070     int BitI1 = Mask[i+1];
3071     if (!isUndefOrEqual(BitI, j))
3072       return false;
3073     if (V2IsSplat) {
3074       if (!isUndefOrEqual(BitI1, NumElts))
3075         return false;
3076     } else {
3077       if (!isUndefOrEqual(BitI1, j + NumElts))
3078         return false;
3079     }
3080   }
3081   return true;
3082 }
3083
3084 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3085   SmallVector<int, 8> M;
3086   N->getMask(M);
3087   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3088 }
3089
3090 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3091 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3092 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3093                          bool V2IsSplat = false) {
3094   int NumElts = VT.getVectorNumElements();
3095   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3096     return false;
3097
3098   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3099     int BitI  = Mask[i];
3100     int BitI1 = Mask[i+1];
3101     if (!isUndefOrEqual(BitI, j + NumElts/2))
3102       return false;
3103     if (V2IsSplat) {
3104       if (isUndefOrEqual(BitI1, NumElts))
3105         return false;
3106     } else {
3107       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3108         return false;
3109     }
3110   }
3111   return true;
3112 }
3113
3114 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3115   SmallVector<int, 8> M;
3116   N->getMask(M);
3117   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3118 }
3119
3120 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3121 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3122 /// <0, 0, 1, 1>
3123 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3124   int NumElems = VT.getVectorNumElements();
3125   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3126     return false;
3127
3128   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3129     int BitI  = Mask[i];
3130     int BitI1 = Mask[i+1];
3131     if (!isUndefOrEqual(BitI, j))
3132       return false;
3133     if (!isUndefOrEqual(BitI1, j))
3134       return false;
3135   }
3136   return true;
3137 }
3138
3139 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3140   SmallVector<int, 8> M;
3141   N->getMask(M);
3142   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3143 }
3144
3145 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3146 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3147 /// <2, 2, 3, 3>
3148 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3149   int NumElems = VT.getVectorNumElements();
3150   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3151     return false;
3152
3153   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3154     int BitI  = Mask[i];
3155     int BitI1 = Mask[i+1];
3156     if (!isUndefOrEqual(BitI, j))
3157       return false;
3158     if (!isUndefOrEqual(BitI1, j))
3159       return false;
3160   }
3161   return true;
3162 }
3163
3164 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3165   SmallVector<int, 8> M;
3166   N->getMask(M);
3167   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3168 }
3169
3170 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3171 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3172 /// MOVSD, and MOVD, i.e. setting the lowest element.
3173 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3174   if (VT.getVectorElementType().getSizeInBits() < 32)
3175     return false;
3176
3177   int NumElts = VT.getVectorNumElements();
3178
3179   if (!isUndefOrEqual(Mask[0], NumElts))
3180     return false;
3181
3182   for (int i = 1; i < NumElts; ++i)
3183     if (!isUndefOrEqual(Mask[i], i))
3184       return false;
3185
3186   return true;
3187 }
3188
3189 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3190   SmallVector<int, 8> M;
3191   N->getMask(M);
3192   return ::isMOVLMask(M, N->getValueType(0));
3193 }
3194
3195 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3196 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3197 /// element of vector 2 and the other elements to come from vector 1 in order.
3198 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3199                                bool V2IsSplat = false, bool V2IsUndef = false) {
3200   int NumOps = VT.getVectorNumElements();
3201   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3202     return false;
3203
3204   if (!isUndefOrEqual(Mask[0], 0))
3205     return false;
3206
3207   for (int i = 1; i < NumOps; ++i)
3208     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3209           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3210           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3211       return false;
3212
3213   return true;
3214 }
3215
3216 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3217                            bool V2IsUndef = false) {
3218   SmallVector<int, 8> M;
3219   N->getMask(M);
3220   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3221 }
3222
3223 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3224 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3225 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3226   if (N->getValueType(0).getVectorNumElements() != 4)
3227     return false;
3228
3229   // Expect 1, 1, 3, 3
3230   for (unsigned i = 0; i < 2; ++i) {
3231     int Elt = N->getMaskElt(i);
3232     if (Elt >= 0 && Elt != 1)
3233       return false;
3234   }
3235
3236   bool HasHi = false;
3237   for (unsigned i = 2; i < 4; ++i) {
3238     int Elt = N->getMaskElt(i);
3239     if (Elt >= 0 && Elt != 3)
3240       return false;
3241     if (Elt == 3)
3242       HasHi = true;
3243   }
3244   // Don't use movshdup if it can be done with a shufps.
3245   // FIXME: verify that matching u, u, 3, 3 is what we want.
3246   return HasHi;
3247 }
3248
3249 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3250 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3251 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3252   if (N->getValueType(0).getVectorNumElements() != 4)
3253     return false;
3254
3255   // Expect 0, 0, 2, 2
3256   for (unsigned i = 0; i < 2; ++i)
3257     if (N->getMaskElt(i) > 0)
3258       return false;
3259
3260   bool HasHi = false;
3261   for (unsigned i = 2; i < 4; ++i) {
3262     int Elt = N->getMaskElt(i);
3263     if (Elt >= 0 && Elt != 2)
3264       return false;
3265     if (Elt == 2)
3266       HasHi = true;
3267   }
3268   // Don't use movsldup if it can be done with a shufps.
3269   return HasHi;
3270 }
3271
3272 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3273 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3274 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3275   int e = N->getValueType(0).getVectorNumElements() / 2;
3276
3277   for (int i = 0; i < e; ++i)
3278     if (!isUndefOrEqual(N->getMaskElt(i), i))
3279       return false;
3280   for (int i = 0; i < e; ++i)
3281     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3282       return false;
3283   return true;
3284 }
3285
3286 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3287 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3288 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3289   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3290   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3291
3292   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3293   unsigned Mask = 0;
3294   for (int i = 0; i < NumOperands; ++i) {
3295     int Val = SVOp->getMaskElt(NumOperands-i-1);
3296     if (Val < 0) Val = 0;
3297     if (Val >= NumOperands) Val -= NumOperands;
3298     Mask |= Val;
3299     if (i != NumOperands - 1)
3300       Mask <<= Shift;
3301   }
3302   return Mask;
3303 }
3304
3305 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3306 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3307 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3308   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3309   unsigned Mask = 0;
3310   // 8 nodes, but we only care about the last 4.
3311   for (unsigned i = 7; i >= 4; --i) {
3312     int Val = SVOp->getMaskElt(i);
3313     if (Val >= 0)
3314       Mask |= (Val - 4);
3315     if (i != 4)
3316       Mask <<= 2;
3317   }
3318   return Mask;
3319 }
3320
3321 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3322 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3323 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3324   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3325   unsigned Mask = 0;
3326   // 8 nodes, but we only care about the first 4.
3327   for (int i = 3; i >= 0; --i) {
3328     int Val = SVOp->getMaskElt(i);
3329     if (Val >= 0)
3330       Mask |= Val;
3331     if (i != 0)
3332       Mask <<= 2;
3333   }
3334   return Mask;
3335 }
3336
3337 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3338 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3339 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3340   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3341   EVT VVT = N->getValueType(0);
3342   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3343   int Val = 0;
3344
3345   unsigned i, e;
3346   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3347     Val = SVOp->getMaskElt(i);
3348     if (Val >= 0)
3349       break;
3350   }
3351   return (Val - i) * EltSize;
3352 }
3353
3354 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3355 /// constant +0.0.
3356 bool X86::isZeroNode(SDValue Elt) {
3357   return ((isa<ConstantSDNode>(Elt) &&
3358            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3359           (isa<ConstantFPSDNode>(Elt) &&
3360            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3361 }
3362
3363 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3364 /// their permute mask.
3365 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3366                                     SelectionDAG &DAG) {
3367   EVT VT = SVOp->getValueType(0);
3368   unsigned NumElems = VT.getVectorNumElements();
3369   SmallVector<int, 8> MaskVec;
3370
3371   for (unsigned i = 0; i != NumElems; ++i) {
3372     int idx = SVOp->getMaskElt(i);
3373     if (idx < 0)
3374       MaskVec.push_back(idx);
3375     else if (idx < (int)NumElems)
3376       MaskVec.push_back(idx + NumElems);
3377     else
3378       MaskVec.push_back(idx - NumElems);
3379   }
3380   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3381                               SVOp->getOperand(0), &MaskVec[0]);
3382 }
3383
3384 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3385 /// the two vector operands have swapped position.
3386 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3387   unsigned NumElems = VT.getVectorNumElements();
3388   for (unsigned i = 0; i != NumElems; ++i) {
3389     int idx = Mask[i];
3390     if (idx < 0)
3391       continue;
3392     else if (idx < (int)NumElems)
3393       Mask[i] = idx + NumElems;
3394     else
3395       Mask[i] = idx - NumElems;
3396   }
3397 }
3398
3399 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3400 /// match movhlps. The lower half elements should come from upper half of
3401 /// V1 (and in order), and the upper half elements should come from the upper
3402 /// half of V2 (and in order).
3403 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3404   if (Op->getValueType(0).getVectorNumElements() != 4)
3405     return false;
3406   for (unsigned i = 0, e = 2; i != e; ++i)
3407     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3408       return false;
3409   for (unsigned i = 2; i != 4; ++i)
3410     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3411       return false;
3412   return true;
3413 }
3414
3415 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3416 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3417 /// required.
3418 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3419   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3420     return false;
3421   N = N->getOperand(0).getNode();
3422   if (!ISD::isNON_EXTLoad(N))
3423     return false;
3424   if (LD)
3425     *LD = cast<LoadSDNode>(N);
3426   return true;
3427 }
3428
3429 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3430 /// match movlp{s|d}. The lower half elements should come from lower half of
3431 /// V1 (and in order), and the upper half elements should come from the upper
3432 /// half of V2 (and in order). And since V1 will become the source of the
3433 /// MOVLP, it must be either a vector load or a scalar load to vector.
3434 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3435                                ShuffleVectorSDNode *Op) {
3436   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3437     return false;
3438   // Is V2 is a vector load, don't do this transformation. We will try to use
3439   // load folding shufps op.
3440   if (ISD::isNON_EXTLoad(V2))
3441     return false;
3442
3443   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3444
3445   if (NumElems != 2 && NumElems != 4)
3446     return false;
3447   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3448     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3449       return false;
3450   for (unsigned i = NumElems/2; i != NumElems; ++i)
3451     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3452       return false;
3453   return true;
3454 }
3455
3456 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3457 /// all the same.
3458 static bool isSplatVector(SDNode *N) {
3459   if (N->getOpcode() != ISD::BUILD_VECTOR)
3460     return false;
3461
3462   SDValue SplatValue = N->getOperand(0);
3463   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3464     if (N->getOperand(i) != SplatValue)
3465       return false;
3466   return true;
3467 }
3468
3469 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3470 /// to an zero vector.
3471 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3472 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3473   SDValue V1 = N->getOperand(0);
3474   SDValue V2 = N->getOperand(1);
3475   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3476   for (unsigned i = 0; i != NumElems; ++i) {
3477     int Idx = N->getMaskElt(i);
3478     if (Idx >= (int)NumElems) {
3479       unsigned Opc = V2.getOpcode();
3480       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3481         continue;
3482       if (Opc != ISD::BUILD_VECTOR ||
3483           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3484         return false;
3485     } else if (Idx >= 0) {
3486       unsigned Opc = V1.getOpcode();
3487       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3488         continue;
3489       if (Opc != ISD::BUILD_VECTOR ||
3490           !X86::isZeroNode(V1.getOperand(Idx)))
3491         return false;
3492     }
3493   }
3494   return true;
3495 }
3496
3497 /// getZeroVector - Returns a vector of specified type with all zero elements.
3498 ///
3499 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3500                              DebugLoc dl) {
3501   assert(VT.isVector() && "Expected a vector type");
3502
3503   // Always build SSE zero vectors as <4 x i32> bitcasted
3504   // to their dest type. This ensures they get CSE'd.
3505   SDValue Vec;
3506   if (VT.getSizeInBits() == 128) {  // SSE
3507     if (HasSSE2) {  // SSE2
3508       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3509       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3510     } else { // SSE1
3511       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3512       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3513     }
3514   } else if (VT.getSizeInBits() == 256) { // AVX
3515     // 256-bit logic and arithmetic instructions in AVX are
3516     // all floating-point, no support for integer ops. Default
3517     // to emitting fp zeroed vectors then.
3518     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3519     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3520     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3521   }
3522   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3523 }
3524
3525 /// getOnesVector - Returns a vector of specified type with all bits set.
3526 ///
3527 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3528   assert(VT.isVector() && "Expected a vector type");
3529
3530   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3531   // type.  This ensures they get CSE'd.
3532   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3533   SDValue Vec;
3534   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3535   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3536 }
3537
3538
3539 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3540 /// that point to V2 points to its first element.
3541 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3542   EVT VT = SVOp->getValueType(0);
3543   unsigned NumElems = VT.getVectorNumElements();
3544
3545   bool Changed = false;
3546   SmallVector<int, 8> MaskVec;
3547   SVOp->getMask(MaskVec);
3548
3549   for (unsigned i = 0; i != NumElems; ++i) {
3550     if (MaskVec[i] > (int)NumElems) {
3551       MaskVec[i] = NumElems;
3552       Changed = true;
3553     }
3554   }
3555   if (Changed)
3556     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3557                                 SVOp->getOperand(1), &MaskVec[0]);
3558   return SDValue(SVOp, 0);
3559 }
3560
3561 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3562 /// operation of specified width.
3563 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3564                        SDValue V2) {
3565   unsigned NumElems = VT.getVectorNumElements();
3566   SmallVector<int, 8> Mask;
3567   Mask.push_back(NumElems);
3568   for (unsigned i = 1; i != NumElems; ++i)
3569     Mask.push_back(i);
3570   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3571 }
3572
3573 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3574 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3575                           SDValue V2) {
3576   unsigned NumElems = VT.getVectorNumElements();
3577   SmallVector<int, 8> Mask;
3578   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3579     Mask.push_back(i);
3580     Mask.push_back(i + NumElems);
3581   }
3582   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3583 }
3584
3585 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3586 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3587                           SDValue V2) {
3588   unsigned NumElems = VT.getVectorNumElements();
3589   unsigned Half = NumElems/2;
3590   SmallVector<int, 8> Mask;
3591   for (unsigned i = 0; i != Half; ++i) {
3592     Mask.push_back(i + Half);
3593     Mask.push_back(i + NumElems + Half);
3594   }
3595   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3596 }
3597
3598 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3599 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3600   EVT PVT = MVT::v4f32;
3601   EVT VT = SV->getValueType(0);
3602   DebugLoc dl = SV->getDebugLoc();
3603   SDValue V1 = SV->getOperand(0);
3604   int NumElems = VT.getVectorNumElements();
3605   int EltNo = SV->getSplatIndex();
3606
3607   // unpack elements to the correct location
3608   while (NumElems > 4) {
3609     if (EltNo < NumElems/2) {
3610       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3611     } else {
3612       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3613       EltNo -= NumElems/2;
3614     }
3615     NumElems >>= 1;
3616   }
3617
3618   // Perform the splat.
3619   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3620   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3621   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3622   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3623 }
3624
3625 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3626 /// vector of zero or undef vector.  This produces a shuffle where the low
3627 /// element of V2 is swizzled into the zero/undef vector, landing at element
3628 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3629 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3630                                              bool isZero, bool HasSSE2,
3631                                              SelectionDAG &DAG) {
3632   EVT VT = V2.getValueType();
3633   SDValue V1 = isZero
3634     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3635   unsigned NumElems = VT.getVectorNumElements();
3636   SmallVector<int, 16> MaskVec;
3637   for (unsigned i = 0; i != NumElems; ++i)
3638     // If this is the insertion idx, put the low elt of V2 here.
3639     MaskVec.push_back(i == Idx ? NumElems : i);
3640   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3641 }
3642
3643 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3644 /// element of the result of the vector shuffle.
3645 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3646                             unsigned Depth) {
3647   if (Depth == 6)
3648     return SDValue();  // Limit search depth.
3649
3650   SDValue V = SDValue(N, 0);
3651   EVT VT = V.getValueType();
3652   unsigned Opcode = V.getOpcode();
3653
3654   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3655   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3656     Index = SV->getMaskElt(Index);
3657
3658     if (Index < 0)
3659       return DAG.getUNDEF(VT.getVectorElementType());
3660
3661     int NumElems = VT.getVectorNumElements();
3662     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3663     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3664   }
3665
3666   // Recurse into target specific vector shuffles to find scalars.
3667   if (isTargetShuffle(Opcode)) {
3668     int NumElems = VT.getVectorNumElements();
3669     SmallVector<unsigned, 16> ShuffleMask;
3670     SDValue ImmN;
3671
3672     switch(Opcode) {
3673     case X86ISD::SHUFPS:
3674     case X86ISD::SHUFPD:
3675       ImmN = N->getOperand(N->getNumOperands()-1);
3676       DecodeSHUFPSMask(NumElems,
3677                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3678                        ShuffleMask);
3679       break;
3680     case X86ISD::PUNPCKHBW:
3681     case X86ISD::PUNPCKHWD:
3682     case X86ISD::PUNPCKHDQ:
3683     case X86ISD::PUNPCKHQDQ:
3684       DecodePUNPCKHMask(NumElems, ShuffleMask);
3685       break;
3686     case X86ISD::UNPCKHPS:
3687     case X86ISD::UNPCKHPD:
3688       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3689       break;
3690     case X86ISD::PUNPCKLBW:
3691     case X86ISD::PUNPCKLWD:
3692     case X86ISD::PUNPCKLDQ:
3693     case X86ISD::PUNPCKLQDQ:
3694       DecodePUNPCKLMask(NumElems, ShuffleMask);
3695       break;
3696     case X86ISD::UNPCKLPS:
3697     case X86ISD::UNPCKLPD:
3698       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3699       break;
3700     case X86ISD::MOVHLPS:
3701       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3702       break;
3703     case X86ISD::MOVLHPS:
3704       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3705       break;
3706     case X86ISD::PSHUFD:
3707       ImmN = N->getOperand(N->getNumOperands()-1);
3708       DecodePSHUFMask(NumElems,
3709                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3710                       ShuffleMask);
3711       break;
3712     case X86ISD::PSHUFHW:
3713       ImmN = N->getOperand(N->getNumOperands()-1);
3714       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3715                         ShuffleMask);
3716       break;
3717     case X86ISD::PSHUFLW:
3718       ImmN = N->getOperand(N->getNumOperands()-1);
3719       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3720                         ShuffleMask);
3721       break;
3722     case X86ISD::MOVSS:
3723     case X86ISD::MOVSD: {
3724       // The index 0 always comes from the first element of the second source,
3725       // this is why MOVSS and MOVSD are used in the first place. The other
3726       // elements come from the other positions of the first source vector.
3727       unsigned OpNum = (Index == 0) ? 1 : 0;
3728       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3729                                  Depth+1);
3730     }
3731     default:
3732       assert("not implemented for target shuffle node");
3733       return SDValue();
3734     }
3735
3736     Index = ShuffleMask[Index];
3737     if (Index < 0)
3738       return DAG.getUNDEF(VT.getVectorElementType());
3739
3740     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3741     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3742                                Depth+1);
3743   }
3744
3745   // Actual nodes that may contain scalar elements
3746   if (Opcode == ISD::BITCAST) {
3747     V = V.getOperand(0);
3748     EVT SrcVT = V.getValueType();
3749     unsigned NumElems = VT.getVectorNumElements();
3750
3751     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3752       return SDValue();
3753   }
3754
3755   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3756     return (Index == 0) ? V.getOperand(0)
3757                           : DAG.getUNDEF(VT.getVectorElementType());
3758
3759   if (V.getOpcode() == ISD::BUILD_VECTOR)
3760     return V.getOperand(Index);
3761
3762   return SDValue();
3763 }
3764
3765 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3766 /// shuffle operation which come from a consecutively from a zero. The
3767 /// search can start in two diferent directions, from left or right.
3768 static
3769 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3770                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3771   int i = 0;
3772
3773   while (i < NumElems) {
3774     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3775     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3776     if (!(Elt.getNode() &&
3777          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3778       break;
3779     ++i;
3780   }
3781
3782   return i;
3783 }
3784
3785 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3786 /// MaskE correspond consecutively to elements from one of the vector operands,
3787 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3788 static
3789 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3790                               int OpIdx, int NumElems, unsigned &OpNum) {
3791   bool SeenV1 = false;
3792   bool SeenV2 = false;
3793
3794   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3795     int Idx = SVOp->getMaskElt(i);
3796     // Ignore undef indicies
3797     if (Idx < 0)
3798       continue;
3799
3800     if (Idx < NumElems)
3801       SeenV1 = true;
3802     else
3803       SeenV2 = true;
3804
3805     // Only accept consecutive elements from the same vector
3806     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3807       return false;
3808   }
3809
3810   OpNum = SeenV1 ? 0 : 1;
3811   return true;
3812 }
3813
3814 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3815 /// logical left shift of a vector.
3816 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3817                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3818   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3819   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3820               false /* check zeros from right */, DAG);
3821   unsigned OpSrc;
3822
3823   if (!NumZeros)
3824     return false;
3825
3826   // Considering the elements in the mask that are not consecutive zeros,
3827   // check if they consecutively come from only one of the source vectors.
3828   //
3829   //               V1 = {X, A, B, C}     0
3830   //                         \  \  \    /
3831   //   vector_shuffle V1, V2 <1, 2, 3, X>
3832   //
3833   if (!isShuffleMaskConsecutive(SVOp,
3834             0,                   // Mask Start Index
3835             NumElems-NumZeros-1, // Mask End Index
3836             NumZeros,            // Where to start looking in the src vector
3837             NumElems,            // Number of elements in vector
3838             OpSrc))              // Which source operand ?
3839     return false;
3840
3841   isLeft = false;
3842   ShAmt = NumZeros;
3843   ShVal = SVOp->getOperand(OpSrc);
3844   return true;
3845 }
3846
3847 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3848 /// logical left shift of a vector.
3849 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3850                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3851   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3852   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3853               true /* check zeros from left */, DAG);
3854   unsigned OpSrc;
3855
3856   if (!NumZeros)
3857     return false;
3858
3859   // Considering the elements in the mask that are not consecutive zeros,
3860   // check if they consecutively come from only one of the source vectors.
3861   //
3862   //                           0    { A, B, X, X } = V2
3863   //                          / \    /  /
3864   //   vector_shuffle V1, V2 <X, X, 4, 5>
3865   //
3866   if (!isShuffleMaskConsecutive(SVOp,
3867             NumZeros,     // Mask Start Index
3868             NumElems-1,   // Mask End Index
3869             0,            // Where to start looking in the src vector
3870             NumElems,     // Number of elements in vector
3871             OpSrc))       // Which source operand ?
3872     return false;
3873
3874   isLeft = true;
3875   ShAmt = NumZeros;
3876   ShVal = SVOp->getOperand(OpSrc);
3877   return true;
3878 }
3879
3880 /// isVectorShift - Returns true if the shuffle can be implemented as a
3881 /// logical left or right shift of a vector.
3882 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3883                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3884   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3885       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3886     return true;
3887
3888   return false;
3889 }
3890
3891 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3892 ///
3893 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3894                                        unsigned NumNonZero, unsigned NumZero,
3895                                        SelectionDAG &DAG,
3896                                        const TargetLowering &TLI) {
3897   if (NumNonZero > 8)
3898     return SDValue();
3899
3900   DebugLoc dl = Op.getDebugLoc();
3901   SDValue V(0, 0);
3902   bool First = true;
3903   for (unsigned i = 0; i < 16; ++i) {
3904     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3905     if (ThisIsNonZero && First) {
3906       if (NumZero)
3907         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3908       else
3909         V = DAG.getUNDEF(MVT::v8i16);
3910       First = false;
3911     }
3912
3913     if ((i & 1) != 0) {
3914       SDValue ThisElt(0, 0), LastElt(0, 0);
3915       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3916       if (LastIsNonZero) {
3917         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3918                               MVT::i16, Op.getOperand(i-1));
3919       }
3920       if (ThisIsNonZero) {
3921         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3922         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3923                               ThisElt, DAG.getConstant(8, MVT::i8));
3924         if (LastIsNonZero)
3925           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3926       } else
3927         ThisElt = LastElt;
3928
3929       if (ThisElt.getNode())
3930         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3931                         DAG.getIntPtrConstant(i/2));
3932     }
3933   }
3934
3935   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3936 }
3937
3938 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3939 ///
3940 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3941                                      unsigned NumNonZero, unsigned NumZero,
3942                                      SelectionDAG &DAG,
3943                                      const TargetLowering &TLI) {
3944   if (NumNonZero > 4)
3945     return SDValue();
3946
3947   DebugLoc dl = Op.getDebugLoc();
3948   SDValue V(0, 0);
3949   bool First = true;
3950   for (unsigned i = 0; i < 8; ++i) {
3951     bool isNonZero = (NonZeros & (1 << i)) != 0;
3952     if (isNonZero) {
3953       if (First) {
3954         if (NumZero)
3955           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3956         else
3957           V = DAG.getUNDEF(MVT::v8i16);
3958         First = false;
3959       }
3960       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3961                       MVT::v8i16, V, Op.getOperand(i),
3962                       DAG.getIntPtrConstant(i));
3963     }
3964   }
3965
3966   return V;
3967 }
3968
3969 /// getVShift - Return a vector logical shift node.
3970 ///
3971 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3972                          unsigned NumBits, SelectionDAG &DAG,
3973                          const TargetLowering &TLI, DebugLoc dl) {
3974   EVT ShVT = MVT::v2i64;
3975   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3976   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3977   return DAG.getNode(ISD::BITCAST, dl, VT,
3978                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3979                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3980 }
3981
3982 SDValue
3983 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3984                                           SelectionDAG &DAG) const {
3985
3986   // Check if the scalar load can be widened into a vector load. And if
3987   // the address is "base + cst" see if the cst can be "absorbed" into
3988   // the shuffle mask.
3989   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3990     SDValue Ptr = LD->getBasePtr();
3991     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3992       return SDValue();
3993     EVT PVT = LD->getValueType(0);
3994     if (PVT != MVT::i32 && PVT != MVT::f32)
3995       return SDValue();
3996
3997     int FI = -1;
3998     int64_t Offset = 0;
3999     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4000       FI = FINode->getIndex();
4001       Offset = 0;
4002     } else if (Ptr.getOpcode() == ISD::ADD &&
4003                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4004                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4005       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4006       Offset = Ptr.getConstantOperandVal(1);
4007       Ptr = Ptr.getOperand(0);
4008     } else {
4009       return SDValue();
4010     }
4011
4012     SDValue Chain = LD->getChain();
4013     // Make sure the stack object alignment is at least 16.
4014     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4015     if (DAG.InferPtrAlignment(Ptr) < 16) {
4016       if (MFI->isFixedObjectIndex(FI)) {
4017         // Can't change the alignment. FIXME: It's possible to compute
4018         // the exact stack offset and reference FI + adjust offset instead.
4019         // If someone *really* cares about this. That's the way to implement it.
4020         return SDValue();
4021       } else {
4022         MFI->setObjectAlignment(FI, 16);
4023       }
4024     }
4025
4026     // (Offset % 16) must be multiple of 4. Then address is then
4027     // Ptr + (Offset & ~15).
4028     if (Offset < 0)
4029       return SDValue();
4030     if ((Offset % 16) & 3)
4031       return SDValue();
4032     int64_t StartOffset = Offset & ~15;
4033     if (StartOffset)
4034       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4035                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4036
4037     int EltNo = (Offset - StartOffset) >> 2;
4038     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4039     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4040     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4041                              LD->getPointerInfo().getWithOffset(StartOffset),
4042                              false, false, 0);
4043     // Canonicalize it to a v4i32 shuffle.
4044     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4045     return DAG.getNode(ISD::BITCAST, dl, VT,
4046                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4047                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4048   }
4049
4050   return SDValue();
4051 }
4052
4053 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4054 /// vector of type 'VT', see if the elements can be replaced by a single large
4055 /// load which has the same value as a build_vector whose operands are 'elts'.
4056 ///
4057 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4058 ///
4059 /// FIXME: we'd also like to handle the case where the last elements are zero
4060 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4061 /// There's even a handy isZeroNode for that purpose.
4062 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4063                                         DebugLoc &DL, SelectionDAG &DAG) {
4064   EVT EltVT = VT.getVectorElementType();
4065   unsigned NumElems = Elts.size();
4066
4067   LoadSDNode *LDBase = NULL;
4068   unsigned LastLoadedElt = -1U;
4069
4070   // For each element in the initializer, see if we've found a load or an undef.
4071   // If we don't find an initial load element, or later load elements are
4072   // non-consecutive, bail out.
4073   for (unsigned i = 0; i < NumElems; ++i) {
4074     SDValue Elt = Elts[i];
4075
4076     if (!Elt.getNode() ||
4077         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4078       return SDValue();
4079     if (!LDBase) {
4080       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4081         return SDValue();
4082       LDBase = cast<LoadSDNode>(Elt.getNode());
4083       LastLoadedElt = i;
4084       continue;
4085     }
4086     if (Elt.getOpcode() == ISD::UNDEF)
4087       continue;
4088
4089     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4090     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4091       return SDValue();
4092     LastLoadedElt = i;
4093   }
4094
4095   // If we have found an entire vector of loads and undefs, then return a large
4096   // load of the entire vector width starting at the base pointer.  If we found
4097   // consecutive loads for the low half, generate a vzext_load node.
4098   if (LastLoadedElt == NumElems - 1) {
4099     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4100       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4101                          LDBase->getPointerInfo(),
4102                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4103     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4104                        LDBase->getPointerInfo(),
4105                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4106                        LDBase->getAlignment());
4107   } else if (NumElems == 4 && LastLoadedElt == 1) {
4108     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4109     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4110     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4111                                               Ops, 2, MVT::i32,
4112                                               LDBase->getMemOperand());
4113     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4114   }
4115   return SDValue();
4116 }
4117
4118 SDValue
4119 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4120   DebugLoc dl = Op.getDebugLoc();
4121   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4122   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4123   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4124   // is present, so AllOnes is ignored.
4125   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4126       (Op.getValueType().getSizeInBits() != 256 &&
4127        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4128     // Canonicalize this to <4 x i32> (SSE) to
4129     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4130     // eliminated on x86-32 hosts.
4131     if (Op.getValueType() == MVT::v4i32)
4132       return Op;
4133
4134     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4135       return getOnesVector(Op.getValueType(), DAG, dl);
4136     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4137   }
4138
4139   EVT VT = Op.getValueType();
4140   EVT ExtVT = VT.getVectorElementType();
4141   unsigned EVTBits = ExtVT.getSizeInBits();
4142
4143   unsigned NumElems = Op.getNumOperands();
4144   unsigned NumZero  = 0;
4145   unsigned NumNonZero = 0;
4146   unsigned NonZeros = 0;
4147   bool IsAllConstants = true;
4148   SmallSet<SDValue, 8> Values;
4149   for (unsigned i = 0; i < NumElems; ++i) {
4150     SDValue Elt = Op.getOperand(i);
4151     if (Elt.getOpcode() == ISD::UNDEF)
4152       continue;
4153     Values.insert(Elt);
4154     if (Elt.getOpcode() != ISD::Constant &&
4155         Elt.getOpcode() != ISD::ConstantFP)
4156       IsAllConstants = false;
4157     if (X86::isZeroNode(Elt))
4158       NumZero++;
4159     else {
4160       NonZeros |= (1 << i);
4161       NumNonZero++;
4162     }
4163   }
4164
4165   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4166   if (NumNonZero == 0)
4167     return DAG.getUNDEF(VT);
4168
4169   // Special case for single non-zero, non-undef, element.
4170   if (NumNonZero == 1) {
4171     unsigned Idx = CountTrailingZeros_32(NonZeros);
4172     SDValue Item = Op.getOperand(Idx);
4173
4174     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4175     // the value are obviously zero, truncate the value to i32 and do the
4176     // insertion that way.  Only do this if the value is non-constant or if the
4177     // value is a constant being inserted into element 0.  It is cheaper to do
4178     // a constant pool load than it is to do a movd + shuffle.
4179     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4180         (!IsAllConstants || Idx == 0)) {
4181       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4182         // Handle SSE only.
4183         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4184         EVT VecVT = MVT::v4i32;
4185         unsigned VecElts = 4;
4186
4187         // Truncate the value (which may itself be a constant) to i32, and
4188         // convert it to a vector with movd (S2V+shuffle to zero extend).
4189         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4190         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4191         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4192                                            Subtarget->hasSSE2(), DAG);
4193
4194         // Now we have our 32-bit value zero extended in the low element of
4195         // a vector.  If Idx != 0, swizzle it into place.
4196         if (Idx != 0) {
4197           SmallVector<int, 4> Mask;
4198           Mask.push_back(Idx);
4199           for (unsigned i = 1; i != VecElts; ++i)
4200             Mask.push_back(i);
4201           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4202                                       DAG.getUNDEF(Item.getValueType()),
4203                                       &Mask[0]);
4204         }
4205         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4206       }
4207     }
4208
4209     // If we have a constant or non-constant insertion into the low element of
4210     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4211     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4212     // depending on what the source datatype is.
4213     if (Idx == 0) {
4214       if (NumZero == 0) {
4215         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4216       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4217           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4218         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4219         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4220         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4221                                            DAG);
4222       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4223         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4224         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4225         EVT MiddleVT = MVT::v4i32;
4226         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4227         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4228                                            Subtarget->hasSSE2(), DAG);
4229         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4230       }
4231     }
4232
4233     // Is it a vector logical left shift?
4234     if (NumElems == 2 && Idx == 1 &&
4235         X86::isZeroNode(Op.getOperand(0)) &&
4236         !X86::isZeroNode(Op.getOperand(1))) {
4237       unsigned NumBits = VT.getSizeInBits();
4238       return getVShift(true, VT,
4239                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4240                                    VT, Op.getOperand(1)),
4241                        NumBits/2, DAG, *this, dl);
4242     }
4243
4244     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4245       return SDValue();
4246
4247     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4248     // is a non-constant being inserted into an element other than the low one,
4249     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4250     // movd/movss) to move this into the low element, then shuffle it into
4251     // place.
4252     if (EVTBits == 32) {
4253       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4254
4255       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4256       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4257                                          Subtarget->hasSSE2(), DAG);
4258       SmallVector<int, 8> MaskVec;
4259       for (unsigned i = 0; i < NumElems; i++)
4260         MaskVec.push_back(i == Idx ? 0 : 1);
4261       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4262     }
4263   }
4264
4265   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4266   if (Values.size() == 1) {
4267     if (EVTBits == 32) {
4268       // Instead of a shuffle like this:
4269       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4270       // Check if it's possible to issue this instead.
4271       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4272       unsigned Idx = CountTrailingZeros_32(NonZeros);
4273       SDValue Item = Op.getOperand(Idx);
4274       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4275         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4276     }
4277     return SDValue();
4278   }
4279
4280   // A vector full of immediates; various special cases are already
4281   // handled, so this is best done with a single constant-pool load.
4282   if (IsAllConstants)
4283     return SDValue();
4284
4285   // Let legalizer expand 2-wide build_vectors.
4286   if (EVTBits == 64) {
4287     if (NumNonZero == 1) {
4288       // One half is zero or undef.
4289       unsigned Idx = CountTrailingZeros_32(NonZeros);
4290       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4291                                  Op.getOperand(Idx));
4292       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4293                                          Subtarget->hasSSE2(), DAG);
4294     }
4295     return SDValue();
4296   }
4297
4298   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4299   if (EVTBits == 8 && NumElems == 16) {
4300     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4301                                         *this);
4302     if (V.getNode()) return V;
4303   }
4304
4305   if (EVTBits == 16 && NumElems == 8) {
4306     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4307                                       *this);
4308     if (V.getNode()) return V;
4309   }
4310
4311   // If element VT is == 32 bits, turn it into a number of shuffles.
4312   SmallVector<SDValue, 8> V;
4313   V.resize(NumElems);
4314   if (NumElems == 4 && NumZero > 0) {
4315     for (unsigned i = 0; i < 4; ++i) {
4316       bool isZero = !(NonZeros & (1 << i));
4317       if (isZero)
4318         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4319       else
4320         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4321     }
4322
4323     for (unsigned i = 0; i < 2; ++i) {
4324       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4325         default: break;
4326         case 0:
4327           V[i] = V[i*2];  // Must be a zero vector.
4328           break;
4329         case 1:
4330           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4331           break;
4332         case 2:
4333           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4334           break;
4335         case 3:
4336           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4337           break;
4338       }
4339     }
4340
4341     SmallVector<int, 8> MaskVec;
4342     bool Reverse = (NonZeros & 0x3) == 2;
4343     for (unsigned i = 0; i < 2; ++i)
4344       MaskVec.push_back(Reverse ? 1-i : i);
4345     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4346     for (unsigned i = 0; i < 2; ++i)
4347       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4348     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4349   }
4350
4351   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4352     // Check for a build vector of consecutive loads.
4353     for (unsigned i = 0; i < NumElems; ++i)
4354       V[i] = Op.getOperand(i);
4355
4356     // Check for elements which are consecutive loads.
4357     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4358     if (LD.getNode())
4359       return LD;
4360
4361     // For SSE 4.1, use insertps to put the high elements into the low element.
4362     if (getSubtarget()->hasSSE41()) {
4363       SDValue Result;
4364       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4365         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4366       else
4367         Result = DAG.getUNDEF(VT);
4368
4369       for (unsigned i = 1; i < NumElems; ++i) {
4370         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4371         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4372                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4373       }
4374       return Result;
4375     }
4376
4377     // Otherwise, expand into a number of unpckl*, start by extending each of
4378     // our (non-undef) elements to the full vector width with the element in the
4379     // bottom slot of the vector (which generates no code for SSE).
4380     for (unsigned i = 0; i < NumElems; ++i) {
4381       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4382         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4383       else
4384         V[i] = DAG.getUNDEF(VT);
4385     }
4386
4387     // Next, we iteratively mix elements, e.g. for v4f32:
4388     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4389     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4390     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4391     unsigned EltStride = NumElems >> 1;
4392     while (EltStride != 0) {
4393       for (unsigned i = 0; i < EltStride; ++i) {
4394         // If V[i+EltStride] is undef and this is the first round of mixing,
4395         // then it is safe to just drop this shuffle: V[i] is already in the
4396         // right place, the one element (since it's the first round) being
4397         // inserted as undef can be dropped.  This isn't safe for successive
4398         // rounds because they will permute elements within both vectors.
4399         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4400             EltStride == NumElems/2)
4401           continue;
4402
4403         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4404       }
4405       EltStride >>= 1;
4406     }
4407     return V[0];
4408   }
4409   return SDValue();
4410 }
4411
4412 SDValue
4413 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4414   // We support concatenate two MMX registers and place them in a MMX
4415   // register.  This is better than doing a stack convert.
4416   DebugLoc dl = Op.getDebugLoc();
4417   EVT ResVT = Op.getValueType();
4418   assert(Op.getNumOperands() == 2);
4419   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4420          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4421   int Mask[2];
4422   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4423   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4424   InVec = Op.getOperand(1);
4425   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4426     unsigned NumElts = ResVT.getVectorNumElements();
4427     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4428     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4429                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4430   } else {
4431     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4432     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4433     Mask[0] = 0; Mask[1] = 2;
4434     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4435   }
4436   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4437 }
4438
4439 // v8i16 shuffles - Prefer shuffles in the following order:
4440 // 1. [all]   pshuflw, pshufhw, optional move
4441 // 2. [ssse3] 1 x pshufb
4442 // 3. [ssse3] 2 x pshufb + 1 x por
4443 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4444 SDValue
4445 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4446                                             SelectionDAG &DAG) const {
4447   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4448   SDValue V1 = SVOp->getOperand(0);
4449   SDValue V2 = SVOp->getOperand(1);
4450   DebugLoc dl = SVOp->getDebugLoc();
4451   SmallVector<int, 8> MaskVals;
4452
4453   // Determine if more than 1 of the words in each of the low and high quadwords
4454   // of the result come from the same quadword of one of the two inputs.  Undef
4455   // mask values count as coming from any quadword, for better codegen.
4456   SmallVector<unsigned, 4> LoQuad(4);
4457   SmallVector<unsigned, 4> HiQuad(4);
4458   BitVector InputQuads(4);
4459   for (unsigned i = 0; i < 8; ++i) {
4460     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4461     int EltIdx = SVOp->getMaskElt(i);
4462     MaskVals.push_back(EltIdx);
4463     if (EltIdx < 0) {
4464       ++Quad[0];
4465       ++Quad[1];
4466       ++Quad[2];
4467       ++Quad[3];
4468       continue;
4469     }
4470     ++Quad[EltIdx / 4];
4471     InputQuads.set(EltIdx / 4);
4472   }
4473
4474   int BestLoQuad = -1;
4475   unsigned MaxQuad = 1;
4476   for (unsigned i = 0; i < 4; ++i) {
4477     if (LoQuad[i] > MaxQuad) {
4478       BestLoQuad = i;
4479       MaxQuad = LoQuad[i];
4480     }
4481   }
4482
4483   int BestHiQuad = -1;
4484   MaxQuad = 1;
4485   for (unsigned i = 0; i < 4; ++i) {
4486     if (HiQuad[i] > MaxQuad) {
4487       BestHiQuad = i;
4488       MaxQuad = HiQuad[i];
4489     }
4490   }
4491
4492   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4493   // of the two input vectors, shuffle them into one input vector so only a
4494   // single pshufb instruction is necessary. If There are more than 2 input
4495   // quads, disable the next transformation since it does not help SSSE3.
4496   bool V1Used = InputQuads[0] || InputQuads[1];
4497   bool V2Used = InputQuads[2] || InputQuads[3];
4498   if (Subtarget->hasSSSE3()) {
4499     if (InputQuads.count() == 2 && V1Used && V2Used) {
4500       BestLoQuad = InputQuads.find_first();
4501       BestHiQuad = InputQuads.find_next(BestLoQuad);
4502     }
4503     if (InputQuads.count() > 2) {
4504       BestLoQuad = -1;
4505       BestHiQuad = -1;
4506     }
4507   }
4508
4509   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4510   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4511   // words from all 4 input quadwords.
4512   SDValue NewV;
4513   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4514     SmallVector<int, 8> MaskV;
4515     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4516     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4517     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4518                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4519                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4520     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4521
4522     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4523     // source words for the shuffle, to aid later transformations.
4524     bool AllWordsInNewV = true;
4525     bool InOrder[2] = { true, true };
4526     for (unsigned i = 0; i != 8; ++i) {
4527       int idx = MaskVals[i];
4528       if (idx != (int)i)
4529         InOrder[i/4] = false;
4530       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4531         continue;
4532       AllWordsInNewV = false;
4533       break;
4534     }
4535
4536     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4537     if (AllWordsInNewV) {
4538       for (int i = 0; i != 8; ++i) {
4539         int idx = MaskVals[i];
4540         if (idx < 0)
4541           continue;
4542         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4543         if ((idx != i) && idx < 4)
4544           pshufhw = false;
4545         if ((idx != i) && idx > 3)
4546           pshuflw = false;
4547       }
4548       V1 = NewV;
4549       V2Used = false;
4550       BestLoQuad = 0;
4551       BestHiQuad = 1;
4552     }
4553
4554     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4555     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4556     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4557       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4558       unsigned TargetMask = 0;
4559       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4560                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4561       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4562                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4563       V1 = NewV.getOperand(0);
4564       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4565     }
4566   }
4567
4568   // If we have SSSE3, and all words of the result are from 1 input vector,
4569   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4570   // is present, fall back to case 4.
4571   if (Subtarget->hasSSSE3()) {
4572     SmallVector<SDValue,16> pshufbMask;
4573
4574     // If we have elements from both input vectors, set the high bit of the
4575     // shuffle mask element to zero out elements that come from V2 in the V1
4576     // mask, and elements that come from V1 in the V2 mask, so that the two
4577     // results can be OR'd together.
4578     bool TwoInputs = V1Used && V2Used;
4579     for (unsigned i = 0; i != 8; ++i) {
4580       int EltIdx = MaskVals[i] * 2;
4581       if (TwoInputs && (EltIdx >= 16)) {
4582         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4583         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4584         continue;
4585       }
4586       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4587       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4588     }
4589     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4590     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4591                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4592                                  MVT::v16i8, &pshufbMask[0], 16));
4593     if (!TwoInputs)
4594       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4595
4596     // Calculate the shuffle mask for the second input, shuffle it, and
4597     // OR it with the first shuffled input.
4598     pshufbMask.clear();
4599     for (unsigned i = 0; i != 8; ++i) {
4600       int EltIdx = MaskVals[i] * 2;
4601       if (EltIdx < 16) {
4602         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4603         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4604         continue;
4605       }
4606       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4607       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4608     }
4609     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4610     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4611                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4612                                  MVT::v16i8, &pshufbMask[0], 16));
4613     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4614     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4615   }
4616
4617   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4618   // and update MaskVals with new element order.
4619   BitVector InOrder(8);
4620   if (BestLoQuad >= 0) {
4621     SmallVector<int, 8> MaskV;
4622     for (int i = 0; i != 4; ++i) {
4623       int idx = MaskVals[i];
4624       if (idx < 0) {
4625         MaskV.push_back(-1);
4626         InOrder.set(i);
4627       } else if ((idx / 4) == BestLoQuad) {
4628         MaskV.push_back(idx & 3);
4629         InOrder.set(i);
4630       } else {
4631         MaskV.push_back(-1);
4632       }
4633     }
4634     for (unsigned i = 4; i != 8; ++i)
4635       MaskV.push_back(i);
4636     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4637                                 &MaskV[0]);
4638
4639     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4640       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4641                                NewV.getOperand(0),
4642                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4643                                DAG);
4644   }
4645
4646   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4647   // and update MaskVals with the new element order.
4648   if (BestHiQuad >= 0) {
4649     SmallVector<int, 8> MaskV;
4650     for (unsigned i = 0; i != 4; ++i)
4651       MaskV.push_back(i);
4652     for (unsigned i = 4; i != 8; ++i) {
4653       int idx = MaskVals[i];
4654       if (idx < 0) {
4655         MaskV.push_back(-1);
4656         InOrder.set(i);
4657       } else if ((idx / 4) == BestHiQuad) {
4658         MaskV.push_back((idx & 3) + 4);
4659         InOrder.set(i);
4660       } else {
4661         MaskV.push_back(-1);
4662       }
4663     }
4664     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4665                                 &MaskV[0]);
4666
4667     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4668       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4669                               NewV.getOperand(0),
4670                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4671                               DAG);
4672   }
4673
4674   // In case BestHi & BestLo were both -1, which means each quadword has a word
4675   // from each of the four input quadwords, calculate the InOrder bitvector now
4676   // before falling through to the insert/extract cleanup.
4677   if (BestLoQuad == -1 && BestHiQuad == -1) {
4678     NewV = V1;
4679     for (int i = 0; i != 8; ++i)
4680       if (MaskVals[i] < 0 || MaskVals[i] == i)
4681         InOrder.set(i);
4682   }
4683
4684   // The other elements are put in the right place using pextrw and pinsrw.
4685   for (unsigned i = 0; i != 8; ++i) {
4686     if (InOrder[i])
4687       continue;
4688     int EltIdx = MaskVals[i];
4689     if (EltIdx < 0)
4690       continue;
4691     SDValue ExtOp = (EltIdx < 8)
4692     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4693                   DAG.getIntPtrConstant(EltIdx))
4694     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4695                   DAG.getIntPtrConstant(EltIdx - 8));
4696     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4697                        DAG.getIntPtrConstant(i));
4698   }
4699   return NewV;
4700 }
4701
4702 // v16i8 shuffles - Prefer shuffles in the following order:
4703 // 1. [ssse3] 1 x pshufb
4704 // 2. [ssse3] 2 x pshufb + 1 x por
4705 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4706 static
4707 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4708                                  SelectionDAG &DAG,
4709                                  const X86TargetLowering &TLI) {
4710   SDValue V1 = SVOp->getOperand(0);
4711   SDValue V2 = SVOp->getOperand(1);
4712   DebugLoc dl = SVOp->getDebugLoc();
4713   SmallVector<int, 16> MaskVals;
4714   SVOp->getMask(MaskVals);
4715
4716   // If we have SSSE3, case 1 is generated when all result bytes come from
4717   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4718   // present, fall back to case 3.
4719   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4720   bool V1Only = true;
4721   bool V2Only = true;
4722   for (unsigned i = 0; i < 16; ++i) {
4723     int EltIdx = MaskVals[i];
4724     if (EltIdx < 0)
4725       continue;
4726     if (EltIdx < 16)
4727       V2Only = false;
4728     else
4729       V1Only = false;
4730   }
4731
4732   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4733   if (TLI.getSubtarget()->hasSSSE3()) {
4734     SmallVector<SDValue,16> pshufbMask;
4735
4736     // If all result elements are from one input vector, then only translate
4737     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4738     //
4739     // Otherwise, we have elements from both input vectors, and must zero out
4740     // elements that come from V2 in the first mask, and V1 in the second mask
4741     // so that we can OR them together.
4742     bool TwoInputs = !(V1Only || V2Only);
4743     for (unsigned i = 0; i != 16; ++i) {
4744       int EltIdx = MaskVals[i];
4745       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4746         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4747         continue;
4748       }
4749       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4750     }
4751     // If all the elements are from V2, assign it to V1 and return after
4752     // building the first pshufb.
4753     if (V2Only)
4754       V1 = V2;
4755     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4756                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4757                                  MVT::v16i8, &pshufbMask[0], 16));
4758     if (!TwoInputs)
4759       return V1;
4760
4761     // Calculate the shuffle mask for the second input, shuffle it, and
4762     // OR it with the first shuffled input.
4763     pshufbMask.clear();
4764     for (unsigned i = 0; i != 16; ++i) {
4765       int EltIdx = MaskVals[i];
4766       if (EltIdx < 16) {
4767         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4768         continue;
4769       }
4770       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4771     }
4772     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4773                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4774                                  MVT::v16i8, &pshufbMask[0], 16));
4775     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4776   }
4777
4778   // No SSSE3 - Calculate in place words and then fix all out of place words
4779   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4780   // the 16 different words that comprise the two doublequadword input vectors.
4781   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4782   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4783   SDValue NewV = V2Only ? V2 : V1;
4784   for (int i = 0; i != 8; ++i) {
4785     int Elt0 = MaskVals[i*2];
4786     int Elt1 = MaskVals[i*2+1];
4787
4788     // This word of the result is all undef, skip it.
4789     if (Elt0 < 0 && Elt1 < 0)
4790       continue;
4791
4792     // This word of the result is already in the correct place, skip it.
4793     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4794       continue;
4795     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4796       continue;
4797
4798     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4799     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4800     SDValue InsElt;
4801
4802     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4803     // using a single extract together, load it and store it.
4804     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4805       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4806                            DAG.getIntPtrConstant(Elt1 / 2));
4807       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4808                         DAG.getIntPtrConstant(i));
4809       continue;
4810     }
4811
4812     // If Elt1 is defined, extract it from the appropriate source.  If the
4813     // source byte is not also odd, shift the extracted word left 8 bits
4814     // otherwise clear the bottom 8 bits if we need to do an or.
4815     if (Elt1 >= 0) {
4816       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4817                            DAG.getIntPtrConstant(Elt1 / 2));
4818       if ((Elt1 & 1) == 0)
4819         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4820                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4821       else if (Elt0 >= 0)
4822         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4823                              DAG.getConstant(0xFF00, MVT::i16));
4824     }
4825     // If Elt0 is defined, extract it from the appropriate source.  If the
4826     // source byte is not also even, shift the extracted word right 8 bits. If
4827     // Elt1 was also defined, OR the extracted values together before
4828     // inserting them in the result.
4829     if (Elt0 >= 0) {
4830       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4831                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4832       if ((Elt0 & 1) != 0)
4833         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4834                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4835       else if (Elt1 >= 0)
4836         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4837                              DAG.getConstant(0x00FF, MVT::i16));
4838       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4839                          : InsElt0;
4840     }
4841     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4842                        DAG.getIntPtrConstant(i));
4843   }
4844   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4845 }
4846
4847 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4848 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4849 /// done when every pair / quad of shuffle mask elements point to elements in
4850 /// the right sequence. e.g.
4851 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4852 static
4853 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4854                                  SelectionDAG &DAG, DebugLoc dl) {
4855   EVT VT = SVOp->getValueType(0);
4856   SDValue V1 = SVOp->getOperand(0);
4857   SDValue V2 = SVOp->getOperand(1);
4858   unsigned NumElems = VT.getVectorNumElements();
4859   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4860   EVT NewVT;
4861   switch (VT.getSimpleVT().SimpleTy) {
4862   default: assert(false && "Unexpected!");
4863   case MVT::v4f32: NewVT = MVT::v2f64; break;
4864   case MVT::v4i32: NewVT = MVT::v2i64; break;
4865   case MVT::v8i16: NewVT = MVT::v4i32; break;
4866   case MVT::v16i8: NewVT = MVT::v4i32; break;
4867   }
4868
4869   int Scale = NumElems / NewWidth;
4870   SmallVector<int, 8> MaskVec;
4871   for (unsigned i = 0; i < NumElems; i += Scale) {
4872     int StartIdx = -1;
4873     for (int j = 0; j < Scale; ++j) {
4874       int EltIdx = SVOp->getMaskElt(i+j);
4875       if (EltIdx < 0)
4876         continue;
4877       if (StartIdx == -1)
4878         StartIdx = EltIdx - (EltIdx % Scale);
4879       if (EltIdx != StartIdx + j)
4880         return SDValue();
4881     }
4882     if (StartIdx == -1)
4883       MaskVec.push_back(-1);
4884     else
4885       MaskVec.push_back(StartIdx / Scale);
4886   }
4887
4888   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4889   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4890   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4891 }
4892
4893 /// getVZextMovL - Return a zero-extending vector move low node.
4894 ///
4895 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4896                             SDValue SrcOp, SelectionDAG &DAG,
4897                             const X86Subtarget *Subtarget, DebugLoc dl) {
4898   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4899     LoadSDNode *LD = NULL;
4900     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4901       LD = dyn_cast<LoadSDNode>(SrcOp);
4902     if (!LD) {
4903       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4904       // instead.
4905       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4906       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4907           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4908           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4909           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4910         // PR2108
4911         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4912         return DAG.getNode(ISD::BITCAST, dl, VT,
4913                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4914                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4915                                                    OpVT,
4916                                                    SrcOp.getOperand(0)
4917                                                           .getOperand(0))));
4918       }
4919     }
4920   }
4921
4922   return DAG.getNode(ISD::BITCAST, dl, VT,
4923                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4924                                  DAG.getNode(ISD::BITCAST, dl,
4925                                              OpVT, SrcOp)));
4926 }
4927
4928 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4929 /// shuffles.
4930 static SDValue
4931 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4932   SDValue V1 = SVOp->getOperand(0);
4933   SDValue V2 = SVOp->getOperand(1);
4934   DebugLoc dl = SVOp->getDebugLoc();
4935   EVT VT = SVOp->getValueType(0);
4936
4937   SmallVector<std::pair<int, int>, 8> Locs;
4938   Locs.resize(4);
4939   SmallVector<int, 8> Mask1(4U, -1);
4940   SmallVector<int, 8> PermMask;
4941   SVOp->getMask(PermMask);
4942
4943   unsigned NumHi = 0;
4944   unsigned NumLo = 0;
4945   for (unsigned i = 0; i != 4; ++i) {
4946     int Idx = PermMask[i];
4947     if (Idx < 0) {
4948       Locs[i] = std::make_pair(-1, -1);
4949     } else {
4950       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4951       if (Idx < 4) {
4952         Locs[i] = std::make_pair(0, NumLo);
4953         Mask1[NumLo] = Idx;
4954         NumLo++;
4955       } else {
4956         Locs[i] = std::make_pair(1, NumHi);
4957         if (2+NumHi < 4)
4958           Mask1[2+NumHi] = Idx;
4959         NumHi++;
4960       }
4961     }
4962   }
4963
4964   if (NumLo <= 2 && NumHi <= 2) {
4965     // If no more than two elements come from either vector. This can be
4966     // implemented with two shuffles. First shuffle gather the elements.
4967     // The second shuffle, which takes the first shuffle as both of its
4968     // vector operands, put the elements into the right order.
4969     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4970
4971     SmallVector<int, 8> Mask2(4U, -1);
4972
4973     for (unsigned i = 0; i != 4; ++i) {
4974       if (Locs[i].first == -1)
4975         continue;
4976       else {
4977         unsigned Idx = (i < 2) ? 0 : 4;
4978         Idx += Locs[i].first * 2 + Locs[i].second;
4979         Mask2[i] = Idx;
4980       }
4981     }
4982
4983     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4984   } else if (NumLo == 3 || NumHi == 3) {
4985     // Otherwise, we must have three elements from one vector, call it X, and
4986     // one element from the other, call it Y.  First, use a shufps to build an
4987     // intermediate vector with the one element from Y and the element from X
4988     // that will be in the same half in the final destination (the indexes don't
4989     // matter). Then, use a shufps to build the final vector, taking the half
4990     // containing the element from Y from the intermediate, and the other half
4991     // from X.
4992     if (NumHi == 3) {
4993       // Normalize it so the 3 elements come from V1.
4994       CommuteVectorShuffleMask(PermMask, VT);
4995       std::swap(V1, V2);
4996     }
4997
4998     // Find the element from V2.
4999     unsigned HiIndex;
5000     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5001       int Val = PermMask[HiIndex];
5002       if (Val < 0)
5003         continue;
5004       if (Val >= 4)
5005         break;
5006     }
5007
5008     Mask1[0] = PermMask[HiIndex];
5009     Mask1[1] = -1;
5010     Mask1[2] = PermMask[HiIndex^1];
5011     Mask1[3] = -1;
5012     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5013
5014     if (HiIndex >= 2) {
5015       Mask1[0] = PermMask[0];
5016       Mask1[1] = PermMask[1];
5017       Mask1[2] = HiIndex & 1 ? 6 : 4;
5018       Mask1[3] = HiIndex & 1 ? 4 : 6;
5019       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5020     } else {
5021       Mask1[0] = HiIndex & 1 ? 2 : 0;
5022       Mask1[1] = HiIndex & 1 ? 0 : 2;
5023       Mask1[2] = PermMask[2];
5024       Mask1[3] = PermMask[3];
5025       if (Mask1[2] >= 0)
5026         Mask1[2] += 4;
5027       if (Mask1[3] >= 0)
5028         Mask1[3] += 4;
5029       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5030     }
5031   }
5032
5033   // Break it into (shuffle shuffle_hi, shuffle_lo).
5034   Locs.clear();
5035   SmallVector<int,8> LoMask(4U, -1);
5036   SmallVector<int,8> HiMask(4U, -1);
5037
5038   SmallVector<int,8> *MaskPtr = &LoMask;
5039   unsigned MaskIdx = 0;
5040   unsigned LoIdx = 0;
5041   unsigned HiIdx = 2;
5042   for (unsigned i = 0; i != 4; ++i) {
5043     if (i == 2) {
5044       MaskPtr = &HiMask;
5045       MaskIdx = 1;
5046       LoIdx = 0;
5047       HiIdx = 2;
5048     }
5049     int Idx = PermMask[i];
5050     if (Idx < 0) {
5051       Locs[i] = std::make_pair(-1, -1);
5052     } else if (Idx < 4) {
5053       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5054       (*MaskPtr)[LoIdx] = Idx;
5055       LoIdx++;
5056     } else {
5057       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5058       (*MaskPtr)[HiIdx] = Idx;
5059       HiIdx++;
5060     }
5061   }
5062
5063   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5064   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5065   SmallVector<int, 8> MaskOps;
5066   for (unsigned i = 0; i != 4; ++i) {
5067     if (Locs[i].first == -1) {
5068       MaskOps.push_back(-1);
5069     } else {
5070       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5071       MaskOps.push_back(Idx);
5072     }
5073   }
5074   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5075 }
5076
5077 static bool MayFoldVectorLoad(SDValue V) {
5078   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5079     V = V.getOperand(0);
5080   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5081     V = V.getOperand(0);
5082   if (MayFoldLoad(V))
5083     return true;
5084   return false;
5085 }
5086
5087 // FIXME: the version above should always be used. Since there's
5088 // a bug where several vector shuffles can't be folded because the
5089 // DAG is not updated during lowering and a node claims to have two
5090 // uses while it only has one, use this version, and let isel match
5091 // another instruction if the load really happens to have more than
5092 // one use. Remove this version after this bug get fixed.
5093 // rdar://8434668, PR8156
5094 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5095   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5096     V = V.getOperand(0);
5097   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5098     V = V.getOperand(0);
5099   if (ISD::isNormalLoad(V.getNode()))
5100     return true;
5101   return false;
5102 }
5103
5104 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5105 /// a vector extract, and if both can be later optimized into a single load.
5106 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5107 /// here because otherwise a target specific shuffle node is going to be
5108 /// emitted for this shuffle, and the optimization not done.
5109 /// FIXME: This is probably not the best approach, but fix the problem
5110 /// until the right path is decided.
5111 static
5112 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5113                                          const TargetLowering &TLI) {
5114   EVT VT = V.getValueType();
5115   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5116
5117   // Be sure that the vector shuffle is present in a pattern like this:
5118   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5119   if (!V.hasOneUse())
5120     return false;
5121
5122   SDNode *N = *V.getNode()->use_begin();
5123   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5124     return false;
5125
5126   SDValue EltNo = N->getOperand(1);
5127   if (!isa<ConstantSDNode>(EltNo))
5128     return false;
5129
5130   // If the bit convert changed the number of elements, it is unsafe
5131   // to examine the mask.
5132   bool HasShuffleIntoBitcast = false;
5133   if (V.getOpcode() == ISD::BITCAST) {
5134     EVT SrcVT = V.getOperand(0).getValueType();
5135     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5136       return false;
5137     V = V.getOperand(0);
5138     HasShuffleIntoBitcast = true;
5139   }
5140
5141   // Select the input vector, guarding against out of range extract vector.
5142   unsigned NumElems = VT.getVectorNumElements();
5143   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5144   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5145   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5146
5147   // Skip one more bit_convert if necessary
5148   if (V.getOpcode() == ISD::BITCAST)
5149     V = V.getOperand(0);
5150
5151   if (ISD::isNormalLoad(V.getNode())) {
5152     // Is the original load suitable?
5153     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5154
5155     // FIXME: avoid the multi-use bug that is preventing lots of
5156     // of foldings to be detected, this is still wrong of course, but
5157     // give the temporary desired behavior, and if it happens that
5158     // the load has real more uses, during isel it will not fold, and
5159     // will generate poor code.
5160     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5161       return false;
5162
5163     if (!HasShuffleIntoBitcast)
5164       return true;
5165
5166     // If there's a bitcast before the shuffle, check if the load type and
5167     // alignment is valid.
5168     unsigned Align = LN0->getAlignment();
5169     unsigned NewAlign =
5170       TLI.getTargetData()->getABITypeAlignment(
5171                                     VT.getTypeForEVT(*DAG.getContext()));
5172
5173     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5174       return false;
5175   }
5176
5177   return true;
5178 }
5179
5180 static
5181 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5182   EVT VT = Op.getValueType();
5183
5184   // Canonizalize to v2f64.
5185   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5186   return DAG.getNode(ISD::BITCAST, dl, VT,
5187                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5188                                           V1, DAG));
5189 }
5190
5191 static
5192 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5193                         bool HasSSE2) {
5194   SDValue V1 = Op.getOperand(0);
5195   SDValue V2 = Op.getOperand(1);
5196   EVT VT = Op.getValueType();
5197
5198   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5199
5200   if (HasSSE2 && VT == MVT::v2f64)
5201     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5202
5203   // v4f32 or v4i32
5204   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5205 }
5206
5207 static
5208 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5209   SDValue V1 = Op.getOperand(0);
5210   SDValue V2 = Op.getOperand(1);
5211   EVT VT = Op.getValueType();
5212
5213   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5214          "unsupported shuffle type");
5215
5216   if (V2.getOpcode() == ISD::UNDEF)
5217     V2 = V1;
5218
5219   // v4i32 or v4f32
5220   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5221 }
5222
5223 static
5224 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5225   SDValue V1 = Op.getOperand(0);
5226   SDValue V2 = Op.getOperand(1);
5227   EVT VT = Op.getValueType();
5228   unsigned NumElems = VT.getVectorNumElements();
5229
5230   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5231   // operand of these instructions is only memory, so check if there's a
5232   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5233   // same masks.
5234   bool CanFoldLoad = false;
5235
5236   // Trivial case, when V2 comes from a load.
5237   if (MayFoldVectorLoad(V2))
5238     CanFoldLoad = true;
5239
5240   // When V1 is a load, it can be folded later into a store in isel, example:
5241   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5242   //    turns into:
5243   //  (MOVLPSmr addr:$src1, VR128:$src2)
5244   // So, recognize this potential and also use MOVLPS or MOVLPD
5245   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5246     CanFoldLoad = true;
5247
5248   if (CanFoldLoad) {
5249     if (HasSSE2 && NumElems == 2)
5250       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5251
5252     if (NumElems == 4)
5253       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5254   }
5255
5256   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5257   // movl and movlp will both match v2i64, but v2i64 is never matched by
5258   // movl earlier because we make it strict to avoid messing with the movlp load
5259   // folding logic (see the code above getMOVLP call). Match it here then,
5260   // this is horrible, but will stay like this until we move all shuffle
5261   // matching to x86 specific nodes. Note that for the 1st condition all
5262   // types are matched with movsd.
5263   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5264     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5265   else if (HasSSE2)
5266     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5267
5268
5269   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5270
5271   // Invert the operand order and use SHUFPS to match it.
5272   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5273                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5274 }
5275
5276 static inline unsigned getUNPCKLOpcode(EVT VT) {
5277   switch(VT.getSimpleVT().SimpleTy) {
5278   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5279   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5280   case MVT::v4f32: return X86ISD::UNPCKLPS;
5281   case MVT::v2f64: return X86ISD::UNPCKLPD;
5282   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5283   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5284   default:
5285     llvm_unreachable("Unknow type for unpckl");
5286   }
5287   return 0;
5288 }
5289
5290 static inline unsigned getUNPCKHOpcode(EVT VT) {
5291   switch(VT.getSimpleVT().SimpleTy) {
5292   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5293   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5294   case MVT::v4f32: return X86ISD::UNPCKHPS;
5295   case MVT::v2f64: return X86ISD::UNPCKHPD;
5296   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5297   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5298   default:
5299     llvm_unreachable("Unknow type for unpckh");
5300   }
5301   return 0;
5302 }
5303
5304 static
5305 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5306                                const TargetLowering &TLI,
5307                                const X86Subtarget *Subtarget) {
5308   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5309   EVT VT = Op.getValueType();
5310   DebugLoc dl = Op.getDebugLoc();
5311   SDValue V1 = Op.getOperand(0);
5312   SDValue V2 = Op.getOperand(1);
5313
5314   if (isZeroShuffle(SVOp))
5315     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5316
5317   // Handle splat operations
5318   if (SVOp->isSplat()) {
5319     // Special case, this is the only place now where it's
5320     // allowed to return a vector_shuffle operation without
5321     // using a target specific node, because *hopefully* it
5322     // will be optimized away by the dag combiner.
5323     if (VT.getVectorNumElements() <= 4 &&
5324         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5325       return Op;
5326
5327     // Handle splats by matching through known masks
5328     if (VT.getVectorNumElements() <= 4)
5329       return SDValue();
5330
5331     // Canonicalize all of the remaining to v4f32.
5332     return PromoteSplat(SVOp, DAG);
5333   }
5334
5335   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5336   // do it!
5337   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5338     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5339     if (NewOp.getNode())
5340       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5341   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5342     // FIXME: Figure out a cleaner way to do this.
5343     // Try to make use of movq to zero out the top part.
5344     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5345       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5346       if (NewOp.getNode()) {
5347         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5348           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5349                               DAG, Subtarget, dl);
5350       }
5351     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5352       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5353       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5354         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5355                             DAG, Subtarget, dl);
5356     }
5357   }
5358   return SDValue();
5359 }
5360
5361 SDValue
5362 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5363   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5364   SDValue V1 = Op.getOperand(0);
5365   SDValue V2 = Op.getOperand(1);
5366   EVT VT = Op.getValueType();
5367   DebugLoc dl = Op.getDebugLoc();
5368   unsigned NumElems = VT.getVectorNumElements();
5369   bool isMMX = VT.getSizeInBits() == 64;
5370   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5371   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5372   bool V1IsSplat = false;
5373   bool V2IsSplat = false;
5374   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5375   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5376   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5377   MachineFunction &MF = DAG.getMachineFunction();
5378   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5379
5380   // Shuffle operations on MMX not supported.
5381   if (isMMX)
5382     return Op;
5383
5384   // Vector shuffle lowering takes 3 steps:
5385   //
5386   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5387   //    narrowing and commutation of operands should be handled.
5388   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5389   //    shuffle nodes.
5390   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5391   //    so the shuffle can be broken into other shuffles and the legalizer can
5392   //    try the lowering again.
5393   //
5394   // The general ideia is that no vector_shuffle operation should be left to
5395   // be matched during isel, all of them must be converted to a target specific
5396   // node here.
5397
5398   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5399   // narrowing and commutation of operands should be handled. The actual code
5400   // doesn't include all of those, work in progress...
5401   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5402   if (NewOp.getNode())
5403     return NewOp;
5404
5405   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5406   // unpckh_undef). Only use pshufd if speed is more important than size.
5407   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5408     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5409       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5410   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5411     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5412       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5413
5414   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5415       RelaxedMayFoldVectorLoad(V1))
5416     return getMOVDDup(Op, dl, V1, DAG);
5417
5418   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5419     return getMOVHighToLow(Op, dl, DAG);
5420
5421   // Use to match splats
5422   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5423       (VT == MVT::v2f64 || VT == MVT::v2i64))
5424     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5425
5426   if (X86::isPSHUFDMask(SVOp)) {
5427     // The actual implementation will match the mask in the if above and then
5428     // during isel it can match several different instructions, not only pshufd
5429     // as its name says, sad but true, emulate the behavior for now...
5430     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5431         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5432
5433     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5434
5435     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5436       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5437
5438     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5439       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5440                                   TargetMask, DAG);
5441
5442     if (VT == MVT::v4f32)
5443       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5444                                   TargetMask, DAG);
5445   }
5446
5447   // Check if this can be converted into a logical shift.
5448   bool isLeft = false;
5449   unsigned ShAmt = 0;
5450   SDValue ShVal;
5451   bool isShift = getSubtarget()->hasSSE2() &&
5452     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5453   if (isShift && ShVal.hasOneUse()) {
5454     // If the shifted value has multiple uses, it may be cheaper to use
5455     // v_set0 + movlhps or movhlps, etc.
5456     EVT EltVT = VT.getVectorElementType();
5457     ShAmt *= EltVT.getSizeInBits();
5458     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5459   }
5460
5461   if (X86::isMOVLMask(SVOp)) {
5462     if (V1IsUndef)
5463       return V2;
5464     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5465       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5466     if (!X86::isMOVLPMask(SVOp)) {
5467       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5468         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5469
5470       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5471         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5472     }
5473   }
5474
5475   // FIXME: fold these into legal mask.
5476   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5477     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5478
5479   if (X86::isMOVHLPSMask(SVOp))
5480     return getMOVHighToLow(Op, dl, DAG);
5481
5482   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5483     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5484
5485   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5486     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5487
5488   if (X86::isMOVLPMask(SVOp))
5489     return getMOVLP(Op, dl, DAG, HasSSE2);
5490
5491   if (ShouldXformToMOVHLPS(SVOp) ||
5492       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5493     return CommuteVectorShuffle(SVOp, DAG);
5494
5495   if (isShift) {
5496     // No better options. Use a vshl / vsrl.
5497     EVT EltVT = VT.getVectorElementType();
5498     ShAmt *= EltVT.getSizeInBits();
5499     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5500   }
5501
5502   bool Commuted = false;
5503   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5504   // 1,1,1,1 -> v8i16 though.
5505   V1IsSplat = isSplatVector(V1.getNode());
5506   V2IsSplat = isSplatVector(V2.getNode());
5507
5508   // Canonicalize the splat or undef, if present, to be on the RHS.
5509   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5510     Op = CommuteVectorShuffle(SVOp, DAG);
5511     SVOp = cast<ShuffleVectorSDNode>(Op);
5512     V1 = SVOp->getOperand(0);
5513     V2 = SVOp->getOperand(1);
5514     std::swap(V1IsSplat, V2IsSplat);
5515     std::swap(V1IsUndef, V2IsUndef);
5516     Commuted = true;
5517   }
5518
5519   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5520     // Shuffling low element of v1 into undef, just return v1.
5521     if (V2IsUndef)
5522       return V1;
5523     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5524     // the instruction selector will not match, so get a canonical MOVL with
5525     // swapped operands to undo the commute.
5526     return getMOVL(DAG, dl, VT, V2, V1);
5527   }
5528
5529   if (X86::isUNPCKLMask(SVOp))
5530     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5531
5532   if (X86::isUNPCKHMask(SVOp))
5533     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5534
5535   if (V2IsSplat) {
5536     // Normalize mask so all entries that point to V2 points to its first
5537     // element then try to match unpck{h|l} again. If match, return a
5538     // new vector_shuffle with the corrected mask.
5539     SDValue NewMask = NormalizeMask(SVOp, DAG);
5540     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5541     if (NSVOp != SVOp) {
5542       if (X86::isUNPCKLMask(NSVOp, true)) {
5543         return NewMask;
5544       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5545         return NewMask;
5546       }
5547     }
5548   }
5549
5550   if (Commuted) {
5551     // Commute is back and try unpck* again.
5552     // FIXME: this seems wrong.
5553     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5554     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5555
5556     if (X86::isUNPCKLMask(NewSVOp))
5557       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5558
5559     if (X86::isUNPCKHMask(NewSVOp))
5560       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5561   }
5562
5563   // Normalize the node to match x86 shuffle ops if needed
5564   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5565     return CommuteVectorShuffle(SVOp, DAG);
5566
5567   // The checks below are all present in isShuffleMaskLegal, but they are
5568   // inlined here right now to enable us to directly emit target specific
5569   // nodes, and remove one by one until they don't return Op anymore.
5570   SmallVector<int, 16> M;
5571   SVOp->getMask(M);
5572
5573   if (isPALIGNRMask(M, VT, HasSSSE3))
5574     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5575                                 X86::getShufflePALIGNRImmediate(SVOp),
5576                                 DAG);
5577
5578   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5579       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5580     if (VT == MVT::v2f64)
5581       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5582     if (VT == MVT::v2i64)
5583       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5584   }
5585
5586   if (isPSHUFHWMask(M, VT))
5587     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5588                                 X86::getShufflePSHUFHWImmediate(SVOp),
5589                                 DAG);
5590
5591   if (isPSHUFLWMask(M, VT))
5592     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5593                                 X86::getShufflePSHUFLWImmediate(SVOp),
5594                                 DAG);
5595
5596   if (isSHUFPMask(M, VT)) {
5597     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5598     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5599       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5600                                   TargetMask, DAG);
5601     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5602       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5603                                   TargetMask, DAG);
5604   }
5605
5606   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5607     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5608       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5609   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5610     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5611       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5612
5613   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5614   if (VT == MVT::v8i16) {
5615     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5616     if (NewOp.getNode())
5617       return NewOp;
5618   }
5619
5620   if (VT == MVT::v16i8) {
5621     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5622     if (NewOp.getNode())
5623       return NewOp;
5624   }
5625
5626   // Handle all 4 wide cases with a number of shuffles.
5627   if (NumElems == 4)
5628     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5629
5630   return SDValue();
5631 }
5632
5633 SDValue
5634 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5635                                                 SelectionDAG &DAG) const {
5636   EVT VT = Op.getValueType();
5637   DebugLoc dl = Op.getDebugLoc();
5638   if (VT.getSizeInBits() == 8) {
5639     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5640                                     Op.getOperand(0), Op.getOperand(1));
5641     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5642                                     DAG.getValueType(VT));
5643     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5644   } else if (VT.getSizeInBits() == 16) {
5645     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5646     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5647     if (Idx == 0)
5648       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5649                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5650                                      DAG.getNode(ISD::BITCAST, dl,
5651                                                  MVT::v4i32,
5652                                                  Op.getOperand(0)),
5653                                      Op.getOperand(1)));
5654     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5655                                     Op.getOperand(0), Op.getOperand(1));
5656     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5657                                     DAG.getValueType(VT));
5658     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5659   } else if (VT == MVT::f32) {
5660     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5661     // the result back to FR32 register. It's only worth matching if the
5662     // result has a single use which is a store or a bitcast to i32.  And in
5663     // the case of a store, it's not worth it if the index is a constant 0,
5664     // because a MOVSSmr can be used instead, which is smaller and faster.
5665     if (!Op.hasOneUse())
5666       return SDValue();
5667     SDNode *User = *Op.getNode()->use_begin();
5668     if ((User->getOpcode() != ISD::STORE ||
5669          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5670           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5671         (User->getOpcode() != ISD::BITCAST ||
5672          User->getValueType(0) != MVT::i32))
5673       return SDValue();
5674     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5675                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5676                                               Op.getOperand(0)),
5677                                               Op.getOperand(1));
5678     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5679   } else if (VT == MVT::i32) {
5680     // ExtractPS works with constant index.
5681     if (isa<ConstantSDNode>(Op.getOperand(1)))
5682       return Op;
5683   }
5684   return SDValue();
5685 }
5686
5687
5688 SDValue
5689 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5690                                            SelectionDAG &DAG) const {
5691   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5692     return SDValue();
5693
5694   if (Subtarget->hasSSE41()) {
5695     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5696     if (Res.getNode())
5697       return Res;
5698   }
5699
5700   EVT VT = Op.getValueType();
5701   DebugLoc dl = Op.getDebugLoc();
5702   // TODO: handle v16i8.
5703   if (VT.getSizeInBits() == 16) {
5704     SDValue Vec = Op.getOperand(0);
5705     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5706     if (Idx == 0)
5707       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5708                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5709                                      DAG.getNode(ISD::BITCAST, dl,
5710                                                  MVT::v4i32, Vec),
5711                                      Op.getOperand(1)));
5712     // Transform it so it match pextrw which produces a 32-bit result.
5713     EVT EltVT = MVT::i32;
5714     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5715                                     Op.getOperand(0), Op.getOperand(1));
5716     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5717                                     DAG.getValueType(VT));
5718     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5719   } else if (VT.getSizeInBits() == 32) {
5720     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5721     if (Idx == 0)
5722       return Op;
5723
5724     // SHUFPS the element to the lowest double word, then movss.
5725     int Mask[4] = { Idx, -1, -1, -1 };
5726     EVT VVT = Op.getOperand(0).getValueType();
5727     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5728                                        DAG.getUNDEF(VVT), Mask);
5729     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5730                        DAG.getIntPtrConstant(0));
5731   } else if (VT.getSizeInBits() == 64) {
5732     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5733     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5734     //        to match extract_elt for f64.
5735     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5736     if (Idx == 0)
5737       return Op;
5738
5739     // UNPCKHPD the element to the lowest double word, then movsd.
5740     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5741     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5742     int Mask[2] = { 1, -1 };
5743     EVT VVT = Op.getOperand(0).getValueType();
5744     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5745                                        DAG.getUNDEF(VVT), Mask);
5746     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5747                        DAG.getIntPtrConstant(0));
5748   }
5749
5750   return SDValue();
5751 }
5752
5753 SDValue
5754 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5755                                                SelectionDAG &DAG) const {
5756   EVT VT = Op.getValueType();
5757   EVT EltVT = VT.getVectorElementType();
5758   DebugLoc dl = Op.getDebugLoc();
5759
5760   SDValue N0 = Op.getOperand(0);
5761   SDValue N1 = Op.getOperand(1);
5762   SDValue N2 = Op.getOperand(2);
5763
5764   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5765       isa<ConstantSDNode>(N2)) {
5766     unsigned Opc;
5767     if (VT == MVT::v8i16)
5768       Opc = X86ISD::PINSRW;
5769     else if (VT == MVT::v16i8)
5770       Opc = X86ISD::PINSRB;
5771     else
5772       Opc = X86ISD::PINSRB;
5773
5774     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5775     // argument.
5776     if (N1.getValueType() != MVT::i32)
5777       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5778     if (N2.getValueType() != MVT::i32)
5779       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5780     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5781   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5782     // Bits [7:6] of the constant are the source select.  This will always be
5783     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5784     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5785     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5786     // Bits [5:4] of the constant are the destination select.  This is the
5787     //  value of the incoming immediate.
5788     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5789     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5790     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5791     // Create this as a scalar to vector..
5792     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5793     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5794   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5795     // PINSR* works with constant index.
5796     return Op;
5797   }
5798   return SDValue();
5799 }
5800
5801 SDValue
5802 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5803   EVT VT = Op.getValueType();
5804   EVT EltVT = VT.getVectorElementType();
5805
5806   if (Subtarget->hasSSE41())
5807     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5808
5809   if (EltVT == MVT::i8)
5810     return SDValue();
5811
5812   DebugLoc dl = Op.getDebugLoc();
5813   SDValue N0 = Op.getOperand(0);
5814   SDValue N1 = Op.getOperand(1);
5815   SDValue N2 = Op.getOperand(2);
5816
5817   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5818     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5819     // as its second argument.
5820     if (N1.getValueType() != MVT::i32)
5821       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5822     if (N2.getValueType() != MVT::i32)
5823       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5824     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5825   }
5826   return SDValue();
5827 }
5828
5829 SDValue
5830 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5831   DebugLoc dl = Op.getDebugLoc();
5832
5833   if (Op.getValueType() == MVT::v1i64 &&
5834       Op.getOperand(0).getValueType() == MVT::i64)
5835     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5836
5837   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5838   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5839          "Expected an SSE type!");
5840   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5841                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5842 }
5843
5844 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5845 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5846 // one of the above mentioned nodes. It has to be wrapped because otherwise
5847 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5848 // be used to form addressing mode. These wrapped nodes will be selected
5849 // into MOV32ri.
5850 SDValue
5851 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5852   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5853
5854   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5855   // global base reg.
5856   unsigned char OpFlag = 0;
5857   unsigned WrapperKind = X86ISD::Wrapper;
5858   CodeModel::Model M = getTargetMachine().getCodeModel();
5859
5860   if (Subtarget->isPICStyleRIPRel() &&
5861       (M == CodeModel::Small || M == CodeModel::Kernel))
5862     WrapperKind = X86ISD::WrapperRIP;
5863   else if (Subtarget->isPICStyleGOT())
5864     OpFlag = X86II::MO_GOTOFF;
5865   else if (Subtarget->isPICStyleStubPIC())
5866     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5867
5868   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5869                                              CP->getAlignment(),
5870                                              CP->getOffset(), OpFlag);
5871   DebugLoc DL = CP->getDebugLoc();
5872   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5873   // With PIC, the address is actually $g + Offset.
5874   if (OpFlag) {
5875     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5876                          DAG.getNode(X86ISD::GlobalBaseReg,
5877                                      DebugLoc(), getPointerTy()),
5878                          Result);
5879   }
5880
5881   return Result;
5882 }
5883
5884 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5885   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5886
5887   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5888   // global base reg.
5889   unsigned char OpFlag = 0;
5890   unsigned WrapperKind = X86ISD::Wrapper;
5891   CodeModel::Model M = getTargetMachine().getCodeModel();
5892
5893   if (Subtarget->isPICStyleRIPRel() &&
5894       (M == CodeModel::Small || M == CodeModel::Kernel))
5895     WrapperKind = X86ISD::WrapperRIP;
5896   else if (Subtarget->isPICStyleGOT())
5897     OpFlag = X86II::MO_GOTOFF;
5898   else if (Subtarget->isPICStyleStubPIC())
5899     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5900
5901   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5902                                           OpFlag);
5903   DebugLoc DL = JT->getDebugLoc();
5904   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5905
5906   // With PIC, the address is actually $g + Offset.
5907   if (OpFlag)
5908     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5909                          DAG.getNode(X86ISD::GlobalBaseReg,
5910                                      DebugLoc(), getPointerTy()),
5911                          Result);
5912
5913   return Result;
5914 }
5915
5916 SDValue
5917 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5918   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5919
5920   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5921   // global base reg.
5922   unsigned char OpFlag = 0;
5923   unsigned WrapperKind = X86ISD::Wrapper;
5924   CodeModel::Model M = getTargetMachine().getCodeModel();
5925
5926   if (Subtarget->isPICStyleRIPRel() &&
5927       (M == CodeModel::Small || M == CodeModel::Kernel))
5928     WrapperKind = X86ISD::WrapperRIP;
5929   else if (Subtarget->isPICStyleGOT())
5930     OpFlag = X86II::MO_GOTOFF;
5931   else if (Subtarget->isPICStyleStubPIC())
5932     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5933
5934   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5935
5936   DebugLoc DL = Op.getDebugLoc();
5937   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5938
5939
5940   // With PIC, the address is actually $g + Offset.
5941   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5942       !Subtarget->is64Bit()) {
5943     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5944                          DAG.getNode(X86ISD::GlobalBaseReg,
5945                                      DebugLoc(), getPointerTy()),
5946                          Result);
5947   }
5948
5949   return Result;
5950 }
5951
5952 SDValue
5953 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5954   // Create the TargetBlockAddressAddress node.
5955   unsigned char OpFlags =
5956     Subtarget->ClassifyBlockAddressReference();
5957   CodeModel::Model M = getTargetMachine().getCodeModel();
5958   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5959   DebugLoc dl = Op.getDebugLoc();
5960   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5961                                        /*isTarget=*/true, OpFlags);
5962
5963   if (Subtarget->isPICStyleRIPRel() &&
5964       (M == CodeModel::Small || M == CodeModel::Kernel))
5965     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5966   else
5967     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5968
5969   // With PIC, the address is actually $g + Offset.
5970   if (isGlobalRelativeToPICBase(OpFlags)) {
5971     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5972                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5973                          Result);
5974   }
5975
5976   return Result;
5977 }
5978
5979 SDValue
5980 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5981                                       int64_t Offset,
5982                                       SelectionDAG &DAG) const {
5983   // Create the TargetGlobalAddress node, folding in the constant
5984   // offset if it is legal.
5985   unsigned char OpFlags =
5986     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5987   CodeModel::Model M = getTargetMachine().getCodeModel();
5988   SDValue Result;
5989   if (OpFlags == X86II::MO_NO_FLAG &&
5990       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5991     // A direct static reference to a global.
5992     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5993     Offset = 0;
5994   } else {
5995     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5996   }
5997
5998   if (Subtarget->isPICStyleRIPRel() &&
5999       (M == CodeModel::Small || M == CodeModel::Kernel))
6000     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6001   else
6002     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6003
6004   // With PIC, the address is actually $g + Offset.
6005   if (isGlobalRelativeToPICBase(OpFlags)) {
6006     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6007                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6008                          Result);
6009   }
6010
6011   // For globals that require a load from a stub to get the address, emit the
6012   // load.
6013   if (isGlobalStubReference(OpFlags))
6014     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6015                          MachinePointerInfo::getGOT(), false, false, 0);
6016
6017   // If there was a non-zero offset that we didn't fold, create an explicit
6018   // addition for it.
6019   if (Offset != 0)
6020     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6021                          DAG.getConstant(Offset, getPointerTy()));
6022
6023   return Result;
6024 }
6025
6026 SDValue
6027 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6028   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6029   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6030   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6031 }
6032
6033 static SDValue
6034 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6035            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6036            unsigned char OperandFlags) {
6037   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6038   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6039   DebugLoc dl = GA->getDebugLoc();
6040   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6041                                            GA->getValueType(0),
6042                                            GA->getOffset(),
6043                                            OperandFlags);
6044   if (InFlag) {
6045     SDValue Ops[] = { Chain,  TGA, *InFlag };
6046     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6047   } else {
6048     SDValue Ops[]  = { Chain, TGA };
6049     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6050   }
6051
6052   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6053   MFI->setAdjustsStack(true);
6054
6055   SDValue Flag = Chain.getValue(1);
6056   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6057 }
6058
6059 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6060 static SDValue
6061 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6062                                 const EVT PtrVT) {
6063   SDValue InFlag;
6064   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6065   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6066                                      DAG.getNode(X86ISD::GlobalBaseReg,
6067                                                  DebugLoc(), PtrVT), InFlag);
6068   InFlag = Chain.getValue(1);
6069
6070   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6071 }
6072
6073 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6074 static SDValue
6075 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6076                                 const EVT PtrVT) {
6077   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6078                     X86::RAX, X86II::MO_TLSGD);
6079 }
6080
6081 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6082 // "local exec" model.
6083 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6084                                    const EVT PtrVT, TLSModel::Model model,
6085                                    bool is64Bit) {
6086   DebugLoc dl = GA->getDebugLoc();
6087
6088   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6089   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6090                                                          is64Bit ? 257 : 256));
6091
6092   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6093                                       DAG.getIntPtrConstant(0),
6094                                       MachinePointerInfo(Ptr), false, false, 0);
6095
6096   unsigned char OperandFlags = 0;
6097   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6098   // initialexec.
6099   unsigned WrapperKind = X86ISD::Wrapper;
6100   if (model == TLSModel::LocalExec) {
6101     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6102   } else if (is64Bit) {
6103     assert(model == TLSModel::InitialExec);
6104     OperandFlags = X86II::MO_GOTTPOFF;
6105     WrapperKind = X86ISD::WrapperRIP;
6106   } else {
6107     assert(model == TLSModel::InitialExec);
6108     OperandFlags = X86II::MO_INDNTPOFF;
6109   }
6110
6111   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6112   // exec)
6113   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6114                                            GA->getValueType(0),
6115                                            GA->getOffset(), OperandFlags);
6116   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6117
6118   if (model == TLSModel::InitialExec)
6119     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6120                          MachinePointerInfo::getGOT(), false, false, 0);
6121
6122   // The address of the thread local variable is the add of the thread
6123   // pointer with the offset of the variable.
6124   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6125 }
6126
6127 SDValue
6128 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6129
6130   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6131   const GlobalValue *GV = GA->getGlobal();
6132
6133   if (Subtarget->isTargetELF()) {
6134     // TODO: implement the "local dynamic" model
6135     // TODO: implement the "initial exec"model for pic executables
6136
6137     // If GV is an alias then use the aliasee for determining
6138     // thread-localness.
6139     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6140       GV = GA->resolveAliasedGlobal(false);
6141
6142     TLSModel::Model model
6143       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6144
6145     switch (model) {
6146       case TLSModel::GeneralDynamic:
6147       case TLSModel::LocalDynamic: // not implemented
6148         if (Subtarget->is64Bit())
6149           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6150         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6151
6152       case TLSModel::InitialExec:
6153       case TLSModel::LocalExec:
6154         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6155                                    Subtarget->is64Bit());
6156     }
6157   } else if (Subtarget->isTargetDarwin()) {
6158     // Darwin only has one model of TLS.  Lower to that.
6159     unsigned char OpFlag = 0;
6160     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6161                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6162
6163     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6164     // global base reg.
6165     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6166                   !Subtarget->is64Bit();
6167     if (PIC32)
6168       OpFlag = X86II::MO_TLVP_PIC_BASE;
6169     else
6170       OpFlag = X86II::MO_TLVP;
6171     DebugLoc DL = Op.getDebugLoc();
6172     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6173                                                 GA->getValueType(0),
6174                                                 GA->getOffset(), OpFlag);
6175     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6176
6177     // With PIC32, the address is actually $g + Offset.
6178     if (PIC32)
6179       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6180                            DAG.getNode(X86ISD::GlobalBaseReg,
6181                                        DebugLoc(), getPointerTy()),
6182                            Offset);
6183
6184     // Lowering the machine isd will make sure everything is in the right
6185     // location.
6186     SDValue Chain = DAG.getEntryNode();
6187     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6188     SDValue Args[] = { Chain, Offset };
6189     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6190
6191     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6192     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6193     MFI->setAdjustsStack(true);
6194     
6195     // And our return value (tls address) is in the standard call return value
6196     // location.
6197     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6198     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6199   }
6200
6201   assert(false &&
6202          "TLS not implemented for this target.");
6203
6204   llvm_unreachable("Unreachable");
6205   return SDValue();
6206 }
6207
6208
6209 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6210 /// take a 2 x i32 value to shift plus a shift amount.
6211 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6212   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6213   EVT VT = Op.getValueType();
6214   unsigned VTBits = VT.getSizeInBits();
6215   DebugLoc dl = Op.getDebugLoc();
6216   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6217   SDValue ShOpLo = Op.getOperand(0);
6218   SDValue ShOpHi = Op.getOperand(1);
6219   SDValue ShAmt  = Op.getOperand(2);
6220   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6221                                      DAG.getConstant(VTBits - 1, MVT::i8))
6222                        : DAG.getConstant(0, VT);
6223
6224   SDValue Tmp2, Tmp3;
6225   if (Op.getOpcode() == ISD::SHL_PARTS) {
6226     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6227     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6228   } else {
6229     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6230     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6231   }
6232
6233   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6234                                 DAG.getConstant(VTBits, MVT::i8));
6235   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6236                              AndNode, DAG.getConstant(0, MVT::i8));
6237
6238   SDValue Hi, Lo;
6239   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6240   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6241   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6242
6243   if (Op.getOpcode() == ISD::SHL_PARTS) {
6244     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6245     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6246   } else {
6247     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6248     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6249   }
6250
6251   SDValue Ops[2] = { Lo, Hi };
6252   return DAG.getMergeValues(Ops, 2, dl);
6253 }
6254
6255 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6256                                            SelectionDAG &DAG) const {
6257   EVT SrcVT = Op.getOperand(0).getValueType();
6258
6259   if (SrcVT.isVector())
6260     return SDValue();
6261
6262   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6263          "Unknown SINT_TO_FP to lower!");
6264
6265   // These are really Legal; return the operand so the caller accepts it as
6266   // Legal.
6267   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6268     return Op;
6269   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6270       Subtarget->is64Bit()) {
6271     return Op;
6272   }
6273
6274   DebugLoc dl = Op.getDebugLoc();
6275   unsigned Size = SrcVT.getSizeInBits()/8;
6276   MachineFunction &MF = DAG.getMachineFunction();
6277   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6278   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6279   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6280                                StackSlot,
6281                                MachinePointerInfo::getFixedStack(SSFI),
6282                                false, false, 0);
6283   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6284 }
6285
6286 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6287                                      SDValue StackSlot,
6288                                      SelectionDAG &DAG) const {
6289   // Build the FILD
6290   DebugLoc DL = Op.getDebugLoc();
6291   SDVTList Tys;
6292   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6293   if (useSSE)
6294     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6295   else
6296     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6297
6298   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6299
6300   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6301   MachineMemOperand *MMO =
6302     DAG.getMachineFunction()
6303     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6304                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6305
6306   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6307   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6308                                            X86ISD::FILD, DL,
6309                                            Tys, Ops, array_lengthof(Ops),
6310                                            SrcVT, MMO);
6311
6312   if (useSSE) {
6313     Chain = Result.getValue(1);
6314     SDValue InFlag = Result.getValue(2);
6315
6316     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6317     // shouldn't be necessary except that RFP cannot be live across
6318     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6319     MachineFunction &MF = DAG.getMachineFunction();
6320     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6321     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6322     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6323     Tys = DAG.getVTList(MVT::Other);
6324     SDValue Ops[] = {
6325       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6326     };
6327     MachineMemOperand *MMO =
6328       DAG.getMachineFunction()
6329       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6330                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6331
6332     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6333                                     Ops, array_lengthof(Ops),
6334                                     Op.getValueType(), MMO);
6335     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6336                          MachinePointerInfo::getFixedStack(SSFI),
6337                          false, false, 0);
6338   }
6339
6340   return Result;
6341 }
6342
6343 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6344 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6345                                                SelectionDAG &DAG) const {
6346   // This algorithm is not obvious. Here it is in C code, more or less:
6347   /*
6348     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6349       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6350       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6351
6352       // Copy ints to xmm registers.
6353       __m128i xh = _mm_cvtsi32_si128( hi );
6354       __m128i xl = _mm_cvtsi32_si128( lo );
6355
6356       // Combine into low half of a single xmm register.
6357       __m128i x = _mm_unpacklo_epi32( xh, xl );
6358       __m128d d;
6359       double sd;
6360
6361       // Merge in appropriate exponents to give the integer bits the right
6362       // magnitude.
6363       x = _mm_unpacklo_epi32( x, exp );
6364
6365       // Subtract away the biases to deal with the IEEE-754 double precision
6366       // implicit 1.
6367       d = _mm_sub_pd( (__m128d) x, bias );
6368
6369       // All conversions up to here are exact. The correctly rounded result is
6370       // calculated using the current rounding mode using the following
6371       // horizontal add.
6372       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6373       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6374                                 // store doesn't really need to be here (except
6375                                 // maybe to zero the other double)
6376       return sd;
6377     }
6378   */
6379
6380   DebugLoc dl = Op.getDebugLoc();
6381   LLVMContext *Context = DAG.getContext();
6382
6383   // Build some magic constants.
6384   std::vector<Constant*> CV0;
6385   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6386   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6387   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6388   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6389   Constant *C0 = ConstantVector::get(CV0);
6390   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6391
6392   std::vector<Constant*> CV1;
6393   CV1.push_back(
6394     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6395   CV1.push_back(
6396     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6397   Constant *C1 = ConstantVector::get(CV1);
6398   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6399
6400   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6401                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6402                                         Op.getOperand(0),
6403                                         DAG.getIntPtrConstant(1)));
6404   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6405                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6406                                         Op.getOperand(0),
6407                                         DAG.getIntPtrConstant(0)));
6408   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6409   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6410                               MachinePointerInfo::getConstantPool(),
6411                               false, false, 16);
6412   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6413   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6414   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6415                               MachinePointerInfo::getConstantPool(),
6416                               false, false, 16);
6417   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6418
6419   // Add the halves; easiest way is to swap them into another reg first.
6420   int ShufMask[2] = { 1, -1 };
6421   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6422                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6423   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6424   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6425                      DAG.getIntPtrConstant(0));
6426 }
6427
6428 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6429 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6430                                                SelectionDAG &DAG) const {
6431   DebugLoc dl = Op.getDebugLoc();
6432   // FP constant to bias correct the final result.
6433   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6434                                    MVT::f64);
6435
6436   // Load the 32-bit value into an XMM register.
6437   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6438                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6439                                          Op.getOperand(0),
6440                                          DAG.getIntPtrConstant(0)));
6441
6442   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6443                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6444                      DAG.getIntPtrConstant(0));
6445
6446   // Or the load with the bias.
6447   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6448                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6449                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6450                                                    MVT::v2f64, Load)),
6451                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6452                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6453                                                    MVT::v2f64, Bias)));
6454   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6455                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6456                    DAG.getIntPtrConstant(0));
6457
6458   // Subtract the bias.
6459   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6460
6461   // Handle final rounding.
6462   EVT DestVT = Op.getValueType();
6463
6464   if (DestVT.bitsLT(MVT::f64)) {
6465     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6466                        DAG.getIntPtrConstant(0));
6467   } else if (DestVT.bitsGT(MVT::f64)) {
6468     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6469   }
6470
6471   // Handle final rounding.
6472   return Sub;
6473 }
6474
6475 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6476                                            SelectionDAG &DAG) const {
6477   SDValue N0 = Op.getOperand(0);
6478   DebugLoc dl = Op.getDebugLoc();
6479
6480   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6481   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6482   // the optimization here.
6483   if (DAG.SignBitIsZero(N0))
6484     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6485
6486   EVT SrcVT = N0.getValueType();
6487   EVT DstVT = Op.getValueType();
6488   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6489     return LowerUINT_TO_FP_i64(Op, DAG);
6490   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6491     return LowerUINT_TO_FP_i32(Op, DAG);
6492
6493   // Make a 64-bit buffer, and use it to build an FILD.
6494   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6495   if (SrcVT == MVT::i32) {
6496     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6497     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6498                                      getPointerTy(), StackSlot, WordOff);
6499     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6500                                   StackSlot, MachinePointerInfo(),
6501                                   false, false, 0);
6502     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6503                                   OffsetSlot, MachinePointerInfo(),
6504                                   false, false, 0);
6505     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6506     return Fild;
6507   }
6508
6509   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6510   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6511                                 StackSlot, MachinePointerInfo(),
6512                                false, false, 0);
6513   // For i64 source, we need to add the appropriate power of 2 if the input
6514   // was negative.  This is the same as the optimization in
6515   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6516   // we must be careful to do the computation in x87 extended precision, not
6517   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6518   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6519   MachineMemOperand *MMO =
6520     DAG.getMachineFunction()
6521     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6522                           MachineMemOperand::MOLoad, 8, 8);
6523
6524   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6525   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6526   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6527                                          MVT::i64, MMO);
6528
6529   APInt FF(32, 0x5F800000ULL);
6530
6531   // Check whether the sign bit is set.
6532   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6533                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6534                                  ISD::SETLT);
6535
6536   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6537   SDValue FudgePtr = DAG.getConstantPool(
6538                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6539                                          getPointerTy());
6540
6541   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6542   SDValue Zero = DAG.getIntPtrConstant(0);
6543   SDValue Four = DAG.getIntPtrConstant(4);
6544   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6545                                Zero, Four);
6546   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6547
6548   // Load the value out, extending it from f32 to f80.
6549   // FIXME: Avoid the extend by constructing the right constant pool?
6550   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6551                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6552                                  MVT::f32, false, false, 4);
6553   // Extend everything to 80 bits to force it to be done on x87.
6554   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6555   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6556 }
6557
6558 std::pair<SDValue,SDValue> X86TargetLowering::
6559 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6560   DebugLoc DL = Op.getDebugLoc();
6561
6562   EVT DstTy = Op.getValueType();
6563
6564   if (!IsSigned) {
6565     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6566     DstTy = MVT::i64;
6567   }
6568
6569   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6570          DstTy.getSimpleVT() >= MVT::i16 &&
6571          "Unknown FP_TO_SINT to lower!");
6572
6573   // These are really Legal.
6574   if (DstTy == MVT::i32 &&
6575       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6576     return std::make_pair(SDValue(), SDValue());
6577   if (Subtarget->is64Bit() &&
6578       DstTy == MVT::i64 &&
6579       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6580     return std::make_pair(SDValue(), SDValue());
6581
6582   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6583   // stack slot.
6584   MachineFunction &MF = DAG.getMachineFunction();
6585   unsigned MemSize = DstTy.getSizeInBits()/8;
6586   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6587   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6588
6589
6590
6591   unsigned Opc;
6592   switch (DstTy.getSimpleVT().SimpleTy) {
6593   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6594   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6595   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6596   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6597   }
6598
6599   SDValue Chain = DAG.getEntryNode();
6600   SDValue Value = Op.getOperand(0);
6601   EVT TheVT = Op.getOperand(0).getValueType();
6602   if (isScalarFPTypeInSSEReg(TheVT)) {
6603     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6604     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6605                          MachinePointerInfo::getFixedStack(SSFI),
6606                          false, false, 0);
6607     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6608     SDValue Ops[] = {
6609       Chain, StackSlot, DAG.getValueType(TheVT)
6610     };
6611
6612     MachineMemOperand *MMO =
6613       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6614                               MachineMemOperand::MOLoad, MemSize, MemSize);
6615     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6616                                     DstTy, MMO);
6617     Chain = Value.getValue(1);
6618     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6619     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6620   }
6621
6622   MachineMemOperand *MMO =
6623     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6624                             MachineMemOperand::MOStore, MemSize, MemSize);
6625
6626   // Build the FP_TO_INT*_IN_MEM
6627   SDValue Ops[] = { Chain, Value, StackSlot };
6628   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6629                                          Ops, 3, DstTy, MMO);
6630
6631   return std::make_pair(FIST, StackSlot);
6632 }
6633
6634 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6635                                            SelectionDAG &DAG) const {
6636   if (Op.getValueType().isVector())
6637     return SDValue();
6638
6639   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6640   SDValue FIST = Vals.first, StackSlot = Vals.second;
6641   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6642   if (FIST.getNode() == 0) return Op;
6643
6644   // Load the result.
6645   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6646                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6647 }
6648
6649 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6650                                            SelectionDAG &DAG) const {
6651   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6652   SDValue FIST = Vals.first, StackSlot = Vals.second;
6653   assert(FIST.getNode() && "Unexpected failure");
6654
6655   // Load the result.
6656   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6657                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6658 }
6659
6660 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6661                                      SelectionDAG &DAG) const {
6662   LLVMContext *Context = DAG.getContext();
6663   DebugLoc dl = Op.getDebugLoc();
6664   EVT VT = Op.getValueType();
6665   EVT EltVT = VT;
6666   if (VT.isVector())
6667     EltVT = VT.getVectorElementType();
6668   std::vector<Constant*> CV;
6669   if (EltVT == MVT::f64) {
6670     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6671     CV.push_back(C);
6672     CV.push_back(C);
6673   } else {
6674     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6675     CV.push_back(C);
6676     CV.push_back(C);
6677     CV.push_back(C);
6678     CV.push_back(C);
6679   }
6680   Constant *C = ConstantVector::get(CV);
6681   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6682   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6683                              MachinePointerInfo::getConstantPool(),
6684                              false, false, 16);
6685   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6686 }
6687
6688 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6689   LLVMContext *Context = DAG.getContext();
6690   DebugLoc dl = Op.getDebugLoc();
6691   EVT VT = Op.getValueType();
6692   EVT EltVT = VT;
6693   if (VT.isVector())
6694     EltVT = VT.getVectorElementType();
6695   std::vector<Constant*> CV;
6696   if (EltVT == MVT::f64) {
6697     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6698     CV.push_back(C);
6699     CV.push_back(C);
6700   } else {
6701     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6702     CV.push_back(C);
6703     CV.push_back(C);
6704     CV.push_back(C);
6705     CV.push_back(C);
6706   }
6707   Constant *C = ConstantVector::get(CV);
6708   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6709   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6710                              MachinePointerInfo::getConstantPool(),
6711                              false, false, 16);
6712   if (VT.isVector()) {
6713     return DAG.getNode(ISD::BITCAST, dl, VT,
6714                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6715                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6716                                 Op.getOperand(0)),
6717                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6718   } else {
6719     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6720   }
6721 }
6722
6723 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6724   LLVMContext *Context = DAG.getContext();
6725   SDValue Op0 = Op.getOperand(0);
6726   SDValue Op1 = Op.getOperand(1);
6727   DebugLoc dl = Op.getDebugLoc();
6728   EVT VT = Op.getValueType();
6729   EVT SrcVT = Op1.getValueType();
6730
6731   // If second operand is smaller, extend it first.
6732   if (SrcVT.bitsLT(VT)) {
6733     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6734     SrcVT = VT;
6735   }
6736   // And if it is bigger, shrink it first.
6737   if (SrcVT.bitsGT(VT)) {
6738     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6739     SrcVT = VT;
6740   }
6741
6742   // At this point the operands and the result should have the same
6743   // type, and that won't be f80 since that is not custom lowered.
6744
6745   // First get the sign bit of second operand.
6746   std::vector<Constant*> CV;
6747   if (SrcVT == MVT::f64) {
6748     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6749     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6750   } else {
6751     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6752     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6753     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6754     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6755   }
6756   Constant *C = ConstantVector::get(CV);
6757   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6758   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6759                               MachinePointerInfo::getConstantPool(),
6760                               false, false, 16);
6761   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6762
6763   // Shift sign bit right or left if the two operands have different types.
6764   if (SrcVT.bitsGT(VT)) {
6765     // Op0 is MVT::f32, Op1 is MVT::f64.
6766     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6767     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6768                           DAG.getConstant(32, MVT::i32));
6769     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6770     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6771                           DAG.getIntPtrConstant(0));
6772   }
6773
6774   // Clear first operand sign bit.
6775   CV.clear();
6776   if (VT == MVT::f64) {
6777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6778     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6779   } else {
6780     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6781     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6782     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6783     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6784   }
6785   C = ConstantVector::get(CV);
6786   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6787   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6788                               MachinePointerInfo::getConstantPool(),
6789                               false, false, 16);
6790   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6791
6792   // Or the value with the sign bit.
6793   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6794 }
6795
6796 /// Emit nodes that will be selected as "test Op0,Op0", or something
6797 /// equivalent.
6798 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6799                                     SelectionDAG &DAG) const {
6800   DebugLoc dl = Op.getDebugLoc();
6801
6802   // CF and OF aren't always set the way we want. Determine which
6803   // of these we need.
6804   bool NeedCF = false;
6805   bool NeedOF = false;
6806   switch (X86CC) {
6807   default: break;
6808   case X86::COND_A: case X86::COND_AE:
6809   case X86::COND_B: case X86::COND_BE:
6810     NeedCF = true;
6811     break;
6812   case X86::COND_G: case X86::COND_GE:
6813   case X86::COND_L: case X86::COND_LE:
6814   case X86::COND_O: case X86::COND_NO:
6815     NeedOF = true;
6816     break;
6817   }
6818
6819   // See if we can use the EFLAGS value from the operand instead of
6820   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6821   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6822   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6823     // Emit a CMP with 0, which is the TEST pattern.
6824     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6825                        DAG.getConstant(0, Op.getValueType()));
6826
6827   unsigned Opcode = 0;
6828   unsigned NumOperands = 0;
6829   switch (Op.getNode()->getOpcode()) {
6830   case ISD::ADD:
6831     // Due to an isel shortcoming, be conservative if this add is likely to be
6832     // selected as part of a load-modify-store instruction. When the root node
6833     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6834     // uses of other nodes in the match, such as the ADD in this case. This
6835     // leads to the ADD being left around and reselected, with the result being
6836     // two adds in the output.  Alas, even if none our users are stores, that
6837     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6838     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6839     // climbing the DAG back to the root, and it doesn't seem to be worth the
6840     // effort.
6841     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6842            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6843       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6844         goto default_case;
6845
6846     if (ConstantSDNode *C =
6847         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6848       // An add of one will be selected as an INC.
6849       if (C->getAPIntValue() == 1) {
6850         Opcode = X86ISD::INC;
6851         NumOperands = 1;
6852         break;
6853       }
6854
6855       // An add of negative one (subtract of one) will be selected as a DEC.
6856       if (C->getAPIntValue().isAllOnesValue()) {
6857         Opcode = X86ISD::DEC;
6858         NumOperands = 1;
6859         break;
6860       }
6861     }
6862
6863     // Otherwise use a regular EFLAGS-setting add.
6864     Opcode = X86ISD::ADD;
6865     NumOperands = 2;
6866     break;
6867   case ISD::AND: {
6868     // If the primary and result isn't used, don't bother using X86ISD::AND,
6869     // because a TEST instruction will be better.
6870     bool NonFlagUse = false;
6871     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6872            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6873       SDNode *User = *UI;
6874       unsigned UOpNo = UI.getOperandNo();
6875       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6876         // Look pass truncate.
6877         UOpNo = User->use_begin().getOperandNo();
6878         User = *User->use_begin();
6879       }
6880
6881       if (User->getOpcode() != ISD::BRCOND &&
6882           User->getOpcode() != ISD::SETCC &&
6883           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6884         NonFlagUse = true;
6885         break;
6886       }
6887     }
6888
6889     if (!NonFlagUse)
6890       break;
6891   }
6892     // FALL THROUGH
6893   case ISD::SUB:
6894   case ISD::OR:
6895   case ISD::XOR:
6896     // Due to the ISEL shortcoming noted above, be conservative if this op is
6897     // likely to be selected as part of a load-modify-store instruction.
6898     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6899            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6900       if (UI->getOpcode() == ISD::STORE)
6901         goto default_case;
6902
6903     // Otherwise use a regular EFLAGS-setting instruction.
6904     switch (Op.getNode()->getOpcode()) {
6905     default: llvm_unreachable("unexpected operator!");
6906     case ISD::SUB: Opcode = X86ISD::SUB; break;
6907     case ISD::OR:  Opcode = X86ISD::OR;  break;
6908     case ISD::XOR: Opcode = X86ISD::XOR; break;
6909     case ISD::AND: Opcode = X86ISD::AND; break;
6910     }
6911
6912     NumOperands = 2;
6913     break;
6914   case X86ISD::ADD:
6915   case X86ISD::SUB:
6916   case X86ISD::INC:
6917   case X86ISD::DEC:
6918   case X86ISD::OR:
6919   case X86ISD::XOR:
6920   case X86ISD::AND:
6921     return SDValue(Op.getNode(), 1);
6922   default:
6923   default_case:
6924     break;
6925   }
6926
6927   if (Opcode == 0)
6928     // Emit a CMP with 0, which is the TEST pattern.
6929     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6930                        DAG.getConstant(0, Op.getValueType()));
6931
6932   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6933   SmallVector<SDValue, 4> Ops;
6934   for (unsigned i = 0; i != NumOperands; ++i)
6935     Ops.push_back(Op.getOperand(i));
6936
6937   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6938   DAG.ReplaceAllUsesWith(Op, New);
6939   return SDValue(New.getNode(), 1);
6940 }
6941
6942 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6943 /// equivalent.
6944 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6945                                    SelectionDAG &DAG) const {
6946   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6947     if (C->getAPIntValue() == 0)
6948       return EmitTest(Op0, X86CC, DAG);
6949
6950   DebugLoc dl = Op0.getDebugLoc();
6951   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6952 }
6953
6954 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6955 /// if it's possible.
6956 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6957                                      DebugLoc dl, SelectionDAG &DAG) const {
6958   SDValue Op0 = And.getOperand(0);
6959   SDValue Op1 = And.getOperand(1);
6960   if (Op0.getOpcode() == ISD::TRUNCATE)
6961     Op0 = Op0.getOperand(0);
6962   if (Op1.getOpcode() == ISD::TRUNCATE)
6963     Op1 = Op1.getOperand(0);
6964
6965   SDValue LHS, RHS;
6966   if (Op1.getOpcode() == ISD::SHL)
6967     std::swap(Op0, Op1);
6968   if (Op0.getOpcode() == ISD::SHL) {
6969     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6970       if (And00C->getZExtValue() == 1) {
6971         // If we looked past a truncate, check that it's only truncating away
6972         // known zeros.
6973         unsigned BitWidth = Op0.getValueSizeInBits();
6974         unsigned AndBitWidth = And.getValueSizeInBits();
6975         if (BitWidth > AndBitWidth) {
6976           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6977           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6978           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6979             return SDValue();
6980         }
6981         LHS = Op1;
6982         RHS = Op0.getOperand(1);
6983       }
6984   } else if (Op1.getOpcode() == ISD::Constant) {
6985     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6986     SDValue AndLHS = Op0;
6987     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6988       LHS = AndLHS.getOperand(0);
6989       RHS = AndLHS.getOperand(1);
6990     }
6991   }
6992
6993   if (LHS.getNode()) {
6994     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6995     // instruction.  Since the shift amount is in-range-or-undefined, we know
6996     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6997     // the encoding for the i16 version is larger than the i32 version.
6998     // Also promote i16 to i32 for performance / code size reason.
6999     if (LHS.getValueType() == MVT::i8 ||
7000         LHS.getValueType() == MVT::i16)
7001       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7002
7003     // If the operand types disagree, extend the shift amount to match.  Since
7004     // BT ignores high bits (like shifts) we can use anyextend.
7005     if (LHS.getValueType() != RHS.getValueType())
7006       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7007
7008     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7009     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7010     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7011                        DAG.getConstant(Cond, MVT::i8), BT);
7012   }
7013
7014   return SDValue();
7015 }
7016
7017 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7018   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7019   SDValue Op0 = Op.getOperand(0);
7020   SDValue Op1 = Op.getOperand(1);
7021   DebugLoc dl = Op.getDebugLoc();
7022   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7023
7024   // Optimize to BT if possible.
7025   // Lower (X & (1 << N)) == 0 to BT(X, N).
7026   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7027   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7028   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7029       Op1.getOpcode() == ISD::Constant &&
7030       cast<ConstantSDNode>(Op1)->isNullValue() &&
7031       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7032     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7033     if (NewSetCC.getNode())
7034       return NewSetCC;
7035   }
7036
7037   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7038   // these.
7039   if (Op1.getOpcode() == ISD::Constant &&
7040       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7041        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7042       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7043  
7044     // If the input is a setcc, then reuse the input setcc or use a new one with
7045     // the inverted condition.
7046     if (Op0.getOpcode() == X86ISD::SETCC) {
7047       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7048       bool Invert = (CC == ISD::SETNE) ^
7049         cast<ConstantSDNode>(Op1)->isNullValue();
7050       if (!Invert) return Op0;
7051       
7052       CCode = X86::GetOppositeBranchCondition(CCode);
7053       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7054                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7055     }
7056   }
7057
7058   bool isFP = Op1.getValueType().isFloatingPoint();
7059   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7060   if (X86CC == X86::COND_INVALID)
7061     return SDValue();
7062
7063   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7064   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7065                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7066 }
7067
7068 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7069   SDValue Cond;
7070   SDValue Op0 = Op.getOperand(0);
7071   SDValue Op1 = Op.getOperand(1);
7072   SDValue CC = Op.getOperand(2);
7073   EVT VT = Op.getValueType();
7074   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7075   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7076   DebugLoc dl = Op.getDebugLoc();
7077
7078   if (isFP) {
7079     unsigned SSECC = 8;
7080     EVT VT0 = Op0.getValueType();
7081     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7082     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7083     bool Swap = false;
7084
7085     switch (SetCCOpcode) {
7086     default: break;
7087     case ISD::SETOEQ:
7088     case ISD::SETEQ:  SSECC = 0; break;
7089     case ISD::SETOGT:
7090     case ISD::SETGT: Swap = true; // Fallthrough
7091     case ISD::SETLT:
7092     case ISD::SETOLT: SSECC = 1; break;
7093     case ISD::SETOGE:
7094     case ISD::SETGE: Swap = true; // Fallthrough
7095     case ISD::SETLE:
7096     case ISD::SETOLE: SSECC = 2; break;
7097     case ISD::SETUO:  SSECC = 3; break;
7098     case ISD::SETUNE:
7099     case ISD::SETNE:  SSECC = 4; break;
7100     case ISD::SETULE: Swap = true;
7101     case ISD::SETUGE: SSECC = 5; break;
7102     case ISD::SETULT: Swap = true;
7103     case ISD::SETUGT: SSECC = 6; break;
7104     case ISD::SETO:   SSECC = 7; break;
7105     }
7106     if (Swap)
7107       std::swap(Op0, Op1);
7108
7109     // In the two special cases we can't handle, emit two comparisons.
7110     if (SSECC == 8) {
7111       if (SetCCOpcode == ISD::SETUEQ) {
7112         SDValue UNORD, EQ;
7113         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7114         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7115         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7116       }
7117       else if (SetCCOpcode == ISD::SETONE) {
7118         SDValue ORD, NEQ;
7119         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7120         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7121         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7122       }
7123       llvm_unreachable("Illegal FP comparison");
7124     }
7125     // Handle all other FP comparisons here.
7126     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7127   }
7128
7129   // We are handling one of the integer comparisons here.  Since SSE only has
7130   // GT and EQ comparisons for integer, swapping operands and multiple
7131   // operations may be required for some comparisons.
7132   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7133   bool Swap = false, Invert = false, FlipSigns = false;
7134
7135   switch (VT.getSimpleVT().SimpleTy) {
7136   default: break;
7137   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7138   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7139   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7140   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7141   }
7142
7143   switch (SetCCOpcode) {
7144   default: break;
7145   case ISD::SETNE:  Invert = true;
7146   case ISD::SETEQ:  Opc = EQOpc; break;
7147   case ISD::SETLT:  Swap = true;
7148   case ISD::SETGT:  Opc = GTOpc; break;
7149   case ISD::SETGE:  Swap = true;
7150   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7151   case ISD::SETULT: Swap = true;
7152   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7153   case ISD::SETUGE: Swap = true;
7154   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7155   }
7156   if (Swap)
7157     std::swap(Op0, Op1);
7158
7159   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7160   // bits of the inputs before performing those operations.
7161   if (FlipSigns) {
7162     EVT EltVT = VT.getVectorElementType();
7163     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7164                                       EltVT);
7165     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7166     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7167                                     SignBits.size());
7168     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7169     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7170   }
7171
7172   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7173
7174   // If the logical-not of the result is required, perform that now.
7175   if (Invert)
7176     Result = DAG.getNOT(dl, Result, VT);
7177
7178   return Result;
7179 }
7180
7181 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7182 static bool isX86LogicalCmp(SDValue Op) {
7183   unsigned Opc = Op.getNode()->getOpcode();
7184   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7185     return true;
7186   if (Op.getResNo() == 1 &&
7187       (Opc == X86ISD::ADD ||
7188        Opc == X86ISD::SUB ||
7189        Opc == X86ISD::ADC ||
7190        Opc == X86ISD::SBB ||
7191        Opc == X86ISD::SMUL ||
7192        Opc == X86ISD::UMUL ||
7193        Opc == X86ISD::INC ||
7194        Opc == X86ISD::DEC ||
7195        Opc == X86ISD::OR ||
7196        Opc == X86ISD::XOR ||
7197        Opc == X86ISD::AND))
7198     return true;
7199
7200   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7201     return true;
7202     
7203   return false;
7204 }
7205
7206 static bool isZero(SDValue V) {
7207   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7208   return C && C->isNullValue();
7209 }
7210
7211 static bool isAllOnes(SDValue V) {
7212   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7213   return C && C->isAllOnesValue();
7214 }
7215
7216 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7217   bool addTest = true;
7218   SDValue Cond  = Op.getOperand(0);
7219   SDValue Op1 = Op.getOperand(1);
7220   SDValue Op2 = Op.getOperand(2);
7221   DebugLoc DL = Op.getDebugLoc();
7222   SDValue CC;
7223
7224   if (Cond.getOpcode() == ISD::SETCC) {
7225     SDValue NewCond = LowerSETCC(Cond, DAG);
7226     if (NewCond.getNode())
7227       Cond = NewCond;
7228   }
7229
7230   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7231   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7232   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7233   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7234   if (Cond.getOpcode() == X86ISD::SETCC &&
7235       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7236       isZero(Cond.getOperand(1).getOperand(1))) {
7237     SDValue Cmp = Cond.getOperand(1);
7238     
7239     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7240     
7241     if ((isAllOnes(Op1) || isAllOnes(Op2)) && 
7242         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7243       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7244
7245       SDValue CmpOp0 = Cmp.getOperand(0);
7246       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7247                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7248       
7249       SDValue Res =   // Res = 0 or -1.
7250         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7251                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7252       
7253       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7254         Res = DAG.getNOT(DL, Res, Res.getValueType());
7255       
7256       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7257       if (N2C == 0 || !N2C->isNullValue())
7258         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7259       return Res;
7260     }
7261   }
7262
7263   // Look past (and (setcc_carry (cmp ...)), 1).
7264   if (Cond.getOpcode() == ISD::AND &&
7265       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7266     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7267     if (C && C->getAPIntValue() == 1)
7268       Cond = Cond.getOperand(0);
7269   }
7270
7271   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7272   // setting operand in place of the X86ISD::SETCC.
7273   if (Cond.getOpcode() == X86ISD::SETCC ||
7274       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7275     CC = Cond.getOperand(0);
7276
7277     SDValue Cmp = Cond.getOperand(1);
7278     unsigned Opc = Cmp.getOpcode();
7279     EVT VT = Op.getValueType();
7280
7281     bool IllegalFPCMov = false;
7282     if (VT.isFloatingPoint() && !VT.isVector() &&
7283         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7284       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7285
7286     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7287         Opc == X86ISD::BT) { // FIXME
7288       Cond = Cmp;
7289       addTest = false;
7290     }
7291   }
7292
7293   if (addTest) {
7294     // Look pass the truncate.
7295     if (Cond.getOpcode() == ISD::TRUNCATE)
7296       Cond = Cond.getOperand(0);
7297
7298     // We know the result of AND is compared against zero. Try to match
7299     // it to BT.
7300     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7301       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7302       if (NewSetCC.getNode()) {
7303         CC = NewSetCC.getOperand(0);
7304         Cond = NewSetCC.getOperand(1);
7305         addTest = false;
7306       }
7307     }
7308   }
7309
7310   if (addTest) {
7311     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7312     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7313   }
7314
7315   // a <  b ? -1 :  0 -> RES = ~setcc_carry
7316   // a <  b ?  0 : -1 -> RES = setcc_carry
7317   // a >= b ? -1 :  0 -> RES = setcc_carry
7318   // a >= b ?  0 : -1 -> RES = ~setcc_carry
7319   if (Cond.getOpcode() == X86ISD::CMP) {
7320     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
7321
7322     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
7323         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
7324       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7325                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
7326       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
7327         return DAG.getNOT(DL, Res, Res.getValueType());
7328       return Res;
7329     }
7330   }
7331
7332   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7333   // condition is true.
7334   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7335   SDValue Ops[] = { Op2, Op1, CC, Cond };
7336   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7337 }
7338
7339 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7340 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7341 // from the AND / OR.
7342 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7343   Opc = Op.getOpcode();
7344   if (Opc != ISD::OR && Opc != ISD::AND)
7345     return false;
7346   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7347           Op.getOperand(0).hasOneUse() &&
7348           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7349           Op.getOperand(1).hasOneUse());
7350 }
7351
7352 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7353 // 1 and that the SETCC node has a single use.
7354 static bool isXor1OfSetCC(SDValue Op) {
7355   if (Op.getOpcode() != ISD::XOR)
7356     return false;
7357   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7358   if (N1C && N1C->getAPIntValue() == 1) {
7359     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7360       Op.getOperand(0).hasOneUse();
7361   }
7362   return false;
7363 }
7364
7365 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7366   bool addTest = true;
7367   SDValue Chain = Op.getOperand(0);
7368   SDValue Cond  = Op.getOperand(1);
7369   SDValue Dest  = Op.getOperand(2);
7370   DebugLoc dl = Op.getDebugLoc();
7371   SDValue CC;
7372
7373   if (Cond.getOpcode() == ISD::SETCC) {
7374     SDValue NewCond = LowerSETCC(Cond, DAG);
7375     if (NewCond.getNode())
7376       Cond = NewCond;
7377   }
7378 #if 0
7379   // FIXME: LowerXALUO doesn't handle these!!
7380   else if (Cond.getOpcode() == X86ISD::ADD  ||
7381            Cond.getOpcode() == X86ISD::SUB  ||
7382            Cond.getOpcode() == X86ISD::SMUL ||
7383            Cond.getOpcode() == X86ISD::UMUL)
7384     Cond = LowerXALUO(Cond, DAG);
7385 #endif
7386
7387   // Look pass (and (setcc_carry (cmp ...)), 1).
7388   if (Cond.getOpcode() == ISD::AND &&
7389       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7390     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7391     if (C && C->getAPIntValue() == 1)
7392       Cond = Cond.getOperand(0);
7393   }
7394
7395   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7396   // setting operand in place of the X86ISD::SETCC.
7397   if (Cond.getOpcode() == X86ISD::SETCC ||
7398       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7399     CC = Cond.getOperand(0);
7400
7401     SDValue Cmp = Cond.getOperand(1);
7402     unsigned Opc = Cmp.getOpcode();
7403     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7404     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7405       Cond = Cmp;
7406       addTest = false;
7407     } else {
7408       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7409       default: break;
7410       case X86::COND_O:
7411       case X86::COND_B:
7412         // These can only come from an arithmetic instruction with overflow,
7413         // e.g. SADDO, UADDO.
7414         Cond = Cond.getNode()->getOperand(1);
7415         addTest = false;
7416         break;
7417       }
7418     }
7419   } else {
7420     unsigned CondOpc;
7421     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7422       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7423       if (CondOpc == ISD::OR) {
7424         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7425         // two branches instead of an explicit OR instruction with a
7426         // separate test.
7427         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7428             isX86LogicalCmp(Cmp)) {
7429           CC = Cond.getOperand(0).getOperand(0);
7430           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7431                               Chain, Dest, CC, Cmp);
7432           CC = Cond.getOperand(1).getOperand(0);
7433           Cond = Cmp;
7434           addTest = false;
7435         }
7436       } else { // ISD::AND
7437         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7438         // two branches instead of an explicit AND instruction with a
7439         // separate test. However, we only do this if this block doesn't
7440         // have a fall-through edge, because this requires an explicit
7441         // jmp when the condition is false.
7442         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7443             isX86LogicalCmp(Cmp) &&
7444             Op.getNode()->hasOneUse()) {
7445           X86::CondCode CCode =
7446             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7447           CCode = X86::GetOppositeBranchCondition(CCode);
7448           CC = DAG.getConstant(CCode, MVT::i8);
7449           SDNode *User = *Op.getNode()->use_begin();
7450           // Look for an unconditional branch following this conditional branch.
7451           // We need this because we need to reverse the successors in order
7452           // to implement FCMP_OEQ.
7453           if (User->getOpcode() == ISD::BR) {
7454             SDValue FalseBB = User->getOperand(1);
7455             SDNode *NewBR =
7456               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7457             assert(NewBR == User);
7458             (void)NewBR;
7459             Dest = FalseBB;
7460
7461             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7462                                 Chain, Dest, CC, Cmp);
7463             X86::CondCode CCode =
7464               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7465             CCode = X86::GetOppositeBranchCondition(CCode);
7466             CC = DAG.getConstant(CCode, MVT::i8);
7467             Cond = Cmp;
7468             addTest = false;
7469           }
7470         }
7471       }
7472     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7473       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7474       // It should be transformed during dag combiner except when the condition
7475       // is set by a arithmetics with overflow node.
7476       X86::CondCode CCode =
7477         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7478       CCode = X86::GetOppositeBranchCondition(CCode);
7479       CC = DAG.getConstant(CCode, MVT::i8);
7480       Cond = Cond.getOperand(0).getOperand(1);
7481       addTest = false;
7482     }
7483   }
7484
7485   if (addTest) {
7486     // Look pass the truncate.
7487     if (Cond.getOpcode() == ISD::TRUNCATE)
7488       Cond = Cond.getOperand(0);
7489
7490     // We know the result of AND is compared against zero. Try to match
7491     // it to BT.
7492     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7493       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7494       if (NewSetCC.getNode()) {
7495         CC = NewSetCC.getOperand(0);
7496         Cond = NewSetCC.getOperand(1);
7497         addTest = false;
7498       }
7499     }
7500   }
7501
7502   if (addTest) {
7503     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7504     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7505   }
7506   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7507                      Chain, Dest, CC, Cond);
7508 }
7509
7510
7511 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7512 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7513 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7514 // that the guard pages used by the OS virtual memory manager are allocated in
7515 // correct sequence.
7516 SDValue
7517 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7518                                            SelectionDAG &DAG) const {
7519   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7520          "This should be used only on Windows targets");
7521   DebugLoc dl = Op.getDebugLoc();
7522
7523   // Get the inputs.
7524   SDValue Chain = Op.getOperand(0);
7525   SDValue Size  = Op.getOperand(1);
7526   // FIXME: Ensure alignment here
7527
7528   SDValue Flag;
7529
7530   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7531
7532   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7533   Flag = Chain.getValue(1);
7534
7535   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7536
7537   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7538   Flag = Chain.getValue(1);
7539
7540   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7541
7542   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7543   return DAG.getMergeValues(Ops1, 2, dl);
7544 }
7545
7546 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7547   MachineFunction &MF = DAG.getMachineFunction();
7548   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7549
7550   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7551   DebugLoc DL = Op.getDebugLoc();
7552
7553   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7554     // vastart just stores the address of the VarArgsFrameIndex slot into the
7555     // memory location argument.
7556     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7557                                    getPointerTy());
7558     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7559                         MachinePointerInfo(SV), false, false, 0);
7560   }
7561
7562   // __va_list_tag:
7563   //   gp_offset         (0 - 6 * 8)
7564   //   fp_offset         (48 - 48 + 8 * 16)
7565   //   overflow_arg_area (point to parameters coming in memory).
7566   //   reg_save_area
7567   SmallVector<SDValue, 8> MemOps;
7568   SDValue FIN = Op.getOperand(1);
7569   // Store gp_offset
7570   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7571                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7572                                                MVT::i32),
7573                                FIN, MachinePointerInfo(SV), false, false, 0);
7574   MemOps.push_back(Store);
7575
7576   // Store fp_offset
7577   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7578                     FIN, DAG.getIntPtrConstant(4));
7579   Store = DAG.getStore(Op.getOperand(0), DL,
7580                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7581                                        MVT::i32),
7582                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7583   MemOps.push_back(Store);
7584
7585   // Store ptr to overflow_arg_area
7586   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7587                     FIN, DAG.getIntPtrConstant(4));
7588   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7589                                     getPointerTy());
7590   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7591                        MachinePointerInfo(SV, 8),
7592                        false, false, 0);
7593   MemOps.push_back(Store);
7594
7595   // Store ptr to reg_save_area.
7596   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7597                     FIN, DAG.getIntPtrConstant(8));
7598   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7599                                     getPointerTy());
7600   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7601                        MachinePointerInfo(SV, 16), false, false, 0);
7602   MemOps.push_back(Store);
7603   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7604                      &MemOps[0], MemOps.size());
7605 }
7606
7607 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7608   assert(Subtarget->is64Bit() &&
7609          "LowerVAARG only handles 64-bit va_arg!");
7610   assert((Subtarget->isTargetLinux() ||
7611           Subtarget->isTargetDarwin()) &&
7612           "Unhandled target in LowerVAARG");
7613   assert(Op.getNode()->getNumOperands() == 4);
7614   SDValue Chain = Op.getOperand(0);
7615   SDValue SrcPtr = Op.getOperand(1);
7616   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7617   unsigned Align = Op.getConstantOperandVal(3);
7618   DebugLoc dl = Op.getDebugLoc();
7619
7620   EVT ArgVT = Op.getNode()->getValueType(0);
7621   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7622   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7623   uint8_t ArgMode;
7624
7625   // Decide which area this value should be read from.
7626   // TODO: Implement the AMD64 ABI in its entirety. This simple
7627   // selection mechanism works only for the basic types.
7628   if (ArgVT == MVT::f80) {
7629     llvm_unreachable("va_arg for f80 not yet implemented");
7630   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7631     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7632   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7633     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7634   } else {
7635     llvm_unreachable("Unhandled argument type in LowerVAARG");
7636   }
7637
7638   if (ArgMode == 2) {
7639     // Sanity Check: Make sure using fp_offset makes sense.
7640     assert(!UseSoftFloat &&
7641            !(DAG.getMachineFunction()
7642                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7643            Subtarget->hasXMM());
7644   }
7645
7646   // Insert VAARG_64 node into the DAG
7647   // VAARG_64 returns two values: Variable Argument Address, Chain
7648   SmallVector<SDValue, 11> InstOps;
7649   InstOps.push_back(Chain);
7650   InstOps.push_back(SrcPtr);
7651   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7652   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7653   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7654   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7655   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7656                                           VTs, &InstOps[0], InstOps.size(),
7657                                           MVT::i64,
7658                                           MachinePointerInfo(SV),
7659                                           /*Align=*/0,
7660                                           /*Volatile=*/false,
7661                                           /*ReadMem=*/true,
7662                                           /*WriteMem=*/true);
7663   Chain = VAARG.getValue(1);
7664
7665   // Load the next argument and return it
7666   return DAG.getLoad(ArgVT, dl,
7667                      Chain,
7668                      VAARG,
7669                      MachinePointerInfo(),
7670                      false, false, 0);
7671 }
7672
7673 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7674   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7675   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7676   SDValue Chain = Op.getOperand(0);
7677   SDValue DstPtr = Op.getOperand(1);
7678   SDValue SrcPtr = Op.getOperand(2);
7679   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7680   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7681   DebugLoc DL = Op.getDebugLoc();
7682
7683   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7684                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7685                        false,
7686                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7687 }
7688
7689 SDValue
7690 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7691   DebugLoc dl = Op.getDebugLoc();
7692   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7693   switch (IntNo) {
7694   default: return SDValue();    // Don't custom lower most intrinsics.
7695   // Comparison intrinsics.
7696   case Intrinsic::x86_sse_comieq_ss:
7697   case Intrinsic::x86_sse_comilt_ss:
7698   case Intrinsic::x86_sse_comile_ss:
7699   case Intrinsic::x86_sse_comigt_ss:
7700   case Intrinsic::x86_sse_comige_ss:
7701   case Intrinsic::x86_sse_comineq_ss:
7702   case Intrinsic::x86_sse_ucomieq_ss:
7703   case Intrinsic::x86_sse_ucomilt_ss:
7704   case Intrinsic::x86_sse_ucomile_ss:
7705   case Intrinsic::x86_sse_ucomigt_ss:
7706   case Intrinsic::x86_sse_ucomige_ss:
7707   case Intrinsic::x86_sse_ucomineq_ss:
7708   case Intrinsic::x86_sse2_comieq_sd:
7709   case Intrinsic::x86_sse2_comilt_sd:
7710   case Intrinsic::x86_sse2_comile_sd:
7711   case Intrinsic::x86_sse2_comigt_sd:
7712   case Intrinsic::x86_sse2_comige_sd:
7713   case Intrinsic::x86_sse2_comineq_sd:
7714   case Intrinsic::x86_sse2_ucomieq_sd:
7715   case Intrinsic::x86_sse2_ucomilt_sd:
7716   case Intrinsic::x86_sse2_ucomile_sd:
7717   case Intrinsic::x86_sse2_ucomigt_sd:
7718   case Intrinsic::x86_sse2_ucomige_sd:
7719   case Intrinsic::x86_sse2_ucomineq_sd: {
7720     unsigned Opc = 0;
7721     ISD::CondCode CC = ISD::SETCC_INVALID;
7722     switch (IntNo) {
7723     default: break;
7724     case Intrinsic::x86_sse_comieq_ss:
7725     case Intrinsic::x86_sse2_comieq_sd:
7726       Opc = X86ISD::COMI;
7727       CC = ISD::SETEQ;
7728       break;
7729     case Intrinsic::x86_sse_comilt_ss:
7730     case Intrinsic::x86_sse2_comilt_sd:
7731       Opc = X86ISD::COMI;
7732       CC = ISD::SETLT;
7733       break;
7734     case Intrinsic::x86_sse_comile_ss:
7735     case Intrinsic::x86_sse2_comile_sd:
7736       Opc = X86ISD::COMI;
7737       CC = ISD::SETLE;
7738       break;
7739     case Intrinsic::x86_sse_comigt_ss:
7740     case Intrinsic::x86_sse2_comigt_sd:
7741       Opc = X86ISD::COMI;
7742       CC = ISD::SETGT;
7743       break;
7744     case Intrinsic::x86_sse_comige_ss:
7745     case Intrinsic::x86_sse2_comige_sd:
7746       Opc = X86ISD::COMI;
7747       CC = ISD::SETGE;
7748       break;
7749     case Intrinsic::x86_sse_comineq_ss:
7750     case Intrinsic::x86_sse2_comineq_sd:
7751       Opc = X86ISD::COMI;
7752       CC = ISD::SETNE;
7753       break;
7754     case Intrinsic::x86_sse_ucomieq_ss:
7755     case Intrinsic::x86_sse2_ucomieq_sd:
7756       Opc = X86ISD::UCOMI;
7757       CC = ISD::SETEQ;
7758       break;
7759     case Intrinsic::x86_sse_ucomilt_ss:
7760     case Intrinsic::x86_sse2_ucomilt_sd:
7761       Opc = X86ISD::UCOMI;
7762       CC = ISD::SETLT;
7763       break;
7764     case Intrinsic::x86_sse_ucomile_ss:
7765     case Intrinsic::x86_sse2_ucomile_sd:
7766       Opc = X86ISD::UCOMI;
7767       CC = ISD::SETLE;
7768       break;
7769     case Intrinsic::x86_sse_ucomigt_ss:
7770     case Intrinsic::x86_sse2_ucomigt_sd:
7771       Opc = X86ISD::UCOMI;
7772       CC = ISD::SETGT;
7773       break;
7774     case Intrinsic::x86_sse_ucomige_ss:
7775     case Intrinsic::x86_sse2_ucomige_sd:
7776       Opc = X86ISD::UCOMI;
7777       CC = ISD::SETGE;
7778       break;
7779     case Intrinsic::x86_sse_ucomineq_ss:
7780     case Intrinsic::x86_sse2_ucomineq_sd:
7781       Opc = X86ISD::UCOMI;
7782       CC = ISD::SETNE;
7783       break;
7784     }
7785
7786     SDValue LHS = Op.getOperand(1);
7787     SDValue RHS = Op.getOperand(2);
7788     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7789     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7790     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7791     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7792                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7793     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7794   }
7795   // ptest and testp intrinsics. The intrinsic these come from are designed to
7796   // return an integer value, not just an instruction so lower it to the ptest
7797   // or testp pattern and a setcc for the result.
7798   case Intrinsic::x86_sse41_ptestz:
7799   case Intrinsic::x86_sse41_ptestc:
7800   case Intrinsic::x86_sse41_ptestnzc:
7801   case Intrinsic::x86_avx_ptestz_256:
7802   case Intrinsic::x86_avx_ptestc_256:
7803   case Intrinsic::x86_avx_ptestnzc_256:
7804   case Intrinsic::x86_avx_vtestz_ps:
7805   case Intrinsic::x86_avx_vtestc_ps:
7806   case Intrinsic::x86_avx_vtestnzc_ps:
7807   case Intrinsic::x86_avx_vtestz_pd:
7808   case Intrinsic::x86_avx_vtestc_pd:
7809   case Intrinsic::x86_avx_vtestnzc_pd:
7810   case Intrinsic::x86_avx_vtestz_ps_256:
7811   case Intrinsic::x86_avx_vtestc_ps_256:
7812   case Intrinsic::x86_avx_vtestnzc_ps_256:
7813   case Intrinsic::x86_avx_vtestz_pd_256:
7814   case Intrinsic::x86_avx_vtestc_pd_256:
7815   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7816     bool IsTestPacked = false;
7817     unsigned X86CC = 0;
7818     switch (IntNo) {
7819     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7820     case Intrinsic::x86_avx_vtestz_ps:
7821     case Intrinsic::x86_avx_vtestz_pd:
7822     case Intrinsic::x86_avx_vtestz_ps_256:
7823     case Intrinsic::x86_avx_vtestz_pd_256:
7824       IsTestPacked = true; // Fallthrough
7825     case Intrinsic::x86_sse41_ptestz:
7826     case Intrinsic::x86_avx_ptestz_256:
7827       // ZF = 1
7828       X86CC = X86::COND_E;
7829       break;
7830     case Intrinsic::x86_avx_vtestc_ps:
7831     case Intrinsic::x86_avx_vtestc_pd:
7832     case Intrinsic::x86_avx_vtestc_ps_256:
7833     case Intrinsic::x86_avx_vtestc_pd_256:
7834       IsTestPacked = true; // Fallthrough
7835     case Intrinsic::x86_sse41_ptestc:
7836     case Intrinsic::x86_avx_ptestc_256:
7837       // CF = 1
7838       X86CC = X86::COND_B;
7839       break;
7840     case Intrinsic::x86_avx_vtestnzc_ps:
7841     case Intrinsic::x86_avx_vtestnzc_pd:
7842     case Intrinsic::x86_avx_vtestnzc_ps_256:
7843     case Intrinsic::x86_avx_vtestnzc_pd_256:
7844       IsTestPacked = true; // Fallthrough
7845     case Intrinsic::x86_sse41_ptestnzc:
7846     case Intrinsic::x86_avx_ptestnzc_256:
7847       // ZF and CF = 0
7848       X86CC = X86::COND_A;
7849       break;
7850     }
7851
7852     SDValue LHS = Op.getOperand(1);
7853     SDValue RHS = Op.getOperand(2);
7854     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7855     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7856     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7857     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7858     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7859   }
7860
7861   // Fix vector shift instructions where the last operand is a non-immediate
7862   // i32 value.
7863   case Intrinsic::x86_sse2_pslli_w:
7864   case Intrinsic::x86_sse2_pslli_d:
7865   case Intrinsic::x86_sse2_pslli_q:
7866   case Intrinsic::x86_sse2_psrli_w:
7867   case Intrinsic::x86_sse2_psrli_d:
7868   case Intrinsic::x86_sse2_psrli_q:
7869   case Intrinsic::x86_sse2_psrai_w:
7870   case Intrinsic::x86_sse2_psrai_d:
7871   case Intrinsic::x86_mmx_pslli_w:
7872   case Intrinsic::x86_mmx_pslli_d:
7873   case Intrinsic::x86_mmx_pslli_q:
7874   case Intrinsic::x86_mmx_psrli_w:
7875   case Intrinsic::x86_mmx_psrli_d:
7876   case Intrinsic::x86_mmx_psrli_q:
7877   case Intrinsic::x86_mmx_psrai_w:
7878   case Intrinsic::x86_mmx_psrai_d: {
7879     SDValue ShAmt = Op.getOperand(2);
7880     if (isa<ConstantSDNode>(ShAmt))
7881       return SDValue();
7882
7883     unsigned NewIntNo = 0;
7884     EVT ShAmtVT = MVT::v4i32;
7885     switch (IntNo) {
7886     case Intrinsic::x86_sse2_pslli_w:
7887       NewIntNo = Intrinsic::x86_sse2_psll_w;
7888       break;
7889     case Intrinsic::x86_sse2_pslli_d:
7890       NewIntNo = Intrinsic::x86_sse2_psll_d;
7891       break;
7892     case Intrinsic::x86_sse2_pslli_q:
7893       NewIntNo = Intrinsic::x86_sse2_psll_q;
7894       break;
7895     case Intrinsic::x86_sse2_psrli_w:
7896       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7897       break;
7898     case Intrinsic::x86_sse2_psrli_d:
7899       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7900       break;
7901     case Intrinsic::x86_sse2_psrli_q:
7902       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7903       break;
7904     case Intrinsic::x86_sse2_psrai_w:
7905       NewIntNo = Intrinsic::x86_sse2_psra_w;
7906       break;
7907     case Intrinsic::x86_sse2_psrai_d:
7908       NewIntNo = Intrinsic::x86_sse2_psra_d;
7909       break;
7910     default: {
7911       ShAmtVT = MVT::v2i32;
7912       switch (IntNo) {
7913       case Intrinsic::x86_mmx_pslli_w:
7914         NewIntNo = Intrinsic::x86_mmx_psll_w;
7915         break;
7916       case Intrinsic::x86_mmx_pslli_d:
7917         NewIntNo = Intrinsic::x86_mmx_psll_d;
7918         break;
7919       case Intrinsic::x86_mmx_pslli_q:
7920         NewIntNo = Intrinsic::x86_mmx_psll_q;
7921         break;
7922       case Intrinsic::x86_mmx_psrli_w:
7923         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7924         break;
7925       case Intrinsic::x86_mmx_psrli_d:
7926         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7927         break;
7928       case Intrinsic::x86_mmx_psrli_q:
7929         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7930         break;
7931       case Intrinsic::x86_mmx_psrai_w:
7932         NewIntNo = Intrinsic::x86_mmx_psra_w;
7933         break;
7934       case Intrinsic::x86_mmx_psrai_d:
7935         NewIntNo = Intrinsic::x86_mmx_psra_d;
7936         break;
7937       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7938       }
7939       break;
7940     }
7941     }
7942
7943     // The vector shift intrinsics with scalars uses 32b shift amounts but
7944     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7945     // to be zero.
7946     SDValue ShOps[4];
7947     ShOps[0] = ShAmt;
7948     ShOps[1] = DAG.getConstant(0, MVT::i32);
7949     if (ShAmtVT == MVT::v4i32) {
7950       ShOps[2] = DAG.getUNDEF(MVT::i32);
7951       ShOps[3] = DAG.getUNDEF(MVT::i32);
7952       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7953     } else {
7954       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7955 // FIXME this must be lowered to get rid of the invalid type.
7956     }
7957
7958     EVT VT = Op.getValueType();
7959     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7960     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7961                        DAG.getConstant(NewIntNo, MVT::i32),
7962                        Op.getOperand(1), ShAmt);
7963   }
7964   }
7965 }
7966
7967 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7968                                            SelectionDAG &DAG) const {
7969   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7970   MFI->setReturnAddressIsTaken(true);
7971
7972   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7973   DebugLoc dl = Op.getDebugLoc();
7974
7975   if (Depth > 0) {
7976     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7977     SDValue Offset =
7978       DAG.getConstant(TD->getPointerSize(),
7979                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7980     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7981                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7982                                    FrameAddr, Offset),
7983                        MachinePointerInfo(), false, false, 0);
7984   }
7985
7986   // Just load the return address.
7987   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7988   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7989                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7990 }
7991
7992 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7993   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7994   MFI->setFrameAddressIsTaken(true);
7995
7996   EVT VT = Op.getValueType();
7997   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7998   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7999   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
8000   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
8001   while (Depth--)
8002     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
8003                             MachinePointerInfo(),
8004                             false, false, 0);
8005   return FrameAddr;
8006 }
8007
8008 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8009                                                      SelectionDAG &DAG) const {
8010   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8011 }
8012
8013 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8014   MachineFunction &MF = DAG.getMachineFunction();
8015   SDValue Chain     = Op.getOperand(0);
8016   SDValue Offset    = Op.getOperand(1);
8017   SDValue Handler   = Op.getOperand(2);
8018   DebugLoc dl       = Op.getDebugLoc();
8019
8020   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8021                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8022                                      getPointerTy());
8023   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8024
8025   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8026                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8027   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8028   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8029                        false, false, 0);
8030   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8031   MF.getRegInfo().addLiveOut(StoreAddrReg);
8032
8033   return DAG.getNode(X86ISD::EH_RETURN, dl,
8034                      MVT::Other,
8035                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8036 }
8037
8038 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8039                                              SelectionDAG &DAG) const {
8040   SDValue Root = Op.getOperand(0);
8041   SDValue Trmp = Op.getOperand(1); // trampoline
8042   SDValue FPtr = Op.getOperand(2); // nested function
8043   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8044   DebugLoc dl  = Op.getDebugLoc();
8045
8046   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8047
8048   if (Subtarget->is64Bit()) {
8049     SDValue OutChains[6];
8050
8051     // Large code-model.
8052     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8053     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8054
8055     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8056     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8057
8058     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8059
8060     // Load the pointer to the nested function into R11.
8061     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8062     SDValue Addr = Trmp;
8063     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8064                                 Addr, MachinePointerInfo(TrmpAddr),
8065                                 false, false, 0);
8066
8067     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8068                        DAG.getConstant(2, MVT::i64));
8069     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8070                                 MachinePointerInfo(TrmpAddr, 2),
8071                                 false, false, 2);
8072
8073     // Load the 'nest' parameter value into R10.
8074     // R10 is specified in X86CallingConv.td
8075     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8076     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8077                        DAG.getConstant(10, MVT::i64));
8078     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8079                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8080                                 false, false, 0);
8081
8082     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8083                        DAG.getConstant(12, MVT::i64));
8084     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8085                                 MachinePointerInfo(TrmpAddr, 12),
8086                                 false, false, 2);
8087
8088     // Jump to the nested function.
8089     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8090     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8091                        DAG.getConstant(20, MVT::i64));
8092     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8093                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8094                                 false, false, 0);
8095
8096     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8097     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8098                        DAG.getConstant(22, MVT::i64));
8099     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8100                                 MachinePointerInfo(TrmpAddr, 22),
8101                                 false, false, 0);
8102
8103     SDValue Ops[] =
8104       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8105     return DAG.getMergeValues(Ops, 2, dl);
8106   } else {
8107     const Function *Func =
8108       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8109     CallingConv::ID CC = Func->getCallingConv();
8110     unsigned NestReg;
8111
8112     switch (CC) {
8113     default:
8114       llvm_unreachable("Unsupported calling convention");
8115     case CallingConv::C:
8116     case CallingConv::X86_StdCall: {
8117       // Pass 'nest' parameter in ECX.
8118       // Must be kept in sync with X86CallingConv.td
8119       NestReg = X86::ECX;
8120
8121       // Check that ECX wasn't needed by an 'inreg' parameter.
8122       const FunctionType *FTy = Func->getFunctionType();
8123       const AttrListPtr &Attrs = Func->getAttributes();
8124
8125       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8126         unsigned InRegCount = 0;
8127         unsigned Idx = 1;
8128
8129         for (FunctionType::param_iterator I = FTy->param_begin(),
8130              E = FTy->param_end(); I != E; ++I, ++Idx)
8131           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8132             // FIXME: should only count parameters that are lowered to integers.
8133             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8134
8135         if (InRegCount > 2) {
8136           report_fatal_error("Nest register in use - reduce number of inreg"
8137                              " parameters!");
8138         }
8139       }
8140       break;
8141     }
8142     case CallingConv::X86_FastCall:
8143     case CallingConv::X86_ThisCall:
8144     case CallingConv::Fast:
8145       // Pass 'nest' parameter in EAX.
8146       // Must be kept in sync with X86CallingConv.td
8147       NestReg = X86::EAX;
8148       break;
8149     }
8150
8151     SDValue OutChains[4];
8152     SDValue Addr, Disp;
8153
8154     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8155                        DAG.getConstant(10, MVT::i32));
8156     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8157
8158     // This is storing the opcode for MOV32ri.
8159     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8160     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8161     OutChains[0] = DAG.getStore(Root, dl,
8162                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8163                                 Trmp, MachinePointerInfo(TrmpAddr),
8164                                 false, false, 0);
8165
8166     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8167                        DAG.getConstant(1, MVT::i32));
8168     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8169                                 MachinePointerInfo(TrmpAddr, 1),
8170                                 false, false, 1);
8171
8172     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8173     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8174                        DAG.getConstant(5, MVT::i32));
8175     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8176                                 MachinePointerInfo(TrmpAddr, 5),
8177                                 false, false, 1);
8178
8179     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8180                        DAG.getConstant(6, MVT::i32));
8181     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8182                                 MachinePointerInfo(TrmpAddr, 6),
8183                                 false, false, 1);
8184
8185     SDValue Ops[] =
8186       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8187     return DAG.getMergeValues(Ops, 2, dl);
8188   }
8189 }
8190
8191 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8192                                             SelectionDAG &DAG) const {
8193   /*
8194    The rounding mode is in bits 11:10 of FPSR, and has the following
8195    settings:
8196      00 Round to nearest
8197      01 Round to -inf
8198      10 Round to +inf
8199      11 Round to 0
8200
8201   FLT_ROUNDS, on the other hand, expects the following:
8202     -1 Undefined
8203      0 Round to 0
8204      1 Round to nearest
8205      2 Round to +inf
8206      3 Round to -inf
8207
8208   To perform the conversion, we do:
8209     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8210   */
8211
8212   MachineFunction &MF = DAG.getMachineFunction();
8213   const TargetMachine &TM = MF.getTarget();
8214   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8215   unsigned StackAlignment = TFI.getStackAlignment();
8216   EVT VT = Op.getValueType();
8217   DebugLoc DL = Op.getDebugLoc();
8218
8219   // Save FP Control Word to stack slot
8220   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8221   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8222
8223
8224   MachineMemOperand *MMO =
8225    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8226                            MachineMemOperand::MOStore, 2, 2);
8227
8228   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8229   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8230                                           DAG.getVTList(MVT::Other),
8231                                           Ops, 2, MVT::i16, MMO);
8232
8233   // Load FP Control Word from stack slot
8234   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8235                             MachinePointerInfo(), false, false, 0);
8236
8237   // Transform as necessary
8238   SDValue CWD1 =
8239     DAG.getNode(ISD::SRL, DL, MVT::i16,
8240                 DAG.getNode(ISD::AND, DL, MVT::i16,
8241                             CWD, DAG.getConstant(0x800, MVT::i16)),
8242                 DAG.getConstant(11, MVT::i8));
8243   SDValue CWD2 =
8244     DAG.getNode(ISD::SRL, DL, MVT::i16,
8245                 DAG.getNode(ISD::AND, DL, MVT::i16,
8246                             CWD, DAG.getConstant(0x400, MVT::i16)),
8247                 DAG.getConstant(9, MVT::i8));
8248
8249   SDValue RetVal =
8250     DAG.getNode(ISD::AND, DL, MVT::i16,
8251                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8252                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8253                             DAG.getConstant(1, MVT::i16)),
8254                 DAG.getConstant(3, MVT::i16));
8255
8256
8257   return DAG.getNode((VT.getSizeInBits() < 16 ?
8258                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8259 }
8260
8261 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8262   EVT VT = Op.getValueType();
8263   EVT OpVT = VT;
8264   unsigned NumBits = VT.getSizeInBits();
8265   DebugLoc dl = Op.getDebugLoc();
8266
8267   Op = Op.getOperand(0);
8268   if (VT == MVT::i8) {
8269     // Zero extend to i32 since there is not an i8 bsr.
8270     OpVT = MVT::i32;
8271     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8272   }
8273
8274   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8275   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8276   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8277
8278   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8279   SDValue Ops[] = {
8280     Op,
8281     DAG.getConstant(NumBits+NumBits-1, OpVT),
8282     DAG.getConstant(X86::COND_E, MVT::i8),
8283     Op.getValue(1)
8284   };
8285   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8286
8287   // Finally xor with NumBits-1.
8288   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8289
8290   if (VT == MVT::i8)
8291     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8292   return Op;
8293 }
8294
8295 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8296   EVT VT = Op.getValueType();
8297   EVT OpVT = VT;
8298   unsigned NumBits = VT.getSizeInBits();
8299   DebugLoc dl = Op.getDebugLoc();
8300
8301   Op = Op.getOperand(0);
8302   if (VT == MVT::i8) {
8303     OpVT = MVT::i32;
8304     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8305   }
8306
8307   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8308   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8309   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8310
8311   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8312   SDValue Ops[] = {
8313     Op,
8314     DAG.getConstant(NumBits, OpVT),
8315     DAG.getConstant(X86::COND_E, MVT::i8),
8316     Op.getValue(1)
8317   };
8318   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8319
8320   if (VT == MVT::i8)
8321     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8322   return Op;
8323 }
8324
8325 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8326   EVT VT = Op.getValueType();
8327   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8328   DebugLoc dl = Op.getDebugLoc();
8329
8330   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8331   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8332   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8333   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8334   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8335   //
8336   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8337   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8338   //  return AloBlo + AloBhi + AhiBlo;
8339
8340   SDValue A = Op.getOperand(0);
8341   SDValue B = Op.getOperand(1);
8342
8343   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8344                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8345                        A, DAG.getConstant(32, MVT::i32));
8346   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8347                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8348                        B, DAG.getConstant(32, MVT::i32));
8349   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8350                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8351                        A, B);
8352   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8353                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8354                        A, Bhi);
8355   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8356                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8357                        Ahi, B);
8358   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8359                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8360                        AloBhi, DAG.getConstant(32, MVT::i32));
8361   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8362                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8363                        AhiBlo, DAG.getConstant(32, MVT::i32));
8364   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8365   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8366   return Res;
8367 }
8368
8369 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8370   EVT VT = Op.getValueType();
8371   DebugLoc dl = Op.getDebugLoc();
8372   SDValue R = Op.getOperand(0);
8373
8374   LLVMContext *Context = DAG.getContext();
8375
8376   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8377
8378   if (VT == MVT::v4i32) {
8379     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8380                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8381                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8382
8383     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8384
8385     std::vector<Constant*> CV(4, CI);
8386     Constant *C = ConstantVector::get(CV);
8387     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8388     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8389                                  MachinePointerInfo::getConstantPool(),
8390                                  false, false, 16);
8391
8392     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8393     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8394     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8395     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8396   }
8397   if (VT == MVT::v16i8) {
8398     // a = a << 5;
8399     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8400                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8401                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8402
8403     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8404     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8405
8406     std::vector<Constant*> CVM1(16, CM1);
8407     std::vector<Constant*> CVM2(16, CM2);
8408     Constant *C = ConstantVector::get(CVM1);
8409     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8410     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8411                             MachinePointerInfo::getConstantPool(),
8412                             false, false, 16);
8413
8414     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8415     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8416     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8417                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8418                     DAG.getConstant(4, MVT::i32));
8419     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8420     // a += a
8421     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8422
8423     C = ConstantVector::get(CVM2);
8424     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8425     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8426                     MachinePointerInfo::getConstantPool(),
8427                     false, false, 16);
8428
8429     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8430     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8431     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8432                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8433                     DAG.getConstant(2, MVT::i32));
8434     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8435     // a += a
8436     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8437
8438     // return pblendv(r, r+r, a);
8439     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 
8440                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8441     return R;
8442   }
8443   return SDValue();
8444 }
8445
8446 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8447   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8448   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8449   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8450   // has only one use.
8451   SDNode *N = Op.getNode();
8452   SDValue LHS = N->getOperand(0);
8453   SDValue RHS = N->getOperand(1);
8454   unsigned BaseOp = 0;
8455   unsigned Cond = 0;
8456   DebugLoc DL = Op.getDebugLoc();
8457   switch (Op.getOpcode()) {
8458   default: llvm_unreachable("Unknown ovf instruction!");
8459   case ISD::SADDO:
8460     // A subtract of one will be selected as a INC. Note that INC doesn't
8461     // set CF, so we can't do this for UADDO.
8462     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8463       if (C->getAPIntValue() == 1) {
8464         BaseOp = X86ISD::INC;
8465         Cond = X86::COND_O;
8466         break;
8467       }
8468     BaseOp = X86ISD::ADD;
8469     Cond = X86::COND_O;
8470     break;
8471   case ISD::UADDO:
8472     BaseOp = X86ISD::ADD;
8473     Cond = X86::COND_B;
8474     break;
8475   case ISD::SSUBO:
8476     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8477     // set CF, so we can't do this for USUBO.
8478     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8479       if (C->getAPIntValue() == 1) {
8480         BaseOp = X86ISD::DEC;
8481         Cond = X86::COND_O;
8482         break;
8483       }
8484     BaseOp = X86ISD::SUB;
8485     Cond = X86::COND_O;
8486     break;
8487   case ISD::USUBO:
8488     BaseOp = X86ISD::SUB;
8489     Cond = X86::COND_B;
8490     break;
8491   case ISD::SMULO:
8492     BaseOp = X86ISD::SMUL;
8493     Cond = X86::COND_O;
8494     break;
8495   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8496     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8497                                  MVT::i32);
8498     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8499     
8500     SDValue SetCC =
8501       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8502                   DAG.getConstant(X86::COND_O, MVT::i32),
8503                   SDValue(Sum.getNode(), 2));
8504     
8505     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8506     return Sum;
8507   }
8508   }
8509
8510   // Also sets EFLAGS.
8511   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8512   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8513
8514   SDValue SetCC =
8515     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8516                 DAG.getConstant(Cond, MVT::i32),
8517                 SDValue(Sum.getNode(), 1));
8518
8519   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8520   return Sum;
8521 }
8522
8523 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8524   DebugLoc dl = Op.getDebugLoc();
8525
8526   if (!Subtarget->hasSSE2()) {
8527     SDValue Chain = Op.getOperand(0);
8528     SDValue Zero = DAG.getConstant(0,
8529                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8530     SDValue Ops[] = {
8531       DAG.getRegister(X86::ESP, MVT::i32), // Base
8532       DAG.getTargetConstant(1, MVT::i8),   // Scale
8533       DAG.getRegister(0, MVT::i32),        // Index
8534       DAG.getTargetConstant(0, MVT::i32),  // Disp
8535       DAG.getRegister(0, MVT::i32),        // Segment.
8536       Zero,
8537       Chain
8538     };
8539     SDNode *Res =
8540       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8541                           array_lengthof(Ops));
8542     return SDValue(Res, 0);
8543   }
8544
8545   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8546   if (!isDev)
8547     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8548
8549   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8550   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8551   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8552   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8553
8554   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8555   if (!Op1 && !Op2 && !Op3 && Op4)
8556     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8557
8558   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8559   if (Op1 && !Op2 && !Op3 && !Op4)
8560     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8561
8562   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8563   //           (MFENCE)>;
8564   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8565 }
8566
8567 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8568   EVT T = Op.getValueType();
8569   DebugLoc DL = Op.getDebugLoc();
8570   unsigned Reg = 0;
8571   unsigned size = 0;
8572   switch(T.getSimpleVT().SimpleTy) {
8573   default:
8574     assert(false && "Invalid value type!");
8575   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8576   case MVT::i16: Reg = X86::AX;  size = 2; break;
8577   case MVT::i32: Reg = X86::EAX; size = 4; break;
8578   case MVT::i64:
8579     assert(Subtarget->is64Bit() && "Node not type legal!");
8580     Reg = X86::RAX; size = 8;
8581     break;
8582   }
8583   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8584                                     Op.getOperand(2), SDValue());
8585   SDValue Ops[] = { cpIn.getValue(0),
8586                     Op.getOperand(1),
8587                     Op.getOperand(3),
8588                     DAG.getTargetConstant(size, MVT::i8),
8589                     cpIn.getValue(1) };
8590   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8591   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8592   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8593                                            Ops, 5, T, MMO);
8594   SDValue cpOut =
8595     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8596   return cpOut;
8597 }
8598
8599 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8600                                                  SelectionDAG &DAG) const {
8601   assert(Subtarget->is64Bit() && "Result not type legalized?");
8602   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8603   SDValue TheChain = Op.getOperand(0);
8604   DebugLoc dl = Op.getDebugLoc();
8605   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8606   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8607   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8608                                    rax.getValue(2));
8609   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8610                             DAG.getConstant(32, MVT::i8));
8611   SDValue Ops[] = {
8612     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8613     rdx.getValue(1)
8614   };
8615   return DAG.getMergeValues(Ops, 2, dl);
8616 }
8617
8618 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8619                                             SelectionDAG &DAG) const {
8620   EVT SrcVT = Op.getOperand(0).getValueType();
8621   EVT DstVT = Op.getValueType();
8622   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8623          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8624   assert((DstVT == MVT::i64 ||
8625           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8626          "Unexpected custom BITCAST");
8627   // i64 <=> MMX conversions are Legal.
8628   if (SrcVT==MVT::i64 && DstVT.isVector())
8629     return Op;
8630   if (DstVT==MVT::i64 && SrcVT.isVector())
8631     return Op;
8632   // MMX <=> MMX conversions are Legal.
8633   if (SrcVT.isVector() && DstVT.isVector())
8634     return Op;
8635   // All other conversions need to be expanded.
8636   return SDValue();
8637 }
8638
8639 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8640   SDNode *Node = Op.getNode();
8641   DebugLoc dl = Node->getDebugLoc();
8642   EVT T = Node->getValueType(0);
8643   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8644                               DAG.getConstant(0, T), Node->getOperand(2));
8645   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8646                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8647                        Node->getOperand(0),
8648                        Node->getOperand(1), negOp,
8649                        cast<AtomicSDNode>(Node)->getSrcValue(),
8650                        cast<AtomicSDNode>(Node)->getAlignment());
8651 }
8652
8653 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8654   EVT VT = Op.getNode()->getValueType(0);
8655
8656   // Let legalize expand this if it isn't a legal type yet.
8657   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8658     return SDValue();
8659   
8660   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8661   
8662   unsigned Opc;
8663   bool ExtraOp = false;
8664   switch (Op.getOpcode()) {
8665   default: assert(0 && "Invalid code");
8666   case ISD::ADDC: Opc = X86ISD::ADD; break;
8667   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8668   case ISD::SUBC: Opc = X86ISD::SUB; break;
8669   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8670   }
8671   
8672   if (!ExtraOp)
8673     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8674                        Op.getOperand(1));
8675   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8676                      Op.getOperand(1), Op.getOperand(2));
8677 }
8678
8679 /// LowerOperation - Provide custom lowering hooks for some operations.
8680 ///
8681 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8682   switch (Op.getOpcode()) {
8683   default: llvm_unreachable("Should not custom lower this!");
8684   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8685   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8686   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8687   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8688   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8689   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8690   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8691   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8692   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8693   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8694   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8695   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8696   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8697   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8698   case ISD::SHL_PARTS:
8699   case ISD::SRA_PARTS:
8700   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8701   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8702   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8703   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8704   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8705   case ISD::FABS:               return LowerFABS(Op, DAG);
8706   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8707   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8708   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8709   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8710   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8711   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8712   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8713   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8714   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8715   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8716   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8717   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8718   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8719   case ISD::FRAME_TO_ARGS_OFFSET:
8720                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8721   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8722   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8723   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8724   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8725   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8726   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8727   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8728   case ISD::SHL:                return LowerSHL(Op, DAG);
8729   case ISD::SADDO:
8730   case ISD::UADDO:
8731   case ISD::SSUBO:
8732   case ISD::USUBO:
8733   case ISD::SMULO:
8734   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8735   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8736   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8737   case ISD::ADDC:
8738   case ISD::ADDE:
8739   case ISD::SUBC:
8740   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8741   }
8742 }
8743
8744 void X86TargetLowering::
8745 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8746                         SelectionDAG &DAG, unsigned NewOp) const {
8747   EVT T = Node->getValueType(0);
8748   DebugLoc dl = Node->getDebugLoc();
8749   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8750
8751   SDValue Chain = Node->getOperand(0);
8752   SDValue In1 = Node->getOperand(1);
8753   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8754                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8755   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8756                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8757   SDValue Ops[] = { Chain, In1, In2L, In2H };
8758   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8759   SDValue Result =
8760     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8761                             cast<MemSDNode>(Node)->getMemOperand());
8762   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8763   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8764   Results.push_back(Result.getValue(2));
8765 }
8766
8767 /// ReplaceNodeResults - Replace a node with an illegal result type
8768 /// with a new node built out of custom code.
8769 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8770                                            SmallVectorImpl<SDValue>&Results,
8771                                            SelectionDAG &DAG) const {
8772   DebugLoc dl = N->getDebugLoc();
8773   switch (N->getOpcode()) {
8774   default:
8775     assert(false && "Do not know how to custom type legalize this operation!");
8776     return;
8777   case ISD::ADDC:
8778   case ISD::ADDE:
8779   case ISD::SUBC:
8780   case ISD::SUBE:
8781     // We don't want to expand or promote these.
8782     return;
8783   case ISD::FP_TO_SINT: {
8784     std::pair<SDValue,SDValue> Vals =
8785         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8786     SDValue FIST = Vals.first, StackSlot = Vals.second;
8787     if (FIST.getNode() != 0) {
8788       EVT VT = N->getValueType(0);
8789       // Return a load from the stack slot.
8790       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8791                                     MachinePointerInfo(), false, false, 0));
8792     }
8793     return;
8794   }
8795   case ISD::READCYCLECOUNTER: {
8796     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8797     SDValue TheChain = N->getOperand(0);
8798     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8799     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8800                                      rd.getValue(1));
8801     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8802                                      eax.getValue(2));
8803     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8804     SDValue Ops[] = { eax, edx };
8805     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8806     Results.push_back(edx.getValue(1));
8807     return;
8808   }
8809   case ISD::ATOMIC_CMP_SWAP: {
8810     EVT T = N->getValueType(0);
8811     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8812     SDValue cpInL, cpInH;
8813     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8814                         DAG.getConstant(0, MVT::i32));
8815     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8816                         DAG.getConstant(1, MVT::i32));
8817     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8818     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8819                              cpInL.getValue(1));
8820     SDValue swapInL, swapInH;
8821     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8822                           DAG.getConstant(0, MVT::i32));
8823     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8824                           DAG.getConstant(1, MVT::i32));
8825     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8826                                cpInH.getValue(1));
8827     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8828                                swapInL.getValue(1));
8829     SDValue Ops[] = { swapInH.getValue(0),
8830                       N->getOperand(1),
8831                       swapInH.getValue(1) };
8832     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8833     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8834     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8835                                              Ops, 3, T, MMO);
8836     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8837                                         MVT::i32, Result.getValue(1));
8838     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8839                                         MVT::i32, cpOutL.getValue(2));
8840     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8841     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8842     Results.push_back(cpOutH.getValue(1));
8843     return;
8844   }
8845   case ISD::ATOMIC_LOAD_ADD:
8846     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8847     return;
8848   case ISD::ATOMIC_LOAD_AND:
8849     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8850     return;
8851   case ISD::ATOMIC_LOAD_NAND:
8852     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8853     return;
8854   case ISD::ATOMIC_LOAD_OR:
8855     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8856     return;
8857   case ISD::ATOMIC_LOAD_SUB:
8858     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8859     return;
8860   case ISD::ATOMIC_LOAD_XOR:
8861     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8862     return;
8863   case ISD::ATOMIC_SWAP:
8864     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8865     return;
8866   }
8867 }
8868
8869 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8870   switch (Opcode) {
8871   default: return NULL;
8872   case X86ISD::BSF:                return "X86ISD::BSF";
8873   case X86ISD::BSR:                return "X86ISD::BSR";
8874   case X86ISD::SHLD:               return "X86ISD::SHLD";
8875   case X86ISD::SHRD:               return "X86ISD::SHRD";
8876   case X86ISD::FAND:               return "X86ISD::FAND";
8877   case X86ISD::FOR:                return "X86ISD::FOR";
8878   case X86ISD::FXOR:               return "X86ISD::FXOR";
8879   case X86ISD::FSRL:               return "X86ISD::FSRL";
8880   case X86ISD::FILD:               return "X86ISD::FILD";
8881   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8882   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8883   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8884   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8885   case X86ISD::FLD:                return "X86ISD::FLD";
8886   case X86ISD::FST:                return "X86ISD::FST";
8887   case X86ISD::CALL:               return "X86ISD::CALL";
8888   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8889   case X86ISD::BT:                 return "X86ISD::BT";
8890   case X86ISD::CMP:                return "X86ISD::CMP";
8891   case X86ISD::COMI:               return "X86ISD::COMI";
8892   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8893   case X86ISD::SETCC:              return "X86ISD::SETCC";
8894   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8895   case X86ISD::CMOV:               return "X86ISD::CMOV";
8896   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8897   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8898   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8899   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8900   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8901   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8902   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8903   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8904   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8905   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8906   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8907   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8908   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8909   case X86ISD::PANDN:              return "X86ISD::PANDN";
8910   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
8911   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
8912   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
8913   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
8914   case X86ISD::FMAX:               return "X86ISD::FMAX";
8915   case X86ISD::FMIN:               return "X86ISD::FMIN";
8916   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8917   case X86ISD::FRCP:               return "X86ISD::FRCP";
8918   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8919   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8920   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8921   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8922   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8923   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8924   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8925   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8926   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8927   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8928   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8929   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8930   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8931   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8932   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8933   case X86ISD::VSHL:               return "X86ISD::VSHL";
8934   case X86ISD::VSRL:               return "X86ISD::VSRL";
8935   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8936   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8937   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8938   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8939   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8940   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8941   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8942   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8943   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8944   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8945   case X86ISD::ADD:                return "X86ISD::ADD";
8946   case X86ISD::SUB:                return "X86ISD::SUB";
8947   case X86ISD::ADC:                return "X86ISD::ADC";
8948   case X86ISD::SBB:                return "X86ISD::SBB";
8949   case X86ISD::SMUL:               return "X86ISD::SMUL";
8950   case X86ISD::UMUL:               return "X86ISD::UMUL";
8951   case X86ISD::INC:                return "X86ISD::INC";
8952   case X86ISD::DEC:                return "X86ISD::DEC";
8953   case X86ISD::OR:                 return "X86ISD::OR";
8954   case X86ISD::XOR:                return "X86ISD::XOR";
8955   case X86ISD::AND:                return "X86ISD::AND";
8956   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8957   case X86ISD::PTEST:              return "X86ISD::PTEST";
8958   case X86ISD::TESTP:              return "X86ISD::TESTP";
8959   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8960   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8961   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8962   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8963   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8964   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8965   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8966   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8967   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8968   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8969   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8970   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8971   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8972   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8973   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8974   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8975   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8976   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8977   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8978   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8979   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8980   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8981   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8982   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8983   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8984   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8985   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8986   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8987   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8988   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8989   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8990   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8991   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8992   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8993   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
8994   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
8995   }
8996 }
8997
8998 // isLegalAddressingMode - Return true if the addressing mode represented
8999 // by AM is legal for this target, for a load/store of the specified type.
9000 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
9001                                               const Type *Ty) const {
9002   // X86 supports extremely general addressing modes.
9003   CodeModel::Model M = getTargetMachine().getCodeModel();
9004   Reloc::Model R = getTargetMachine().getRelocationModel();
9005
9006   // X86 allows a sign-extended 32-bit immediate field as a displacement.
9007   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
9008     return false;
9009
9010   if (AM.BaseGV) {
9011     unsigned GVFlags =
9012       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9013
9014     // If a reference to this global requires an extra load, we can't fold it.
9015     if (isGlobalStubReference(GVFlags))
9016       return false;
9017
9018     // If BaseGV requires a register for the PIC base, we cannot also have a
9019     // BaseReg specified.
9020     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9021       return false;
9022
9023     // If lower 4G is not available, then we must use rip-relative addressing.
9024     if ((M != CodeModel::Small || R != Reloc::Static) &&
9025         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9026       return false;
9027   }
9028
9029   switch (AM.Scale) {
9030   case 0:
9031   case 1:
9032   case 2:
9033   case 4:
9034   case 8:
9035     // These scales always work.
9036     break;
9037   case 3:
9038   case 5:
9039   case 9:
9040     // These scales are formed with basereg+scalereg.  Only accept if there is
9041     // no basereg yet.
9042     if (AM.HasBaseReg)
9043       return false;
9044     break;
9045   default:  // Other stuff never works.
9046     return false;
9047   }
9048
9049   return true;
9050 }
9051
9052
9053 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9054   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9055     return false;
9056   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9057   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9058   if (NumBits1 <= NumBits2)
9059     return false;
9060   return true;
9061 }
9062
9063 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9064   if (!VT1.isInteger() || !VT2.isInteger())
9065     return false;
9066   unsigned NumBits1 = VT1.getSizeInBits();
9067   unsigned NumBits2 = VT2.getSizeInBits();
9068   if (NumBits1 <= NumBits2)
9069     return false;
9070   return true;
9071 }
9072
9073 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9074   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9075   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9076 }
9077
9078 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9079   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9080   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9081 }
9082
9083 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9084   // i16 instructions are longer (0x66 prefix) and potentially slower.
9085   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9086 }
9087
9088 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9089 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9090 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9091 /// are assumed to be legal.
9092 bool
9093 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9094                                       EVT VT) const {
9095   // Very little shuffling can be done for 64-bit vectors right now.
9096   if (VT.getSizeInBits() == 64)
9097     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9098
9099   // FIXME: pshufb, blends, shifts.
9100   return (VT.getVectorNumElements() == 2 ||
9101           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9102           isMOVLMask(M, VT) ||
9103           isSHUFPMask(M, VT) ||
9104           isPSHUFDMask(M, VT) ||
9105           isPSHUFHWMask(M, VT) ||
9106           isPSHUFLWMask(M, VT) ||
9107           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9108           isUNPCKLMask(M, VT) ||
9109           isUNPCKHMask(M, VT) ||
9110           isUNPCKL_v_undef_Mask(M, VT) ||
9111           isUNPCKH_v_undef_Mask(M, VT));
9112 }
9113
9114 bool
9115 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9116                                           EVT VT) const {
9117   unsigned NumElts = VT.getVectorNumElements();
9118   // FIXME: This collection of masks seems suspect.
9119   if (NumElts == 2)
9120     return true;
9121   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9122     return (isMOVLMask(Mask, VT)  ||
9123             isCommutedMOVLMask(Mask, VT, true) ||
9124             isSHUFPMask(Mask, VT) ||
9125             isCommutedSHUFPMask(Mask, VT));
9126   }
9127   return false;
9128 }
9129
9130 //===----------------------------------------------------------------------===//
9131 //                           X86 Scheduler Hooks
9132 //===----------------------------------------------------------------------===//
9133
9134 // private utility function
9135 MachineBasicBlock *
9136 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9137                                                        MachineBasicBlock *MBB,
9138                                                        unsigned regOpc,
9139                                                        unsigned immOpc,
9140                                                        unsigned LoadOpc,
9141                                                        unsigned CXchgOpc,
9142                                                        unsigned notOpc,
9143                                                        unsigned EAXreg,
9144                                                        TargetRegisterClass *RC,
9145                                                        bool invSrc) const {
9146   // For the atomic bitwise operator, we generate
9147   //   thisMBB:
9148   //   newMBB:
9149   //     ld  t1 = [bitinstr.addr]
9150   //     op  t2 = t1, [bitinstr.val]
9151   //     mov EAX = t1
9152   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9153   //     bz  newMBB
9154   //     fallthrough -->nextMBB
9155   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9156   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9157   MachineFunction::iterator MBBIter = MBB;
9158   ++MBBIter;
9159
9160   /// First build the CFG
9161   MachineFunction *F = MBB->getParent();
9162   MachineBasicBlock *thisMBB = MBB;
9163   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9164   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9165   F->insert(MBBIter, newMBB);
9166   F->insert(MBBIter, nextMBB);
9167
9168   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9169   nextMBB->splice(nextMBB->begin(), thisMBB,
9170                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9171                   thisMBB->end());
9172   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9173
9174   // Update thisMBB to fall through to newMBB
9175   thisMBB->addSuccessor(newMBB);
9176
9177   // newMBB jumps to itself and fall through to nextMBB
9178   newMBB->addSuccessor(nextMBB);
9179   newMBB->addSuccessor(newMBB);
9180
9181   // Insert instructions into newMBB based on incoming instruction
9182   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9183          "unexpected number of operands");
9184   DebugLoc dl = bInstr->getDebugLoc();
9185   MachineOperand& destOper = bInstr->getOperand(0);
9186   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9187   int numArgs = bInstr->getNumOperands() - 1;
9188   for (int i=0; i < numArgs; ++i)
9189     argOpers[i] = &bInstr->getOperand(i+1);
9190
9191   // x86 address has 4 operands: base, index, scale, and displacement
9192   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9193   int valArgIndx = lastAddrIndx + 1;
9194
9195   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9196   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9197   for (int i=0; i <= lastAddrIndx; ++i)
9198     (*MIB).addOperand(*argOpers[i]);
9199
9200   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9201   if (invSrc) {
9202     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9203   }
9204   else
9205     tt = t1;
9206
9207   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9208   assert((argOpers[valArgIndx]->isReg() ||
9209           argOpers[valArgIndx]->isImm()) &&
9210          "invalid operand");
9211   if (argOpers[valArgIndx]->isReg())
9212     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9213   else
9214     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9215   MIB.addReg(tt);
9216   (*MIB).addOperand(*argOpers[valArgIndx]);
9217
9218   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9219   MIB.addReg(t1);
9220
9221   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9222   for (int i=0; i <= lastAddrIndx; ++i)
9223     (*MIB).addOperand(*argOpers[i]);
9224   MIB.addReg(t2);
9225   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9226   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9227                     bInstr->memoperands_end());
9228
9229   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9230   MIB.addReg(EAXreg);
9231
9232   // insert branch
9233   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9234
9235   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9236   return nextMBB;
9237 }
9238
9239 // private utility function:  64 bit atomics on 32 bit host.
9240 MachineBasicBlock *
9241 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9242                                                        MachineBasicBlock *MBB,
9243                                                        unsigned regOpcL,
9244                                                        unsigned regOpcH,
9245                                                        unsigned immOpcL,
9246                                                        unsigned immOpcH,
9247                                                        bool invSrc) const {
9248   // For the atomic bitwise operator, we generate
9249   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9250   //     ld t1,t2 = [bitinstr.addr]
9251   //   newMBB:
9252   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9253   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9254   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9255   //     mov ECX, EBX <- t5, t6
9256   //     mov EAX, EDX <- t1, t2
9257   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9258   //     mov t3, t4 <- EAX, EDX
9259   //     bz  newMBB
9260   //     result in out1, out2
9261   //     fallthrough -->nextMBB
9262
9263   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9264   const unsigned LoadOpc = X86::MOV32rm;
9265   const unsigned NotOpc = X86::NOT32r;
9266   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9267   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9268   MachineFunction::iterator MBBIter = MBB;
9269   ++MBBIter;
9270
9271   /// First build the CFG
9272   MachineFunction *F = MBB->getParent();
9273   MachineBasicBlock *thisMBB = MBB;
9274   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9275   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9276   F->insert(MBBIter, newMBB);
9277   F->insert(MBBIter, nextMBB);
9278
9279   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9280   nextMBB->splice(nextMBB->begin(), thisMBB,
9281                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9282                   thisMBB->end());
9283   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9284
9285   // Update thisMBB to fall through to newMBB
9286   thisMBB->addSuccessor(newMBB);
9287
9288   // newMBB jumps to itself and fall through to nextMBB
9289   newMBB->addSuccessor(nextMBB);
9290   newMBB->addSuccessor(newMBB);
9291
9292   DebugLoc dl = bInstr->getDebugLoc();
9293   // Insert instructions into newMBB based on incoming instruction
9294   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9295   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9296          "unexpected number of operands");
9297   MachineOperand& dest1Oper = bInstr->getOperand(0);
9298   MachineOperand& dest2Oper = bInstr->getOperand(1);
9299   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9300   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9301     argOpers[i] = &bInstr->getOperand(i+2);
9302
9303     // We use some of the operands multiple times, so conservatively just
9304     // clear any kill flags that might be present.
9305     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9306       argOpers[i]->setIsKill(false);
9307   }
9308
9309   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9310   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9311
9312   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9313   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9314   for (int i=0; i <= lastAddrIndx; ++i)
9315     (*MIB).addOperand(*argOpers[i]);
9316   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9317   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9318   // add 4 to displacement.
9319   for (int i=0; i <= lastAddrIndx-2; ++i)
9320     (*MIB).addOperand(*argOpers[i]);
9321   MachineOperand newOp3 = *(argOpers[3]);
9322   if (newOp3.isImm())
9323     newOp3.setImm(newOp3.getImm()+4);
9324   else
9325     newOp3.setOffset(newOp3.getOffset()+4);
9326   (*MIB).addOperand(newOp3);
9327   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9328
9329   // t3/4 are defined later, at the bottom of the loop
9330   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9331   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9332   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9333     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9334   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9335     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9336
9337   // The subsequent operations should be using the destination registers of
9338   //the PHI instructions.
9339   if (invSrc) {
9340     t1 = F->getRegInfo().createVirtualRegister(RC);
9341     t2 = F->getRegInfo().createVirtualRegister(RC);
9342     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9343     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9344   } else {
9345     t1 = dest1Oper.getReg();
9346     t2 = dest2Oper.getReg();
9347   }
9348
9349   int valArgIndx = lastAddrIndx + 1;
9350   assert((argOpers[valArgIndx]->isReg() ||
9351           argOpers[valArgIndx]->isImm()) &&
9352          "invalid operand");
9353   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9354   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9355   if (argOpers[valArgIndx]->isReg())
9356     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9357   else
9358     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9359   if (regOpcL != X86::MOV32rr)
9360     MIB.addReg(t1);
9361   (*MIB).addOperand(*argOpers[valArgIndx]);
9362   assert(argOpers[valArgIndx + 1]->isReg() ==
9363          argOpers[valArgIndx]->isReg());
9364   assert(argOpers[valArgIndx + 1]->isImm() ==
9365          argOpers[valArgIndx]->isImm());
9366   if (argOpers[valArgIndx + 1]->isReg())
9367     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9368   else
9369     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9370   if (regOpcH != X86::MOV32rr)
9371     MIB.addReg(t2);
9372   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9373
9374   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9375   MIB.addReg(t1);
9376   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9377   MIB.addReg(t2);
9378
9379   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9380   MIB.addReg(t5);
9381   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9382   MIB.addReg(t6);
9383
9384   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9385   for (int i=0; i <= lastAddrIndx; ++i)
9386     (*MIB).addOperand(*argOpers[i]);
9387
9388   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9389   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9390                     bInstr->memoperands_end());
9391
9392   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9393   MIB.addReg(X86::EAX);
9394   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9395   MIB.addReg(X86::EDX);
9396
9397   // insert branch
9398   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9399
9400   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9401   return nextMBB;
9402 }
9403
9404 // private utility function
9405 MachineBasicBlock *
9406 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9407                                                       MachineBasicBlock *MBB,
9408                                                       unsigned cmovOpc) const {
9409   // For the atomic min/max operator, we generate
9410   //   thisMBB:
9411   //   newMBB:
9412   //     ld t1 = [min/max.addr]
9413   //     mov t2 = [min/max.val]
9414   //     cmp  t1, t2
9415   //     cmov[cond] t2 = t1
9416   //     mov EAX = t1
9417   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9418   //     bz   newMBB
9419   //     fallthrough -->nextMBB
9420   //
9421   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9422   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9423   MachineFunction::iterator MBBIter = MBB;
9424   ++MBBIter;
9425
9426   /// First build the CFG
9427   MachineFunction *F = MBB->getParent();
9428   MachineBasicBlock *thisMBB = MBB;
9429   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9430   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9431   F->insert(MBBIter, newMBB);
9432   F->insert(MBBIter, nextMBB);
9433
9434   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9435   nextMBB->splice(nextMBB->begin(), thisMBB,
9436                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9437                   thisMBB->end());
9438   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9439
9440   // Update thisMBB to fall through to newMBB
9441   thisMBB->addSuccessor(newMBB);
9442
9443   // newMBB jumps to newMBB and fall through to nextMBB
9444   newMBB->addSuccessor(nextMBB);
9445   newMBB->addSuccessor(newMBB);
9446
9447   DebugLoc dl = mInstr->getDebugLoc();
9448   // Insert instructions into newMBB based on incoming instruction
9449   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9450          "unexpected number of operands");
9451   MachineOperand& destOper = mInstr->getOperand(0);
9452   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9453   int numArgs = mInstr->getNumOperands() - 1;
9454   for (int i=0; i < numArgs; ++i)
9455     argOpers[i] = &mInstr->getOperand(i+1);
9456
9457   // x86 address has 4 operands: base, index, scale, and displacement
9458   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9459   int valArgIndx = lastAddrIndx + 1;
9460
9461   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9462   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9463   for (int i=0; i <= lastAddrIndx; ++i)
9464     (*MIB).addOperand(*argOpers[i]);
9465
9466   // We only support register and immediate values
9467   assert((argOpers[valArgIndx]->isReg() ||
9468           argOpers[valArgIndx]->isImm()) &&
9469          "invalid operand");
9470
9471   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9472   if (argOpers[valArgIndx]->isReg())
9473     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9474   else
9475     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9476   (*MIB).addOperand(*argOpers[valArgIndx]);
9477
9478   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9479   MIB.addReg(t1);
9480
9481   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9482   MIB.addReg(t1);
9483   MIB.addReg(t2);
9484
9485   // Generate movc
9486   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9487   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9488   MIB.addReg(t2);
9489   MIB.addReg(t1);
9490
9491   // Cmp and exchange if none has modified the memory location
9492   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9493   for (int i=0; i <= lastAddrIndx; ++i)
9494     (*MIB).addOperand(*argOpers[i]);
9495   MIB.addReg(t3);
9496   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9497   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9498                     mInstr->memoperands_end());
9499
9500   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9501   MIB.addReg(X86::EAX);
9502
9503   // insert branch
9504   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9505
9506   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9507   return nextMBB;
9508 }
9509
9510 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9511 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9512 // in the .td file.
9513 MachineBasicBlock *
9514 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9515                             unsigned numArgs, bool memArg) const {
9516   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9517          "Target must have SSE4.2 or AVX features enabled");
9518
9519   DebugLoc dl = MI->getDebugLoc();
9520   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9521   unsigned Opc;
9522   if (!Subtarget->hasAVX()) {
9523     if (memArg)
9524       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9525     else
9526       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9527   } else {
9528     if (memArg)
9529       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9530     else
9531       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9532   }
9533
9534   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9535   for (unsigned i = 0; i < numArgs; ++i) {
9536     MachineOperand &Op = MI->getOperand(i+1);
9537     if (!(Op.isReg() && Op.isImplicit()))
9538       MIB.addOperand(Op);
9539   }
9540   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9541     .addReg(X86::XMM0);
9542
9543   MI->eraseFromParent();
9544   return BB;
9545 }
9546
9547 MachineBasicBlock *
9548 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9549   DebugLoc dl = MI->getDebugLoc();
9550   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9551   
9552   // Address into RAX/EAX, other two args into ECX, EDX.
9553   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9554   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9555   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9556   for (int i = 0; i < X86::AddrNumOperands; ++i)
9557     MIB.addOperand(MI->getOperand(i));
9558   
9559   unsigned ValOps = X86::AddrNumOperands;
9560   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9561     .addReg(MI->getOperand(ValOps).getReg());
9562   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9563     .addReg(MI->getOperand(ValOps+1).getReg());
9564
9565   // The instruction doesn't actually take any operands though.
9566   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9567   
9568   MI->eraseFromParent(); // The pseudo is gone now.
9569   return BB;
9570 }
9571
9572 MachineBasicBlock *
9573 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9574   DebugLoc dl = MI->getDebugLoc();
9575   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9576   
9577   // First arg in ECX, the second in EAX.
9578   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9579     .addReg(MI->getOperand(0).getReg());
9580   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9581     .addReg(MI->getOperand(1).getReg());
9582     
9583   // The instruction doesn't actually take any operands though.
9584   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9585   
9586   MI->eraseFromParent(); // The pseudo is gone now.
9587   return BB;
9588 }
9589
9590 MachineBasicBlock *
9591 X86TargetLowering::EmitVAARG64WithCustomInserter(
9592                    MachineInstr *MI,
9593                    MachineBasicBlock *MBB) const {
9594   // Emit va_arg instruction on X86-64.
9595
9596   // Operands to this pseudo-instruction:
9597   // 0  ) Output        : destination address (reg)
9598   // 1-5) Input         : va_list address (addr, i64mem)
9599   // 6  ) ArgSize       : Size (in bytes) of vararg type
9600   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9601   // 8  ) Align         : Alignment of type
9602   // 9  ) EFLAGS (implicit-def)
9603
9604   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9605   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9606
9607   unsigned DestReg = MI->getOperand(0).getReg();
9608   MachineOperand &Base = MI->getOperand(1);
9609   MachineOperand &Scale = MI->getOperand(2);
9610   MachineOperand &Index = MI->getOperand(3);
9611   MachineOperand &Disp = MI->getOperand(4);
9612   MachineOperand &Segment = MI->getOperand(5);
9613   unsigned ArgSize = MI->getOperand(6).getImm();
9614   unsigned ArgMode = MI->getOperand(7).getImm();
9615   unsigned Align = MI->getOperand(8).getImm();
9616
9617   // Memory Reference
9618   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9619   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9620   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9621
9622   // Machine Information
9623   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9624   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9625   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9626   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9627   DebugLoc DL = MI->getDebugLoc();
9628
9629   // struct va_list {
9630   //   i32   gp_offset
9631   //   i32   fp_offset
9632   //   i64   overflow_area (address)
9633   //   i64   reg_save_area (address)
9634   // }
9635   // sizeof(va_list) = 24
9636   // alignment(va_list) = 8
9637
9638   unsigned TotalNumIntRegs = 6;
9639   unsigned TotalNumXMMRegs = 8;
9640   bool UseGPOffset = (ArgMode == 1);
9641   bool UseFPOffset = (ArgMode == 2);
9642   unsigned MaxOffset = TotalNumIntRegs * 8 +
9643                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9644
9645   /* Align ArgSize to a multiple of 8 */
9646   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9647   bool NeedsAlign = (Align > 8);
9648
9649   MachineBasicBlock *thisMBB = MBB;
9650   MachineBasicBlock *overflowMBB;
9651   MachineBasicBlock *offsetMBB;
9652   MachineBasicBlock *endMBB;
9653
9654   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9655   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9656   unsigned OffsetReg = 0;
9657
9658   if (!UseGPOffset && !UseFPOffset) {
9659     // If we only pull from the overflow region, we don't create a branch.
9660     // We don't need to alter control flow.
9661     OffsetDestReg = 0; // unused
9662     OverflowDestReg = DestReg;
9663
9664     offsetMBB = NULL;
9665     overflowMBB = thisMBB;
9666     endMBB = thisMBB;
9667   } else {
9668     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9669     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9670     // If not, pull from overflow_area. (branch to overflowMBB)
9671     //
9672     //       thisMBB
9673     //         |     .
9674     //         |        .
9675     //     offsetMBB   overflowMBB
9676     //         |        .
9677     //         |     .
9678     //        endMBB
9679
9680     // Registers for the PHI in endMBB
9681     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9682     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9683
9684     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9685     MachineFunction *MF = MBB->getParent();
9686     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9687     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9688     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9689
9690     MachineFunction::iterator MBBIter = MBB;
9691     ++MBBIter;
9692
9693     // Insert the new basic blocks
9694     MF->insert(MBBIter, offsetMBB);
9695     MF->insert(MBBIter, overflowMBB);
9696     MF->insert(MBBIter, endMBB);
9697
9698     // Transfer the remainder of MBB and its successor edges to endMBB.
9699     endMBB->splice(endMBB->begin(), thisMBB,
9700                     llvm::next(MachineBasicBlock::iterator(MI)),
9701                     thisMBB->end());
9702     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9703
9704     // Make offsetMBB and overflowMBB successors of thisMBB
9705     thisMBB->addSuccessor(offsetMBB);
9706     thisMBB->addSuccessor(overflowMBB);
9707
9708     // endMBB is a successor of both offsetMBB and overflowMBB
9709     offsetMBB->addSuccessor(endMBB);
9710     overflowMBB->addSuccessor(endMBB);
9711
9712     // Load the offset value into a register
9713     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9714     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9715       .addOperand(Base)
9716       .addOperand(Scale)
9717       .addOperand(Index)
9718       .addDisp(Disp, UseFPOffset ? 4 : 0)
9719       .addOperand(Segment)
9720       .setMemRefs(MMOBegin, MMOEnd);
9721
9722     // Check if there is enough room left to pull this argument.
9723     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9724       .addReg(OffsetReg)
9725       .addImm(MaxOffset + 8 - ArgSizeA8);
9726
9727     // Branch to "overflowMBB" if offset >= max
9728     // Fall through to "offsetMBB" otherwise
9729     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9730       .addMBB(overflowMBB);
9731   }
9732
9733   // In offsetMBB, emit code to use the reg_save_area.
9734   if (offsetMBB) {
9735     assert(OffsetReg != 0);
9736
9737     // Read the reg_save_area address.
9738     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9739     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9740       .addOperand(Base)
9741       .addOperand(Scale)
9742       .addOperand(Index)
9743       .addDisp(Disp, 16)
9744       .addOperand(Segment)
9745       .setMemRefs(MMOBegin, MMOEnd);
9746
9747     // Zero-extend the offset
9748     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9749       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9750         .addImm(0)
9751         .addReg(OffsetReg)
9752         .addImm(X86::sub_32bit);
9753
9754     // Add the offset to the reg_save_area to get the final address.
9755     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9756       .addReg(OffsetReg64)
9757       .addReg(RegSaveReg);
9758
9759     // Compute the offset for the next argument
9760     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9761     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9762       .addReg(OffsetReg)
9763       .addImm(UseFPOffset ? 16 : 8);
9764
9765     // Store it back into the va_list.
9766     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9767       .addOperand(Base)
9768       .addOperand(Scale)
9769       .addOperand(Index)
9770       .addDisp(Disp, UseFPOffset ? 4 : 0)
9771       .addOperand(Segment)
9772       .addReg(NextOffsetReg)
9773       .setMemRefs(MMOBegin, MMOEnd);
9774
9775     // Jump to endMBB
9776     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9777       .addMBB(endMBB);
9778   }
9779
9780   //
9781   // Emit code to use overflow area
9782   //
9783
9784   // Load the overflow_area address into a register.
9785   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9786   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9787     .addOperand(Base)
9788     .addOperand(Scale)
9789     .addOperand(Index)
9790     .addDisp(Disp, 8)
9791     .addOperand(Segment)
9792     .setMemRefs(MMOBegin, MMOEnd);
9793
9794   // If we need to align it, do so. Otherwise, just copy the address
9795   // to OverflowDestReg.
9796   if (NeedsAlign) {
9797     // Align the overflow address
9798     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9799     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9800
9801     // aligned_addr = (addr + (align-1)) & ~(align-1)
9802     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9803       .addReg(OverflowAddrReg)
9804       .addImm(Align-1);
9805
9806     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9807       .addReg(TmpReg)
9808       .addImm(~(uint64_t)(Align-1));
9809   } else {
9810     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9811       .addReg(OverflowAddrReg);
9812   }
9813
9814   // Compute the next overflow address after this argument.
9815   // (the overflow address should be kept 8-byte aligned)
9816   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9817   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9818     .addReg(OverflowDestReg)
9819     .addImm(ArgSizeA8);
9820
9821   // Store the new overflow address.
9822   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9823     .addOperand(Base)
9824     .addOperand(Scale)
9825     .addOperand(Index)
9826     .addDisp(Disp, 8)
9827     .addOperand(Segment)
9828     .addReg(NextAddrReg)
9829     .setMemRefs(MMOBegin, MMOEnd);
9830
9831   // If we branched, emit the PHI to the front of endMBB.
9832   if (offsetMBB) {
9833     BuildMI(*endMBB, endMBB->begin(), DL,
9834             TII->get(X86::PHI), DestReg)
9835       .addReg(OffsetDestReg).addMBB(offsetMBB)
9836       .addReg(OverflowDestReg).addMBB(overflowMBB);
9837   }
9838
9839   // Erase the pseudo instruction
9840   MI->eraseFromParent();
9841
9842   return endMBB;
9843 }
9844
9845 MachineBasicBlock *
9846 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9847                                                  MachineInstr *MI,
9848                                                  MachineBasicBlock *MBB) const {
9849   // Emit code to save XMM registers to the stack. The ABI says that the
9850   // number of registers to save is given in %al, so it's theoretically
9851   // possible to do an indirect jump trick to avoid saving all of them,
9852   // however this code takes a simpler approach and just executes all
9853   // of the stores if %al is non-zero. It's less code, and it's probably
9854   // easier on the hardware branch predictor, and stores aren't all that
9855   // expensive anyway.
9856
9857   // Create the new basic blocks. One block contains all the XMM stores,
9858   // and one block is the final destination regardless of whether any
9859   // stores were performed.
9860   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9861   MachineFunction *F = MBB->getParent();
9862   MachineFunction::iterator MBBIter = MBB;
9863   ++MBBIter;
9864   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9865   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9866   F->insert(MBBIter, XMMSaveMBB);
9867   F->insert(MBBIter, EndMBB);
9868
9869   // Transfer the remainder of MBB and its successor edges to EndMBB.
9870   EndMBB->splice(EndMBB->begin(), MBB,
9871                  llvm::next(MachineBasicBlock::iterator(MI)),
9872                  MBB->end());
9873   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9874
9875   // The original block will now fall through to the XMM save block.
9876   MBB->addSuccessor(XMMSaveMBB);
9877   // The XMMSaveMBB will fall through to the end block.
9878   XMMSaveMBB->addSuccessor(EndMBB);
9879
9880   // Now add the instructions.
9881   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9882   DebugLoc DL = MI->getDebugLoc();
9883
9884   unsigned CountReg = MI->getOperand(0).getReg();
9885   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9886   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9887
9888   if (!Subtarget->isTargetWin64()) {
9889     // If %al is 0, branch around the XMM save block.
9890     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9891     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9892     MBB->addSuccessor(EndMBB);
9893   }
9894
9895   // In the XMM save block, save all the XMM argument registers.
9896   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9897     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9898     MachineMemOperand *MMO =
9899       F->getMachineMemOperand(
9900           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9901         MachineMemOperand::MOStore,
9902         /*Size=*/16, /*Align=*/16);
9903     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9904       .addFrameIndex(RegSaveFrameIndex)
9905       .addImm(/*Scale=*/1)
9906       .addReg(/*IndexReg=*/0)
9907       .addImm(/*Disp=*/Offset)
9908       .addReg(/*Segment=*/0)
9909       .addReg(MI->getOperand(i).getReg())
9910       .addMemOperand(MMO);
9911   }
9912
9913   MI->eraseFromParent();   // The pseudo instruction is gone now.
9914
9915   return EndMBB;
9916 }
9917
9918 MachineBasicBlock *
9919 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9920                                      MachineBasicBlock *BB) const {
9921   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9922   DebugLoc DL = MI->getDebugLoc();
9923
9924   // To "insert" a SELECT_CC instruction, we actually have to insert the
9925   // diamond control-flow pattern.  The incoming instruction knows the
9926   // destination vreg to set, the condition code register to branch on, the
9927   // true/false values to select between, and a branch opcode to use.
9928   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9929   MachineFunction::iterator It = BB;
9930   ++It;
9931
9932   //  thisMBB:
9933   //  ...
9934   //   TrueVal = ...
9935   //   cmpTY ccX, r1, r2
9936   //   bCC copy1MBB
9937   //   fallthrough --> copy0MBB
9938   MachineBasicBlock *thisMBB = BB;
9939   MachineFunction *F = BB->getParent();
9940   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9941   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9942   F->insert(It, copy0MBB);
9943   F->insert(It, sinkMBB);
9944
9945   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9946   // live into the sink and copy blocks.
9947   const MachineFunction *MF = BB->getParent();
9948   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9949   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9950
9951   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9952     const MachineOperand &MO = MI->getOperand(I);
9953     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9954     unsigned Reg = MO.getReg();
9955     if (Reg != X86::EFLAGS) continue;
9956     copy0MBB->addLiveIn(Reg);
9957     sinkMBB->addLiveIn(Reg);
9958   }
9959
9960   // Transfer the remainder of BB and its successor edges to sinkMBB.
9961   sinkMBB->splice(sinkMBB->begin(), BB,
9962                   llvm::next(MachineBasicBlock::iterator(MI)),
9963                   BB->end());
9964   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9965
9966   // Add the true and fallthrough blocks as its successors.
9967   BB->addSuccessor(copy0MBB);
9968   BB->addSuccessor(sinkMBB);
9969
9970   // Create the conditional branch instruction.
9971   unsigned Opc =
9972     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9973   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9974
9975   //  copy0MBB:
9976   //   %FalseValue = ...
9977   //   # fallthrough to sinkMBB
9978   copy0MBB->addSuccessor(sinkMBB);
9979
9980   //  sinkMBB:
9981   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9982   //  ...
9983   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9984           TII->get(X86::PHI), MI->getOperand(0).getReg())
9985     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9986     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9987
9988   MI->eraseFromParent();   // The pseudo instruction is gone now.
9989   return sinkMBB;
9990 }
9991
9992 MachineBasicBlock *
9993 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9994                                           MachineBasicBlock *BB) const {
9995   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9996   DebugLoc DL = MI->getDebugLoc();
9997
9998   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9999   // non-trivial part is impdef of ESP.
10000   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
10001   // mingw-w64.
10002
10003   const char *StackProbeSymbol =
10004       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
10005
10006   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
10007     .addExternalSymbol(StackProbeSymbol)
10008     .addReg(X86::EAX, RegState::Implicit)
10009     .addReg(X86::ESP, RegState::Implicit)
10010     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
10011     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
10012     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10013
10014   MI->eraseFromParent();   // The pseudo instruction is gone now.
10015   return BB;
10016 }
10017
10018 MachineBasicBlock *
10019 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10020                                       MachineBasicBlock *BB) const {
10021   // This is pretty easy.  We're taking the value that we received from
10022   // our load from the relocation, sticking it in either RDI (x86-64)
10023   // or EAX and doing an indirect call.  The return value will then
10024   // be in the normal return register.
10025   const X86InstrInfo *TII
10026     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10027   DebugLoc DL = MI->getDebugLoc();
10028   MachineFunction *F = BB->getParent();
10029
10030   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10031   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10032
10033   if (Subtarget->is64Bit()) {
10034     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10035                                       TII->get(X86::MOV64rm), X86::RDI)
10036     .addReg(X86::RIP)
10037     .addImm(0).addReg(0)
10038     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10039                       MI->getOperand(3).getTargetFlags())
10040     .addReg(0);
10041     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10042     addDirectMem(MIB, X86::RDI);
10043   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10044     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10045                                       TII->get(X86::MOV32rm), X86::EAX)
10046     .addReg(0)
10047     .addImm(0).addReg(0)
10048     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10049                       MI->getOperand(3).getTargetFlags())
10050     .addReg(0);
10051     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10052     addDirectMem(MIB, X86::EAX);
10053   } else {
10054     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10055                                       TII->get(X86::MOV32rm), X86::EAX)
10056     .addReg(TII->getGlobalBaseReg(F))
10057     .addImm(0).addReg(0)
10058     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10059                       MI->getOperand(3).getTargetFlags())
10060     .addReg(0);
10061     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10062     addDirectMem(MIB, X86::EAX);
10063   }
10064
10065   MI->eraseFromParent(); // The pseudo instruction is gone now.
10066   return BB;
10067 }
10068
10069 MachineBasicBlock *
10070 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10071                                                MachineBasicBlock *BB) const {
10072   switch (MI->getOpcode()) {
10073   default: assert(false && "Unexpected instr type to insert");
10074   case X86::WIN_ALLOCA:
10075     return EmitLoweredWinAlloca(MI, BB);
10076   case X86::TLSCall_32:
10077   case X86::TLSCall_64:
10078     return EmitLoweredTLSCall(MI, BB);
10079   case X86::CMOV_GR8:
10080   case X86::CMOV_FR32:
10081   case X86::CMOV_FR64:
10082   case X86::CMOV_V4F32:
10083   case X86::CMOV_V2F64:
10084   case X86::CMOV_V2I64:
10085   case X86::CMOV_GR16:
10086   case X86::CMOV_GR32:
10087   case X86::CMOV_RFP32:
10088   case X86::CMOV_RFP64:
10089   case X86::CMOV_RFP80:
10090     return EmitLoweredSelect(MI, BB);
10091
10092   case X86::FP32_TO_INT16_IN_MEM:
10093   case X86::FP32_TO_INT32_IN_MEM:
10094   case X86::FP32_TO_INT64_IN_MEM:
10095   case X86::FP64_TO_INT16_IN_MEM:
10096   case X86::FP64_TO_INT32_IN_MEM:
10097   case X86::FP64_TO_INT64_IN_MEM:
10098   case X86::FP80_TO_INT16_IN_MEM:
10099   case X86::FP80_TO_INT32_IN_MEM:
10100   case X86::FP80_TO_INT64_IN_MEM: {
10101     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10102     DebugLoc DL = MI->getDebugLoc();
10103
10104     // Change the floating point control register to use "round towards zero"
10105     // mode when truncating to an integer value.
10106     MachineFunction *F = BB->getParent();
10107     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10108     addFrameReference(BuildMI(*BB, MI, DL,
10109                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10110
10111     // Load the old value of the high byte of the control word...
10112     unsigned OldCW =
10113       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10114     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10115                       CWFrameIdx);
10116
10117     // Set the high part to be round to zero...
10118     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10119       .addImm(0xC7F);
10120
10121     // Reload the modified control word now...
10122     addFrameReference(BuildMI(*BB, MI, DL,
10123                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10124
10125     // Restore the memory image of control word to original value
10126     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10127       .addReg(OldCW);
10128
10129     // Get the X86 opcode to use.
10130     unsigned Opc;
10131     switch (MI->getOpcode()) {
10132     default: llvm_unreachable("illegal opcode!");
10133     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10134     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10135     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10136     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10137     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10138     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10139     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10140     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10141     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10142     }
10143
10144     X86AddressMode AM;
10145     MachineOperand &Op = MI->getOperand(0);
10146     if (Op.isReg()) {
10147       AM.BaseType = X86AddressMode::RegBase;
10148       AM.Base.Reg = Op.getReg();
10149     } else {
10150       AM.BaseType = X86AddressMode::FrameIndexBase;
10151       AM.Base.FrameIndex = Op.getIndex();
10152     }
10153     Op = MI->getOperand(1);
10154     if (Op.isImm())
10155       AM.Scale = Op.getImm();
10156     Op = MI->getOperand(2);
10157     if (Op.isImm())
10158       AM.IndexReg = Op.getImm();
10159     Op = MI->getOperand(3);
10160     if (Op.isGlobal()) {
10161       AM.GV = Op.getGlobal();
10162     } else {
10163       AM.Disp = Op.getImm();
10164     }
10165     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10166                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10167
10168     // Reload the original control word now.
10169     addFrameReference(BuildMI(*BB, MI, DL,
10170                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10171
10172     MI->eraseFromParent();   // The pseudo instruction is gone now.
10173     return BB;
10174   }
10175     // String/text processing lowering.
10176   case X86::PCMPISTRM128REG:
10177   case X86::VPCMPISTRM128REG:
10178     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10179   case X86::PCMPISTRM128MEM:
10180   case X86::VPCMPISTRM128MEM:
10181     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10182   case X86::PCMPESTRM128REG:
10183   case X86::VPCMPESTRM128REG:
10184     return EmitPCMP(MI, BB, 5, false /* in mem */);
10185   case X86::PCMPESTRM128MEM:
10186   case X86::VPCMPESTRM128MEM:
10187     return EmitPCMP(MI, BB, 5, true /* in mem */);
10188
10189     // Thread synchronization.
10190   case X86::MONITOR:
10191     return EmitMonitor(MI, BB);  
10192   case X86::MWAIT:
10193     return EmitMwait(MI, BB);
10194
10195     // Atomic Lowering.
10196   case X86::ATOMAND32:
10197     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10198                                                X86::AND32ri, X86::MOV32rm,
10199                                                X86::LCMPXCHG32,
10200                                                X86::NOT32r, X86::EAX,
10201                                                X86::GR32RegisterClass);
10202   case X86::ATOMOR32:
10203     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10204                                                X86::OR32ri, X86::MOV32rm,
10205                                                X86::LCMPXCHG32,
10206                                                X86::NOT32r, X86::EAX,
10207                                                X86::GR32RegisterClass);
10208   case X86::ATOMXOR32:
10209     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10210                                                X86::XOR32ri, X86::MOV32rm,
10211                                                X86::LCMPXCHG32,
10212                                                X86::NOT32r, X86::EAX,
10213                                                X86::GR32RegisterClass);
10214   case X86::ATOMNAND32:
10215     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10216                                                X86::AND32ri, X86::MOV32rm,
10217                                                X86::LCMPXCHG32,
10218                                                X86::NOT32r, X86::EAX,
10219                                                X86::GR32RegisterClass, true);
10220   case X86::ATOMMIN32:
10221     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10222   case X86::ATOMMAX32:
10223     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10224   case X86::ATOMUMIN32:
10225     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10226   case X86::ATOMUMAX32:
10227     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10228
10229   case X86::ATOMAND16:
10230     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10231                                                X86::AND16ri, X86::MOV16rm,
10232                                                X86::LCMPXCHG16,
10233                                                X86::NOT16r, X86::AX,
10234                                                X86::GR16RegisterClass);
10235   case X86::ATOMOR16:
10236     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10237                                                X86::OR16ri, X86::MOV16rm,
10238                                                X86::LCMPXCHG16,
10239                                                X86::NOT16r, X86::AX,
10240                                                X86::GR16RegisterClass);
10241   case X86::ATOMXOR16:
10242     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10243                                                X86::XOR16ri, X86::MOV16rm,
10244                                                X86::LCMPXCHG16,
10245                                                X86::NOT16r, X86::AX,
10246                                                X86::GR16RegisterClass);
10247   case X86::ATOMNAND16:
10248     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10249                                                X86::AND16ri, X86::MOV16rm,
10250                                                X86::LCMPXCHG16,
10251                                                X86::NOT16r, X86::AX,
10252                                                X86::GR16RegisterClass, true);
10253   case X86::ATOMMIN16:
10254     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10255   case X86::ATOMMAX16:
10256     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10257   case X86::ATOMUMIN16:
10258     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10259   case X86::ATOMUMAX16:
10260     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10261
10262   case X86::ATOMAND8:
10263     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10264                                                X86::AND8ri, X86::MOV8rm,
10265                                                X86::LCMPXCHG8,
10266                                                X86::NOT8r, X86::AL,
10267                                                X86::GR8RegisterClass);
10268   case X86::ATOMOR8:
10269     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10270                                                X86::OR8ri, X86::MOV8rm,
10271                                                X86::LCMPXCHG8,
10272                                                X86::NOT8r, X86::AL,
10273                                                X86::GR8RegisterClass);
10274   case X86::ATOMXOR8:
10275     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10276                                                X86::XOR8ri, X86::MOV8rm,
10277                                                X86::LCMPXCHG8,
10278                                                X86::NOT8r, X86::AL,
10279                                                X86::GR8RegisterClass);
10280   case X86::ATOMNAND8:
10281     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10282                                                X86::AND8ri, X86::MOV8rm,
10283                                                X86::LCMPXCHG8,
10284                                                X86::NOT8r, X86::AL,
10285                                                X86::GR8RegisterClass, true);
10286   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10287   // This group is for 64-bit host.
10288   case X86::ATOMAND64:
10289     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10290                                                X86::AND64ri32, X86::MOV64rm,
10291                                                X86::LCMPXCHG64,
10292                                                X86::NOT64r, X86::RAX,
10293                                                X86::GR64RegisterClass);
10294   case X86::ATOMOR64:
10295     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10296                                                X86::OR64ri32, X86::MOV64rm,
10297                                                X86::LCMPXCHG64,
10298                                                X86::NOT64r, X86::RAX,
10299                                                X86::GR64RegisterClass);
10300   case X86::ATOMXOR64:
10301     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10302                                                X86::XOR64ri32, X86::MOV64rm,
10303                                                X86::LCMPXCHG64,
10304                                                X86::NOT64r, X86::RAX,
10305                                                X86::GR64RegisterClass);
10306   case X86::ATOMNAND64:
10307     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10308                                                X86::AND64ri32, X86::MOV64rm,
10309                                                X86::LCMPXCHG64,
10310                                                X86::NOT64r, X86::RAX,
10311                                                X86::GR64RegisterClass, true);
10312   case X86::ATOMMIN64:
10313     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10314   case X86::ATOMMAX64:
10315     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10316   case X86::ATOMUMIN64:
10317     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10318   case X86::ATOMUMAX64:
10319     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10320
10321   // This group does 64-bit operations on a 32-bit host.
10322   case X86::ATOMAND6432:
10323     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10324                                                X86::AND32rr, X86::AND32rr,
10325                                                X86::AND32ri, X86::AND32ri,
10326                                                false);
10327   case X86::ATOMOR6432:
10328     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10329                                                X86::OR32rr, X86::OR32rr,
10330                                                X86::OR32ri, X86::OR32ri,
10331                                                false);
10332   case X86::ATOMXOR6432:
10333     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10334                                                X86::XOR32rr, X86::XOR32rr,
10335                                                X86::XOR32ri, X86::XOR32ri,
10336                                                false);
10337   case X86::ATOMNAND6432:
10338     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10339                                                X86::AND32rr, X86::AND32rr,
10340                                                X86::AND32ri, X86::AND32ri,
10341                                                true);
10342   case X86::ATOMADD6432:
10343     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10344                                                X86::ADD32rr, X86::ADC32rr,
10345                                                X86::ADD32ri, X86::ADC32ri,
10346                                                false);
10347   case X86::ATOMSUB6432:
10348     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10349                                                X86::SUB32rr, X86::SBB32rr,
10350                                                X86::SUB32ri, X86::SBB32ri,
10351                                                false);
10352   case X86::ATOMSWAP6432:
10353     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10354                                                X86::MOV32rr, X86::MOV32rr,
10355                                                X86::MOV32ri, X86::MOV32ri,
10356                                                false);
10357   case X86::VASTART_SAVE_XMM_REGS:
10358     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10359
10360   case X86::VAARG_64:
10361     return EmitVAARG64WithCustomInserter(MI, BB);
10362   }
10363 }
10364
10365 //===----------------------------------------------------------------------===//
10366 //                           X86 Optimization Hooks
10367 //===----------------------------------------------------------------------===//
10368
10369 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10370                                                        const APInt &Mask,
10371                                                        APInt &KnownZero,
10372                                                        APInt &KnownOne,
10373                                                        const SelectionDAG &DAG,
10374                                                        unsigned Depth) const {
10375   unsigned Opc = Op.getOpcode();
10376   assert((Opc >= ISD::BUILTIN_OP_END ||
10377           Opc == ISD::INTRINSIC_WO_CHAIN ||
10378           Opc == ISD::INTRINSIC_W_CHAIN ||
10379           Opc == ISD::INTRINSIC_VOID) &&
10380          "Should use MaskedValueIsZero if you don't know whether Op"
10381          " is a target node!");
10382
10383   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10384   switch (Opc) {
10385   default: break;
10386   case X86ISD::ADD:
10387   case X86ISD::SUB:
10388   case X86ISD::ADC:
10389   case X86ISD::SBB:
10390   case X86ISD::SMUL:
10391   case X86ISD::UMUL:
10392   case X86ISD::INC:
10393   case X86ISD::DEC:
10394   case X86ISD::OR:
10395   case X86ISD::XOR:
10396   case X86ISD::AND:
10397     // These nodes' second result is a boolean.
10398     if (Op.getResNo() == 0)
10399       break;
10400     // Fallthrough
10401   case X86ISD::SETCC:
10402     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10403                                        Mask.getBitWidth() - 1);
10404     break;
10405   }
10406 }
10407
10408 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10409                                                          unsigned Depth) const {
10410   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10411   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10412     return Op.getValueType().getScalarType().getSizeInBits();
10413
10414   // Fallback case.
10415   return 1;
10416 }
10417
10418 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10419 /// node is a GlobalAddress + offset.
10420 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10421                                        const GlobalValue* &GA,
10422                                        int64_t &Offset) const {
10423   if (N->getOpcode() == X86ISD::Wrapper) {
10424     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10425       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10426       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10427       return true;
10428     }
10429   }
10430   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10431 }
10432
10433 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10434 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10435 /// if the load addresses are consecutive, non-overlapping, and in the right
10436 /// order.
10437 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10438                                      TargetLowering::DAGCombinerInfo &DCI) {
10439   DebugLoc dl = N->getDebugLoc();
10440   EVT VT = N->getValueType(0);
10441
10442   if (VT.getSizeInBits() != 128)
10443     return SDValue();
10444
10445   // Don't create instructions with illegal types after legalize types has run.
10446   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10447   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10448     return SDValue();
10449
10450   SmallVector<SDValue, 16> Elts;
10451   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10452     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10453
10454   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10455 }
10456
10457 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10458 /// generation and convert it from being a bunch of shuffles and extracts
10459 /// to a simple store and scalar loads to extract the elements.
10460 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10461                                                 const TargetLowering &TLI) {
10462   SDValue InputVector = N->getOperand(0);
10463
10464   // Only operate on vectors of 4 elements, where the alternative shuffling
10465   // gets to be more expensive.
10466   if (InputVector.getValueType() != MVT::v4i32)
10467     return SDValue();
10468
10469   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10470   // single use which is a sign-extend or zero-extend, and all elements are
10471   // used.
10472   SmallVector<SDNode *, 4> Uses;
10473   unsigned ExtractedElements = 0;
10474   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10475        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10476     if (UI.getUse().getResNo() != InputVector.getResNo())
10477       return SDValue();
10478
10479     SDNode *Extract = *UI;
10480     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10481       return SDValue();
10482
10483     if (Extract->getValueType(0) != MVT::i32)
10484       return SDValue();
10485     if (!Extract->hasOneUse())
10486       return SDValue();
10487     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10488         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10489       return SDValue();
10490     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10491       return SDValue();
10492
10493     // Record which element was extracted.
10494     ExtractedElements |=
10495       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10496
10497     Uses.push_back(Extract);
10498   }
10499
10500   // If not all the elements were used, this may not be worthwhile.
10501   if (ExtractedElements != 15)
10502     return SDValue();
10503
10504   // Ok, we've now decided to do the transformation.
10505   DebugLoc dl = InputVector.getDebugLoc();
10506
10507   // Store the value to a temporary stack slot.
10508   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10509   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10510                             MachinePointerInfo(), false, false, 0);
10511
10512   // Replace each use (extract) with a load of the appropriate element.
10513   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10514        UE = Uses.end(); UI != UE; ++UI) {
10515     SDNode *Extract = *UI;
10516
10517     // Compute the element's address.
10518     SDValue Idx = Extract->getOperand(1);
10519     unsigned EltSize =
10520         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10521     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10522     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10523
10524     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10525                                      StackPtr, OffsetVal);
10526
10527     // Load the scalar.
10528     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10529                                      ScalarAddr, MachinePointerInfo(),
10530                                      false, false, 0);
10531
10532     // Replace the exact with the load.
10533     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10534   }
10535
10536   // The replacement was made in place; don't return anything.
10537   return SDValue();
10538 }
10539
10540 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10541 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10542                                     const X86Subtarget *Subtarget) {
10543   DebugLoc DL = N->getDebugLoc();
10544   SDValue Cond = N->getOperand(0);
10545   // Get the LHS/RHS of the select.
10546   SDValue LHS = N->getOperand(1);
10547   SDValue RHS = N->getOperand(2);
10548
10549   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10550   // instructions match the semantics of the common C idiom x<y?x:y but not
10551   // x<=y?x:y, because of how they handle negative zero (which can be
10552   // ignored in unsafe-math mode).
10553   if (Subtarget->hasSSE2() &&
10554       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10555       Cond.getOpcode() == ISD::SETCC) {
10556     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10557
10558     unsigned Opcode = 0;
10559     // Check for x CC y ? x : y.
10560     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10561         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10562       switch (CC) {
10563       default: break;
10564       case ISD::SETULT:
10565         // Converting this to a min would handle NaNs incorrectly, and swapping
10566         // the operands would cause it to handle comparisons between positive
10567         // and negative zero incorrectly.
10568         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10569           if (!UnsafeFPMath &&
10570               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10571             break;
10572           std::swap(LHS, RHS);
10573         }
10574         Opcode = X86ISD::FMIN;
10575         break;
10576       case ISD::SETOLE:
10577         // Converting this to a min would handle comparisons between positive
10578         // and negative zero incorrectly.
10579         if (!UnsafeFPMath &&
10580             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10581           break;
10582         Opcode = X86ISD::FMIN;
10583         break;
10584       case ISD::SETULE:
10585         // Converting this to a min would handle both negative zeros and NaNs
10586         // incorrectly, but we can swap the operands to fix both.
10587         std::swap(LHS, RHS);
10588       case ISD::SETOLT:
10589       case ISD::SETLT:
10590       case ISD::SETLE:
10591         Opcode = X86ISD::FMIN;
10592         break;
10593
10594       case ISD::SETOGE:
10595         // Converting this to a max would handle comparisons between positive
10596         // and negative zero incorrectly.
10597         if (!UnsafeFPMath &&
10598             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10599           break;
10600         Opcode = X86ISD::FMAX;
10601         break;
10602       case ISD::SETUGT:
10603         // Converting this to a max would handle NaNs incorrectly, and swapping
10604         // the operands would cause it to handle comparisons between positive
10605         // and negative zero incorrectly.
10606         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10607           if (!UnsafeFPMath &&
10608               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10609             break;
10610           std::swap(LHS, RHS);
10611         }
10612         Opcode = X86ISD::FMAX;
10613         break;
10614       case ISD::SETUGE:
10615         // Converting this to a max would handle both negative zeros and NaNs
10616         // incorrectly, but we can swap the operands to fix both.
10617         std::swap(LHS, RHS);
10618       case ISD::SETOGT:
10619       case ISD::SETGT:
10620       case ISD::SETGE:
10621         Opcode = X86ISD::FMAX;
10622         break;
10623       }
10624     // Check for x CC y ? y : x -- a min/max with reversed arms.
10625     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10626                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10627       switch (CC) {
10628       default: break;
10629       case ISD::SETOGE:
10630         // Converting this to a min would handle comparisons between positive
10631         // and negative zero incorrectly, and swapping the operands would
10632         // cause it to handle NaNs incorrectly.
10633         if (!UnsafeFPMath &&
10634             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10635           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10636             break;
10637           std::swap(LHS, RHS);
10638         }
10639         Opcode = X86ISD::FMIN;
10640         break;
10641       case ISD::SETUGT:
10642         // Converting this to a min would handle NaNs incorrectly.
10643         if (!UnsafeFPMath &&
10644             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10645           break;
10646         Opcode = X86ISD::FMIN;
10647         break;
10648       case ISD::SETUGE:
10649         // Converting this to a min would handle both negative zeros and NaNs
10650         // incorrectly, but we can swap the operands to fix both.
10651         std::swap(LHS, RHS);
10652       case ISD::SETOGT:
10653       case ISD::SETGT:
10654       case ISD::SETGE:
10655         Opcode = X86ISD::FMIN;
10656         break;
10657
10658       case ISD::SETULT:
10659         // Converting this to a max would handle NaNs incorrectly.
10660         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10661           break;
10662         Opcode = X86ISD::FMAX;
10663         break;
10664       case ISD::SETOLE:
10665         // Converting this to a max would handle comparisons between positive
10666         // and negative zero incorrectly, and swapping the operands would
10667         // cause it to handle NaNs incorrectly.
10668         if (!UnsafeFPMath &&
10669             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10670           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10671             break;
10672           std::swap(LHS, RHS);
10673         }
10674         Opcode = X86ISD::FMAX;
10675         break;
10676       case ISD::SETULE:
10677         // Converting this to a max would handle both negative zeros and NaNs
10678         // incorrectly, but we can swap the operands to fix both.
10679         std::swap(LHS, RHS);
10680       case ISD::SETOLT:
10681       case ISD::SETLT:
10682       case ISD::SETLE:
10683         Opcode = X86ISD::FMAX;
10684         break;
10685       }
10686     }
10687
10688     if (Opcode)
10689       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10690   }
10691
10692   // If this is a select between two integer constants, try to do some
10693   // optimizations.
10694   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10695     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10696       // Don't do this for crazy integer types.
10697       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10698         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10699         // so that TrueC (the true value) is larger than FalseC.
10700         bool NeedsCondInvert = false;
10701
10702         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10703             // Efficiently invertible.
10704             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10705              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10706               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10707           NeedsCondInvert = true;
10708           std::swap(TrueC, FalseC);
10709         }
10710
10711         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10712         if (FalseC->getAPIntValue() == 0 &&
10713             TrueC->getAPIntValue().isPowerOf2()) {
10714           if (NeedsCondInvert) // Invert the condition if needed.
10715             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10716                                DAG.getConstant(1, Cond.getValueType()));
10717
10718           // Zero extend the condition if needed.
10719           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10720
10721           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10722           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10723                              DAG.getConstant(ShAmt, MVT::i8));
10724         }
10725
10726         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10727         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10728           if (NeedsCondInvert) // Invert the condition if needed.
10729             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10730                                DAG.getConstant(1, Cond.getValueType()));
10731
10732           // Zero extend the condition if needed.
10733           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10734                              FalseC->getValueType(0), Cond);
10735           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10736                              SDValue(FalseC, 0));
10737         }
10738
10739         // Optimize cases that will turn into an LEA instruction.  This requires
10740         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10741         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10742           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10743           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10744
10745           bool isFastMultiplier = false;
10746           if (Diff < 10) {
10747             switch ((unsigned char)Diff) {
10748               default: break;
10749               case 1:  // result = add base, cond
10750               case 2:  // result = lea base(    , cond*2)
10751               case 3:  // result = lea base(cond, cond*2)
10752               case 4:  // result = lea base(    , cond*4)
10753               case 5:  // result = lea base(cond, cond*4)
10754               case 8:  // result = lea base(    , cond*8)
10755               case 9:  // result = lea base(cond, cond*8)
10756                 isFastMultiplier = true;
10757                 break;
10758             }
10759           }
10760
10761           if (isFastMultiplier) {
10762             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10763             if (NeedsCondInvert) // Invert the condition if needed.
10764               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10765                                  DAG.getConstant(1, Cond.getValueType()));
10766
10767             // Zero extend the condition if needed.
10768             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10769                                Cond);
10770             // Scale the condition by the difference.
10771             if (Diff != 1)
10772               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10773                                  DAG.getConstant(Diff, Cond.getValueType()));
10774
10775             // Add the base if non-zero.
10776             if (FalseC->getAPIntValue() != 0)
10777               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10778                                  SDValue(FalseC, 0));
10779             return Cond;
10780           }
10781         }
10782       }
10783   }
10784
10785   return SDValue();
10786 }
10787
10788 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10789 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10790                                   TargetLowering::DAGCombinerInfo &DCI) {
10791   DebugLoc DL = N->getDebugLoc();
10792
10793   // If the flag operand isn't dead, don't touch this CMOV.
10794   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10795     return SDValue();
10796
10797   // If this is a select between two integer constants, try to do some
10798   // optimizations.  Note that the operands are ordered the opposite of SELECT
10799   // operands.
10800   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10801     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10802       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10803       // larger than FalseC (the false value).
10804       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10805
10806       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10807         CC = X86::GetOppositeBranchCondition(CC);
10808         std::swap(TrueC, FalseC);
10809       }
10810
10811       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10812       // This is efficient for any integer data type (including i8/i16) and
10813       // shift amount.
10814       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10815         SDValue Cond = N->getOperand(3);
10816         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10817                            DAG.getConstant(CC, MVT::i8), Cond);
10818
10819         // Zero extend the condition if needed.
10820         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10821
10822         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10823         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10824                            DAG.getConstant(ShAmt, MVT::i8));
10825         if (N->getNumValues() == 2)  // Dead flag value?
10826           return DCI.CombineTo(N, Cond, SDValue());
10827         return Cond;
10828       }
10829
10830       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10831       // for any integer data type, including i8/i16.
10832       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10833         SDValue Cond = N->getOperand(3);
10834         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10835                            DAG.getConstant(CC, MVT::i8), Cond);
10836
10837         // Zero extend the condition if needed.
10838         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10839                            FalseC->getValueType(0), Cond);
10840         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10841                            SDValue(FalseC, 0));
10842
10843         if (N->getNumValues() == 2)  // Dead flag value?
10844           return DCI.CombineTo(N, Cond, SDValue());
10845         return Cond;
10846       }
10847
10848       // Optimize cases that will turn into an LEA instruction.  This requires
10849       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10850       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10851         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10852         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10853
10854         bool isFastMultiplier = false;
10855         if (Diff < 10) {
10856           switch ((unsigned char)Diff) {
10857           default: break;
10858           case 1:  // result = add base, cond
10859           case 2:  // result = lea base(    , cond*2)
10860           case 3:  // result = lea base(cond, cond*2)
10861           case 4:  // result = lea base(    , cond*4)
10862           case 5:  // result = lea base(cond, cond*4)
10863           case 8:  // result = lea base(    , cond*8)
10864           case 9:  // result = lea base(cond, cond*8)
10865             isFastMultiplier = true;
10866             break;
10867           }
10868         }
10869
10870         if (isFastMultiplier) {
10871           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10872           SDValue Cond = N->getOperand(3);
10873           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10874                              DAG.getConstant(CC, MVT::i8), Cond);
10875           // Zero extend the condition if needed.
10876           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10877                              Cond);
10878           // Scale the condition by the difference.
10879           if (Diff != 1)
10880             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10881                                DAG.getConstant(Diff, Cond.getValueType()));
10882
10883           // Add the base if non-zero.
10884           if (FalseC->getAPIntValue() != 0)
10885             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10886                                SDValue(FalseC, 0));
10887           if (N->getNumValues() == 2)  // Dead flag value?
10888             return DCI.CombineTo(N, Cond, SDValue());
10889           return Cond;
10890         }
10891       }
10892     }
10893   }
10894   return SDValue();
10895 }
10896
10897
10898 /// PerformMulCombine - Optimize a single multiply with constant into two
10899 /// in order to implement it with two cheaper instructions, e.g.
10900 /// LEA + SHL, LEA + LEA.
10901 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10902                                  TargetLowering::DAGCombinerInfo &DCI) {
10903   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10904     return SDValue();
10905
10906   EVT VT = N->getValueType(0);
10907   if (VT != MVT::i64)
10908     return SDValue();
10909
10910   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10911   if (!C)
10912     return SDValue();
10913   uint64_t MulAmt = C->getZExtValue();
10914   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10915     return SDValue();
10916
10917   uint64_t MulAmt1 = 0;
10918   uint64_t MulAmt2 = 0;
10919   if ((MulAmt % 9) == 0) {
10920     MulAmt1 = 9;
10921     MulAmt2 = MulAmt / 9;
10922   } else if ((MulAmt % 5) == 0) {
10923     MulAmt1 = 5;
10924     MulAmt2 = MulAmt / 5;
10925   } else if ((MulAmt % 3) == 0) {
10926     MulAmt1 = 3;
10927     MulAmt2 = MulAmt / 3;
10928   }
10929   if (MulAmt2 &&
10930       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10931     DebugLoc DL = N->getDebugLoc();
10932
10933     if (isPowerOf2_64(MulAmt2) &&
10934         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10935       // If second multiplifer is pow2, issue it first. We want the multiply by
10936       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10937       // is an add.
10938       std::swap(MulAmt1, MulAmt2);
10939
10940     SDValue NewMul;
10941     if (isPowerOf2_64(MulAmt1))
10942       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10943                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10944     else
10945       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10946                            DAG.getConstant(MulAmt1, VT));
10947
10948     if (isPowerOf2_64(MulAmt2))
10949       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10950                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10951     else
10952       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10953                            DAG.getConstant(MulAmt2, VT));
10954
10955     // Do not add new nodes to DAG combiner worklist.
10956     DCI.CombineTo(N, NewMul, false);
10957   }
10958   return SDValue();
10959 }
10960
10961 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10962   SDValue N0 = N->getOperand(0);
10963   SDValue N1 = N->getOperand(1);
10964   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10965   EVT VT = N0.getValueType();
10966
10967   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10968   // since the result of setcc_c is all zero's or all ones.
10969   if (N1C && N0.getOpcode() == ISD::AND &&
10970       N0.getOperand(1).getOpcode() == ISD::Constant) {
10971     SDValue N00 = N0.getOperand(0);
10972     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10973         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10974           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10975          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10976       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10977       APInt ShAmt = N1C->getAPIntValue();
10978       Mask = Mask.shl(ShAmt);
10979       if (Mask != 0)
10980         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10981                            N00, DAG.getConstant(Mask, VT));
10982     }
10983   }
10984
10985   return SDValue();
10986 }
10987
10988 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10989 ///                       when possible.
10990 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10991                                    const X86Subtarget *Subtarget) {
10992   EVT VT = N->getValueType(0);
10993   if (!VT.isVector() && VT.isInteger() &&
10994       N->getOpcode() == ISD::SHL)
10995     return PerformSHLCombine(N, DAG);
10996
10997   // On X86 with SSE2 support, we can transform this to a vector shift if
10998   // all elements are shifted by the same amount.  We can't do this in legalize
10999   // because the a constant vector is typically transformed to a constant pool
11000   // so we have no knowledge of the shift amount.
11001   if (!Subtarget->hasSSE2())
11002     return SDValue();
11003
11004   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
11005     return SDValue();
11006
11007   SDValue ShAmtOp = N->getOperand(1);
11008   EVT EltVT = VT.getVectorElementType();
11009   DebugLoc DL = N->getDebugLoc();
11010   SDValue BaseShAmt = SDValue();
11011   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
11012     unsigned NumElts = VT.getVectorNumElements();
11013     unsigned i = 0;
11014     for (; i != NumElts; ++i) {
11015       SDValue Arg = ShAmtOp.getOperand(i);
11016       if (Arg.getOpcode() == ISD::UNDEF) continue;
11017       BaseShAmt = Arg;
11018       break;
11019     }
11020     for (; i != NumElts; ++i) {
11021       SDValue Arg = ShAmtOp.getOperand(i);
11022       if (Arg.getOpcode() == ISD::UNDEF) continue;
11023       if (Arg != BaseShAmt) {
11024         return SDValue();
11025       }
11026     }
11027   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11028              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11029     SDValue InVec = ShAmtOp.getOperand(0);
11030     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11031       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11032       unsigned i = 0;
11033       for (; i != NumElts; ++i) {
11034         SDValue Arg = InVec.getOperand(i);
11035         if (Arg.getOpcode() == ISD::UNDEF) continue;
11036         BaseShAmt = Arg;
11037         break;
11038       }
11039     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11040        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11041          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11042          if (C->getZExtValue() == SplatIdx)
11043            BaseShAmt = InVec.getOperand(1);
11044        }
11045     }
11046     if (BaseShAmt.getNode() == 0)
11047       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11048                               DAG.getIntPtrConstant(0));
11049   } else
11050     return SDValue();
11051
11052   // The shift amount is an i32.
11053   if (EltVT.bitsGT(MVT::i32))
11054     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11055   else if (EltVT.bitsLT(MVT::i32))
11056     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11057
11058   // The shift amount is identical so we can do a vector shift.
11059   SDValue  ValOp = N->getOperand(0);
11060   switch (N->getOpcode()) {
11061   default:
11062     llvm_unreachable("Unknown shift opcode!");
11063     break;
11064   case ISD::SHL:
11065     if (VT == MVT::v2i64)
11066       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11067                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11068                          ValOp, BaseShAmt);
11069     if (VT == MVT::v4i32)
11070       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11071                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11072                          ValOp, BaseShAmt);
11073     if (VT == MVT::v8i16)
11074       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11075                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11076                          ValOp, BaseShAmt);
11077     break;
11078   case ISD::SRA:
11079     if (VT == MVT::v4i32)
11080       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11081                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11082                          ValOp, BaseShAmt);
11083     if (VT == MVT::v8i16)
11084       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11085                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11086                          ValOp, BaseShAmt);
11087     break;
11088   case ISD::SRL:
11089     if (VT == MVT::v2i64)
11090       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11091                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11092                          ValOp, BaseShAmt);
11093     if (VT == MVT::v4i32)
11094       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11095                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11096                          ValOp, BaseShAmt);
11097     if (VT ==  MVT::v8i16)
11098       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11099                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11100                          ValOp, BaseShAmt);
11101     break;
11102   }
11103   return SDValue();
11104 }
11105
11106
11107 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11108                                  TargetLowering::DAGCombinerInfo &DCI,
11109                                  const X86Subtarget *Subtarget) {
11110   if (DCI.isBeforeLegalizeOps())
11111     return SDValue();
11112   
11113   // Want to form PANDN nodes, in the hopes of then easily combining them with
11114   // OR and AND nodes to form PBLEND/PSIGN.
11115   EVT VT = N->getValueType(0);
11116   if (VT != MVT::v2i64)
11117     return SDValue();
11118   
11119   SDValue N0 = N->getOperand(0);
11120   SDValue N1 = N->getOperand(1);
11121   DebugLoc DL = N->getDebugLoc();
11122   
11123   // Check LHS for vnot
11124   if (N0.getOpcode() == ISD::XOR && 
11125       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11126     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11127
11128   // Check RHS for vnot
11129   if (N1.getOpcode() == ISD::XOR &&
11130       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11131     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11132   
11133   return SDValue();
11134 }
11135
11136 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11137                                 TargetLowering::DAGCombinerInfo &DCI,
11138                                 const X86Subtarget *Subtarget) {
11139   if (DCI.isBeforeLegalizeOps())
11140     return SDValue();
11141
11142   EVT VT = N->getValueType(0);
11143   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11144     return SDValue();
11145
11146   SDValue N0 = N->getOperand(0);
11147   SDValue N1 = N->getOperand(1);
11148   
11149   // look for psign/blend
11150   if (Subtarget->hasSSSE3()) {
11151     if (VT == MVT::v2i64) {
11152       // Canonicalize pandn to RHS
11153       if (N0.getOpcode() == X86ISD::PANDN)
11154         std::swap(N0, N1);
11155       // or (and (m, x), (pandn m, y))
11156       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11157         SDValue Mask = N1.getOperand(0);
11158         SDValue X    = N1.getOperand(1);
11159         SDValue Y;
11160         if (N0.getOperand(0) == Mask)
11161           Y = N0.getOperand(1);
11162         if (N0.getOperand(1) == Mask)
11163           Y = N0.getOperand(0);
11164         
11165         // Check to see if the mask appeared in both the AND and PANDN and
11166         if (!Y.getNode())
11167           return SDValue();
11168         
11169         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11170         if (Mask.getOpcode() != ISD::BITCAST ||
11171             X.getOpcode() != ISD::BITCAST ||
11172             Y.getOpcode() != ISD::BITCAST)
11173           return SDValue();
11174         
11175         // Look through mask bitcast.
11176         Mask = Mask.getOperand(0);
11177         EVT MaskVT = Mask.getValueType();
11178
11179         // Validate that the Mask operand is a vector sra node.  The sra node
11180         // will be an intrinsic.
11181         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11182           return SDValue();
11183         
11184         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11185         // there is no psrai.b
11186         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11187         case Intrinsic::x86_sse2_psrai_w:
11188         case Intrinsic::x86_sse2_psrai_d:
11189           break;
11190         default: return SDValue();
11191         }
11192         
11193         // Check that the SRA is all signbits.
11194         SDValue SraC = Mask.getOperand(2);
11195         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11196         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11197         if ((SraAmt + 1) != EltBits)
11198           return SDValue();
11199         
11200         DebugLoc DL = N->getDebugLoc();
11201
11202         // Now we know we at least have a plendvb with the mask val.  See if
11203         // we can form a psignb/w/d.
11204         // psign = x.type == y.type == mask.type && y = sub(0, x);
11205         X = X.getOperand(0);
11206         Y = Y.getOperand(0);
11207         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11208             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11209             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11210           unsigned Opc = 0;
11211           switch (EltBits) {
11212           case 8: Opc = X86ISD::PSIGNB; break;
11213           case 16: Opc = X86ISD::PSIGNW; break;
11214           case 32: Opc = X86ISD::PSIGND; break;
11215           default: break;
11216           }
11217           if (Opc) {
11218             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11219             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11220           }
11221         }
11222         // PBLENDVB only available on SSE 4.1
11223         if (!Subtarget->hasSSE41())
11224           return SDValue();
11225         
11226         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11227         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11228         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11229         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11230         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11231       }
11232     }
11233   }
11234   
11235   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11236   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11237     std::swap(N0, N1);
11238   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11239     return SDValue();
11240   if (!N0.hasOneUse() || !N1.hasOneUse())
11241     return SDValue();
11242
11243   SDValue ShAmt0 = N0.getOperand(1);
11244   if (ShAmt0.getValueType() != MVT::i8)
11245     return SDValue();
11246   SDValue ShAmt1 = N1.getOperand(1);
11247   if (ShAmt1.getValueType() != MVT::i8)
11248     return SDValue();
11249   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11250     ShAmt0 = ShAmt0.getOperand(0);
11251   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11252     ShAmt1 = ShAmt1.getOperand(0);
11253
11254   DebugLoc DL = N->getDebugLoc();
11255   unsigned Opc = X86ISD::SHLD;
11256   SDValue Op0 = N0.getOperand(0);
11257   SDValue Op1 = N1.getOperand(0);
11258   if (ShAmt0.getOpcode() == ISD::SUB) {
11259     Opc = X86ISD::SHRD;
11260     std::swap(Op0, Op1);
11261     std::swap(ShAmt0, ShAmt1);
11262   }
11263
11264   unsigned Bits = VT.getSizeInBits();
11265   if (ShAmt1.getOpcode() == ISD::SUB) {
11266     SDValue Sum = ShAmt1.getOperand(0);
11267     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11268       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11269       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11270         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11271       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11272         return DAG.getNode(Opc, DL, VT,
11273                            Op0, Op1,
11274                            DAG.getNode(ISD::TRUNCATE, DL,
11275                                        MVT::i8, ShAmt0));
11276     }
11277   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11278     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11279     if (ShAmt0C &&
11280         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11281       return DAG.getNode(Opc, DL, VT,
11282                          N0.getOperand(0), N1.getOperand(0),
11283                          DAG.getNode(ISD::TRUNCATE, DL,
11284                                        MVT::i8, ShAmt0));
11285   }
11286   
11287   return SDValue();
11288 }
11289
11290 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11291 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11292                                    const X86Subtarget *Subtarget) {
11293   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11294   // the FP state in cases where an emms may be missing.
11295   // A preferable solution to the general problem is to figure out the right
11296   // places to insert EMMS.  This qualifies as a quick hack.
11297
11298   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11299   StoreSDNode *St = cast<StoreSDNode>(N);
11300   EVT VT = St->getValue().getValueType();
11301   if (VT.getSizeInBits() != 64)
11302     return SDValue();
11303
11304   const Function *F = DAG.getMachineFunction().getFunction();
11305   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11306   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11307     && Subtarget->hasSSE2();
11308   if ((VT.isVector() ||
11309        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11310       isa<LoadSDNode>(St->getValue()) &&
11311       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11312       St->getChain().hasOneUse() && !St->isVolatile()) {
11313     SDNode* LdVal = St->getValue().getNode();
11314     LoadSDNode *Ld = 0;
11315     int TokenFactorIndex = -1;
11316     SmallVector<SDValue, 8> Ops;
11317     SDNode* ChainVal = St->getChain().getNode();
11318     // Must be a store of a load.  We currently handle two cases:  the load
11319     // is a direct child, and it's under an intervening TokenFactor.  It is
11320     // possible to dig deeper under nested TokenFactors.
11321     if (ChainVal == LdVal)
11322       Ld = cast<LoadSDNode>(St->getChain());
11323     else if (St->getValue().hasOneUse() &&
11324              ChainVal->getOpcode() == ISD::TokenFactor) {
11325       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11326         if (ChainVal->getOperand(i).getNode() == LdVal) {
11327           TokenFactorIndex = i;
11328           Ld = cast<LoadSDNode>(St->getValue());
11329         } else
11330           Ops.push_back(ChainVal->getOperand(i));
11331       }
11332     }
11333
11334     if (!Ld || !ISD::isNormalLoad(Ld))
11335       return SDValue();
11336
11337     // If this is not the MMX case, i.e. we are just turning i64 load/store
11338     // into f64 load/store, avoid the transformation if there are multiple
11339     // uses of the loaded value.
11340     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11341       return SDValue();
11342
11343     DebugLoc LdDL = Ld->getDebugLoc();
11344     DebugLoc StDL = N->getDebugLoc();
11345     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11346     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11347     // pair instead.
11348     if (Subtarget->is64Bit() || F64IsLegal) {
11349       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11350       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11351                                   Ld->getPointerInfo(), Ld->isVolatile(),
11352                                   Ld->isNonTemporal(), Ld->getAlignment());
11353       SDValue NewChain = NewLd.getValue(1);
11354       if (TokenFactorIndex != -1) {
11355         Ops.push_back(NewChain);
11356         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11357                                Ops.size());
11358       }
11359       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11360                           St->getPointerInfo(),
11361                           St->isVolatile(), St->isNonTemporal(),
11362                           St->getAlignment());
11363     }
11364
11365     // Otherwise, lower to two pairs of 32-bit loads / stores.
11366     SDValue LoAddr = Ld->getBasePtr();
11367     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11368                                  DAG.getConstant(4, MVT::i32));
11369
11370     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11371                                Ld->getPointerInfo(),
11372                                Ld->isVolatile(), Ld->isNonTemporal(),
11373                                Ld->getAlignment());
11374     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11375                                Ld->getPointerInfo().getWithOffset(4),
11376                                Ld->isVolatile(), Ld->isNonTemporal(),
11377                                MinAlign(Ld->getAlignment(), 4));
11378
11379     SDValue NewChain = LoLd.getValue(1);
11380     if (TokenFactorIndex != -1) {
11381       Ops.push_back(LoLd);
11382       Ops.push_back(HiLd);
11383       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11384                              Ops.size());
11385     }
11386
11387     LoAddr = St->getBasePtr();
11388     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11389                          DAG.getConstant(4, MVT::i32));
11390
11391     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11392                                 St->getPointerInfo(),
11393                                 St->isVolatile(), St->isNonTemporal(),
11394                                 St->getAlignment());
11395     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11396                                 St->getPointerInfo().getWithOffset(4),
11397                                 St->isVolatile(),
11398                                 St->isNonTemporal(),
11399                                 MinAlign(St->getAlignment(), 4));
11400     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11401   }
11402   return SDValue();
11403 }
11404
11405 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11406 /// X86ISD::FXOR nodes.
11407 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11408   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11409   // F[X]OR(0.0, x) -> x
11410   // F[X]OR(x, 0.0) -> x
11411   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11412     if (C->getValueAPF().isPosZero())
11413       return N->getOperand(1);
11414   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11415     if (C->getValueAPF().isPosZero())
11416       return N->getOperand(0);
11417   return SDValue();
11418 }
11419
11420 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11421 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11422   // FAND(0.0, x) -> 0.0
11423   // FAND(x, 0.0) -> 0.0
11424   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11425     if (C->getValueAPF().isPosZero())
11426       return N->getOperand(0);
11427   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11428     if (C->getValueAPF().isPosZero())
11429       return N->getOperand(1);
11430   return SDValue();
11431 }
11432
11433 static SDValue PerformBTCombine(SDNode *N,
11434                                 SelectionDAG &DAG,
11435                                 TargetLowering::DAGCombinerInfo &DCI) {
11436   // BT ignores high bits in the bit index operand.
11437   SDValue Op1 = N->getOperand(1);
11438   if (Op1.hasOneUse()) {
11439     unsigned BitWidth = Op1.getValueSizeInBits();
11440     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11441     APInt KnownZero, KnownOne;
11442     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11443                                           !DCI.isBeforeLegalizeOps());
11444     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11445     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11446         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11447       DCI.CommitTargetLoweringOpt(TLO);
11448   }
11449   return SDValue();
11450 }
11451
11452 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11453   SDValue Op = N->getOperand(0);
11454   if (Op.getOpcode() == ISD::BITCAST)
11455     Op = Op.getOperand(0);
11456   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11457   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11458       VT.getVectorElementType().getSizeInBits() ==
11459       OpVT.getVectorElementType().getSizeInBits()) {
11460     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11461   }
11462   return SDValue();
11463 }
11464
11465 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11466   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11467   //           (and (i32 x86isd::setcc_carry), 1)
11468   // This eliminates the zext. This transformation is necessary because
11469   // ISD::SETCC is always legalized to i8.
11470   DebugLoc dl = N->getDebugLoc();
11471   SDValue N0 = N->getOperand(0);
11472   EVT VT = N->getValueType(0);
11473   if (N0.getOpcode() == ISD::AND &&
11474       N0.hasOneUse() &&
11475       N0.getOperand(0).hasOneUse()) {
11476     SDValue N00 = N0.getOperand(0);
11477     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11478       return SDValue();
11479     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11480     if (!C || C->getZExtValue() != 1)
11481       return SDValue();
11482     return DAG.getNode(ISD::AND, dl, VT,
11483                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11484                                    N00.getOperand(0), N00.getOperand(1)),
11485                        DAG.getConstant(1, VT));
11486   }
11487
11488   return SDValue();
11489 }
11490
11491 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11492 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11493   unsigned X86CC = N->getConstantOperandVal(0);
11494   SDValue EFLAG = N->getOperand(1);
11495   DebugLoc DL = N->getDebugLoc();
11496   
11497   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11498   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11499   // cases.
11500   if (X86CC == X86::COND_B)
11501     return DAG.getNode(ISD::AND, DL, MVT::i8,
11502                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11503                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11504                        DAG.getConstant(1, MVT::i8));
11505   
11506   return SDValue();
11507 }
11508           
11509 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11510 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11511                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11512   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11513   // the result is either zero or one (depending on the input carry bit).
11514   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11515   if (X86::isZeroNode(N->getOperand(0)) &&
11516       X86::isZeroNode(N->getOperand(1)) &&
11517       // We don't have a good way to replace an EFLAGS use, so only do this when
11518       // dead right now.
11519       SDValue(N, 1).use_empty()) {
11520     DebugLoc DL = N->getDebugLoc();
11521     EVT VT = N->getValueType(0);
11522     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11523     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11524                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11525                                            DAG.getConstant(X86::COND_B,MVT::i8),
11526                                            N->getOperand(2)),
11527                                DAG.getConstant(1, VT));
11528     return DCI.CombineTo(N, Res1, CarryOut);
11529   }
11530
11531   return SDValue();
11532 }
11533
11534 // fold (add Y, (sete  X, 0)) -> adc  0, Y
11535 //      (add Y, (setne X, 0)) -> sbb -1, Y
11536 //      (sub (sete  X, 0), Y) -> sbb  0, Y
11537 //      (sub (setne X, 0), Y) -> adc -1, Y
11538 static SDValue OptimizeConditonalInDecrement(SDNode *N, SelectionDAG &DAG) {
11539   DebugLoc DL = N->getDebugLoc();
11540   
11541   // Look through ZExts.
11542   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
11543   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
11544     return SDValue();
11545
11546   SDValue SetCC = Ext.getOperand(0);
11547   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
11548     return SDValue();
11549
11550   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
11551   if (CC != X86::COND_E && CC != X86::COND_NE)
11552     return SDValue();
11553
11554   SDValue Cmp = SetCC.getOperand(1);
11555   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
11556       !X86::isZeroNode(Cmp.getOperand(1)))
11557     return SDValue();
11558
11559   SDValue CmpOp0 = Cmp.getOperand(0);
11560   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
11561                                DAG.getConstant(1, CmpOp0.getValueType()));
11562
11563   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
11564   if (CC == X86::COND_NE)
11565     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
11566                        DL, OtherVal.getValueType(), OtherVal,
11567                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
11568   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
11569                      DL, OtherVal.getValueType(), OtherVal,
11570                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
11571 }
11572
11573 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11574                                              DAGCombinerInfo &DCI) const {
11575   SelectionDAG &DAG = DCI.DAG;
11576   switch (N->getOpcode()) {
11577   default: break;
11578   case ISD::EXTRACT_VECTOR_ELT:
11579     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11580   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11581   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11582   case ISD::ADD:
11583   case ISD::SUB:            return OptimizeConditonalInDecrement(N, DAG);
11584   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11585   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11586   case ISD::SHL:
11587   case ISD::SRA:
11588   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11589   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11590   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11591   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11592   case X86ISD::FXOR:
11593   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11594   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11595   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11596   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11597   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11598   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11599   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11600   case X86ISD::SHUFPD:
11601   case X86ISD::PALIGN:
11602   case X86ISD::PUNPCKHBW:
11603   case X86ISD::PUNPCKHWD:
11604   case X86ISD::PUNPCKHDQ:
11605   case X86ISD::PUNPCKHQDQ:
11606   case X86ISD::UNPCKHPS:
11607   case X86ISD::UNPCKHPD:
11608   case X86ISD::PUNPCKLBW:
11609   case X86ISD::PUNPCKLWD:
11610   case X86ISD::PUNPCKLDQ:
11611   case X86ISD::PUNPCKLQDQ:
11612   case X86ISD::UNPCKLPS:
11613   case X86ISD::UNPCKLPD:
11614   case X86ISD::MOVHLPS:
11615   case X86ISD::MOVLHPS:
11616   case X86ISD::PSHUFD:
11617   case X86ISD::PSHUFHW:
11618   case X86ISD::PSHUFLW:
11619   case X86ISD::MOVSS:
11620   case X86ISD::MOVSD:
11621   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11622   }
11623
11624   return SDValue();
11625 }
11626
11627 /// isTypeDesirableForOp - Return true if the target has native support for
11628 /// the specified value type and it is 'desirable' to use the type for the
11629 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11630 /// instruction encodings are longer and some i16 instructions are slow.
11631 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11632   if (!isTypeLegal(VT))
11633     return false;
11634   if (VT != MVT::i16)
11635     return true;
11636
11637   switch (Opc) {
11638   default:
11639     return true;
11640   case ISD::LOAD:
11641   case ISD::SIGN_EXTEND:
11642   case ISD::ZERO_EXTEND:
11643   case ISD::ANY_EXTEND:
11644   case ISD::SHL:
11645   case ISD::SRL:
11646   case ISD::SUB:
11647   case ISD::ADD:
11648   case ISD::MUL:
11649   case ISD::AND:
11650   case ISD::OR:
11651   case ISD::XOR:
11652     return false;
11653   }
11654 }
11655
11656 /// IsDesirableToPromoteOp - This method query the target whether it is
11657 /// beneficial for dag combiner to promote the specified node. If true, it
11658 /// should return the desired promotion type by reference.
11659 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11660   EVT VT = Op.getValueType();
11661   if (VT != MVT::i16)
11662     return false;
11663
11664   bool Promote = false;
11665   bool Commute = false;
11666   switch (Op.getOpcode()) {
11667   default: break;
11668   case ISD::LOAD: {
11669     LoadSDNode *LD = cast<LoadSDNode>(Op);
11670     // If the non-extending load has a single use and it's not live out, then it
11671     // might be folded.
11672     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11673                                                      Op.hasOneUse()*/) {
11674       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11675              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11676         // The only case where we'd want to promote LOAD (rather then it being
11677         // promoted as an operand is when it's only use is liveout.
11678         if (UI->getOpcode() != ISD::CopyToReg)
11679           return false;
11680       }
11681     }
11682     Promote = true;
11683     break;
11684   }
11685   case ISD::SIGN_EXTEND:
11686   case ISD::ZERO_EXTEND:
11687   case ISD::ANY_EXTEND:
11688     Promote = true;
11689     break;
11690   case ISD::SHL:
11691   case ISD::SRL: {
11692     SDValue N0 = Op.getOperand(0);
11693     // Look out for (store (shl (load), x)).
11694     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11695       return false;
11696     Promote = true;
11697     break;
11698   }
11699   case ISD::ADD:
11700   case ISD::MUL:
11701   case ISD::AND:
11702   case ISD::OR:
11703   case ISD::XOR:
11704     Commute = true;
11705     // fallthrough
11706   case ISD::SUB: {
11707     SDValue N0 = Op.getOperand(0);
11708     SDValue N1 = Op.getOperand(1);
11709     if (!Commute && MayFoldLoad(N1))
11710       return false;
11711     // Avoid disabling potential load folding opportunities.
11712     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11713       return false;
11714     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11715       return false;
11716     Promote = true;
11717   }
11718   }
11719
11720   PVT = MVT::i32;
11721   return Promote;
11722 }
11723
11724 //===----------------------------------------------------------------------===//
11725 //                           X86 Inline Assembly Support
11726 //===----------------------------------------------------------------------===//
11727
11728 static bool LowerToBSwap(CallInst *CI) {
11729   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11730   // we will turn this bswap into something that will be lowered to logical ops
11731   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11732   // so don't worry about this.
11733
11734   // Verify this is a simple bswap.
11735   if (CI->getNumArgOperands() != 1 ||
11736       CI->getType() != CI->getArgOperand(0)->getType() ||
11737       !CI->getType()->isIntegerTy())
11738     return false;
11739
11740   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11741   if (!Ty || Ty->getBitWidth() % 16 != 0)
11742     return false;
11743
11744   // Okay, we can do this xform, do so now.
11745   const Type *Tys[] = { Ty };
11746   Module *M = CI->getParent()->getParent()->getParent();
11747   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11748
11749   Value *Op = CI->getArgOperand(0);
11750   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11751
11752   CI->replaceAllUsesWith(Op);
11753   CI->eraseFromParent();
11754   return true;
11755 }
11756
11757 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11758   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11759   InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11760
11761   std::string AsmStr = IA->getAsmString();
11762
11763   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11764   SmallVector<StringRef, 4> AsmPieces;
11765   SplitString(AsmStr, AsmPieces, ";\n");
11766
11767   switch (AsmPieces.size()) {
11768   default: return false;
11769   case 1:
11770     AsmStr = AsmPieces[0];
11771     AsmPieces.clear();
11772     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11773
11774     // bswap $0
11775     if (AsmPieces.size() == 2 &&
11776         (AsmPieces[0] == "bswap" ||
11777          AsmPieces[0] == "bswapq" ||
11778          AsmPieces[0] == "bswapl") &&
11779         (AsmPieces[1] == "$0" ||
11780          AsmPieces[1] == "${0:q}")) {
11781       // No need to check constraints, nothing other than the equivalent of
11782       // "=r,0" would be valid here.
11783       return LowerToBSwap(CI);
11784     }
11785     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11786     if (CI->getType()->isIntegerTy(16) &&
11787         AsmPieces.size() == 3 &&
11788         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11789         AsmPieces[1] == "$$8," &&
11790         AsmPieces[2] == "${0:w}" &&
11791         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11792       AsmPieces.clear();
11793       const std::string &Constraints = IA->getConstraintString();
11794       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11795       std::sort(AsmPieces.begin(), AsmPieces.end());
11796       if (AsmPieces.size() == 4 &&
11797           AsmPieces[0] == "~{cc}" &&
11798           AsmPieces[1] == "~{dirflag}" &&
11799           AsmPieces[2] == "~{flags}" &&
11800           AsmPieces[3] == "~{fpsr}") {
11801         return LowerToBSwap(CI);
11802       }
11803     }
11804     break;
11805   case 3:
11806     if (CI->getType()->isIntegerTy(32) &&
11807         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11808       SmallVector<StringRef, 4> Words;
11809       SplitString(AsmPieces[0], Words, " \t,");
11810       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11811           Words[2] == "${0:w}") {
11812         Words.clear();
11813         SplitString(AsmPieces[1], Words, " \t,");
11814         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11815             Words[2] == "$0") {
11816           Words.clear();
11817           SplitString(AsmPieces[2], Words, " \t,");
11818           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11819               Words[2] == "${0:w}") {
11820             AsmPieces.clear();
11821             const std::string &Constraints = IA->getConstraintString();
11822             SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11823             std::sort(AsmPieces.begin(), AsmPieces.end());
11824             if (AsmPieces.size() == 4 &&
11825                 AsmPieces[0] == "~{cc}" &&
11826                 AsmPieces[1] == "~{dirflag}" &&
11827                 AsmPieces[2] == "~{flags}" &&
11828                 AsmPieces[3] == "~{fpsr}") {
11829               return LowerToBSwap(CI);
11830             }
11831           }
11832         }
11833       }
11834     }
11835     if (CI->getType()->isIntegerTy(64) &&
11836         Constraints.size() >= 2 &&
11837         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11838         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11839       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11840       SmallVector<StringRef, 4> Words;
11841       SplitString(AsmPieces[0], Words, " \t");
11842       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11843         Words.clear();
11844         SplitString(AsmPieces[1], Words, " \t");
11845         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11846           Words.clear();
11847           SplitString(AsmPieces[2], Words, " \t,");
11848           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11849               Words[2] == "%edx") {
11850             return LowerToBSwap(CI);
11851           }
11852         }
11853       }
11854     }
11855     break;
11856   }
11857   return false;
11858 }
11859
11860
11861
11862 /// getConstraintType - Given a constraint letter, return the type of
11863 /// constraint it is for this target.
11864 X86TargetLowering::ConstraintType
11865 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11866   if (Constraint.size() == 1) {
11867     switch (Constraint[0]) {
11868     case 'R':
11869     case 'q':
11870     case 'Q':
11871     case 'f':
11872     case 't':
11873     case 'u':
11874     case 'y':
11875     case 'x':
11876     case 'Y':
11877       return C_RegisterClass;
11878     case 'a':
11879     case 'b':
11880     case 'c':
11881     case 'd':
11882     case 'S':
11883     case 'D':
11884     case 'A':
11885       return C_Register;
11886     case 'I':
11887     case 'J':
11888     case 'K':
11889     case 'L':
11890     case 'M':
11891     case 'N':
11892     case 'G':
11893     case 'C':
11894     case 'e':
11895     case 'Z':
11896       return C_Other;
11897     default:
11898       break;
11899     }
11900   }
11901   return TargetLowering::getConstraintType(Constraint);
11902 }
11903
11904 /// Examine constraint type and operand type and determine a weight value.
11905 /// This object must already have been set up with the operand type
11906 /// and the current alternative constraint selected.
11907 TargetLowering::ConstraintWeight
11908   X86TargetLowering::getSingleConstraintMatchWeight(
11909     AsmOperandInfo &info, const char *constraint) const {
11910   ConstraintWeight weight = CW_Invalid;
11911   Value *CallOperandVal = info.CallOperandVal;
11912     // If we don't have a value, we can't do a match,
11913     // but allow it at the lowest weight.
11914   if (CallOperandVal == NULL)
11915     return CW_Default;
11916   const Type *type = CallOperandVal->getType();
11917   // Look at the constraint type.
11918   switch (*constraint) {
11919   default:
11920     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11921   case 'R':
11922   case 'q':
11923   case 'Q':
11924   case 'a':
11925   case 'b':
11926   case 'c':
11927   case 'd':
11928   case 'S':
11929   case 'D':
11930   case 'A':
11931     if (CallOperandVal->getType()->isIntegerTy())
11932       weight = CW_SpecificReg;
11933     break;
11934   case 'f':
11935   case 't':
11936   case 'u':
11937       if (type->isFloatingPointTy())
11938         weight = CW_SpecificReg;
11939       break;
11940   case 'y':
11941       if (type->isX86_MMXTy() && Subtarget->hasMMX())
11942         weight = CW_SpecificReg;
11943       break;
11944   case 'x':
11945   case 'Y':
11946     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11947       weight = CW_Register;
11948     break;
11949   case 'I':
11950     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11951       if (C->getZExtValue() <= 31)
11952         weight = CW_Constant;
11953     }
11954     break;
11955   case 'J':
11956     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11957       if (C->getZExtValue() <= 63)
11958         weight = CW_Constant;
11959     }
11960     break;
11961   case 'K':
11962     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11963       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11964         weight = CW_Constant;
11965     }
11966     break;
11967   case 'L':
11968     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11969       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11970         weight = CW_Constant;
11971     }
11972     break;
11973   case 'M':
11974     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11975       if (C->getZExtValue() <= 3)
11976         weight = CW_Constant;
11977     }
11978     break;
11979   case 'N':
11980     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11981       if (C->getZExtValue() <= 0xff)
11982         weight = CW_Constant;
11983     }
11984     break;
11985   case 'G':
11986   case 'C':
11987     if (dyn_cast<ConstantFP>(CallOperandVal)) {
11988       weight = CW_Constant;
11989     }
11990     break;
11991   case 'e':
11992     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11993       if ((C->getSExtValue() >= -0x80000000LL) &&
11994           (C->getSExtValue() <= 0x7fffffffLL))
11995         weight = CW_Constant;
11996     }
11997     break;
11998   case 'Z':
11999     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
12000       if (C->getZExtValue() <= 0xffffffff)
12001         weight = CW_Constant;
12002     }
12003     break;
12004   }
12005   return weight;
12006 }
12007
12008 /// LowerXConstraint - try to replace an X constraint, which matches anything,
12009 /// with another that has more specific requirements based on the type of the
12010 /// corresponding operand.
12011 const char *X86TargetLowering::
12012 LowerXConstraint(EVT ConstraintVT) const {
12013   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
12014   // 'f' like normal targets.
12015   if (ConstraintVT.isFloatingPoint()) {
12016     if (Subtarget->hasXMMInt())
12017       return "Y";
12018     if (Subtarget->hasXMM())
12019       return "x";
12020   }
12021
12022   return TargetLowering::LowerXConstraint(ConstraintVT);
12023 }
12024
12025 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12026 /// vector.  If it is invalid, don't add anything to Ops.
12027 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12028                                                      char Constraint,
12029                                                      std::vector<SDValue>&Ops,
12030                                                      SelectionDAG &DAG) const {
12031   SDValue Result(0, 0);
12032
12033   switch (Constraint) {
12034   default: break;
12035   case 'I':
12036     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12037       if (C->getZExtValue() <= 31) {
12038         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12039         break;
12040       }
12041     }
12042     return;
12043   case 'J':
12044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12045       if (C->getZExtValue() <= 63) {
12046         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12047         break;
12048       }
12049     }
12050     return;
12051   case 'K':
12052     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12053       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12054         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12055         break;
12056       }
12057     }
12058     return;
12059   case 'N':
12060     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12061       if (C->getZExtValue() <= 255) {
12062         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12063         break;
12064       }
12065     }
12066     return;
12067   case 'e': {
12068     // 32-bit signed value
12069     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12070       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12071                                            C->getSExtValue())) {
12072         // Widen to 64 bits here to get it sign extended.
12073         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12074         break;
12075       }
12076     // FIXME gcc accepts some relocatable values here too, but only in certain
12077     // memory models; it's complicated.
12078     }
12079     return;
12080   }
12081   case 'Z': {
12082     // 32-bit unsigned value
12083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12084       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12085                                            C->getZExtValue())) {
12086         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12087         break;
12088       }
12089     }
12090     // FIXME gcc accepts some relocatable values here too, but only in certain
12091     // memory models; it's complicated.
12092     return;
12093   }
12094   case 'i': {
12095     // Literal immediates are always ok.
12096     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12097       // Widen to 64 bits here to get it sign extended.
12098       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12099       break;
12100     }
12101
12102     // In any sort of PIC mode addresses need to be computed at runtime by
12103     // adding in a register or some sort of table lookup.  These can't
12104     // be used as immediates.
12105     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12106       return;
12107
12108     // If we are in non-pic codegen mode, we allow the address of a global (with
12109     // an optional displacement) to be used with 'i'.
12110     GlobalAddressSDNode *GA = 0;
12111     int64_t Offset = 0;
12112
12113     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12114     while (1) {
12115       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12116         Offset += GA->getOffset();
12117         break;
12118       } else if (Op.getOpcode() == ISD::ADD) {
12119         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12120           Offset += C->getZExtValue();
12121           Op = Op.getOperand(0);
12122           continue;
12123         }
12124       } else if (Op.getOpcode() == ISD::SUB) {
12125         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12126           Offset += -C->getZExtValue();
12127           Op = Op.getOperand(0);
12128           continue;
12129         }
12130       }
12131
12132       // Otherwise, this isn't something we can handle, reject it.
12133       return;
12134     }
12135
12136     const GlobalValue *GV = GA->getGlobal();
12137     // If we require an extra load to get this address, as in PIC mode, we
12138     // can't accept it.
12139     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12140                                                         getTargetMachine())))
12141       return;
12142
12143     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12144                                         GA->getValueType(0), Offset);
12145     break;
12146   }
12147   }
12148
12149   if (Result.getNode()) {
12150     Ops.push_back(Result);
12151     return;
12152   }
12153   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12154 }
12155
12156 std::vector<unsigned> X86TargetLowering::
12157 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12158                                   EVT VT) const {
12159   if (Constraint.size() == 1) {
12160     // FIXME: not handling fp-stack yet!
12161     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12162     default: break;  // Unknown constraint letter
12163     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12164       if (Subtarget->is64Bit()) {
12165         if (VT == MVT::i32)
12166           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12167                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12168                                        X86::R10D,X86::R11D,X86::R12D,
12169                                        X86::R13D,X86::R14D,X86::R15D,
12170                                        X86::EBP, X86::ESP, 0);
12171         else if (VT == MVT::i16)
12172           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12173                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12174                                        X86::R10W,X86::R11W,X86::R12W,
12175                                        X86::R13W,X86::R14W,X86::R15W,
12176                                        X86::BP,  X86::SP, 0);
12177         else if (VT == MVT::i8)
12178           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12179                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12180                                        X86::R10B,X86::R11B,X86::R12B,
12181                                        X86::R13B,X86::R14B,X86::R15B,
12182                                        X86::BPL, X86::SPL, 0);
12183
12184         else if (VT == MVT::i64)
12185           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12186                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12187                                        X86::R10, X86::R11, X86::R12,
12188                                        X86::R13, X86::R14, X86::R15,
12189                                        X86::RBP, X86::RSP, 0);
12190
12191         break;
12192       }
12193       // 32-bit fallthrough
12194     case 'Q':   // Q_REGS
12195       if (VT == MVT::i32)
12196         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12197       else if (VT == MVT::i16)
12198         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12199       else if (VT == MVT::i8)
12200         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12201       else if (VT == MVT::i64)
12202         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12203       break;
12204     }
12205   }
12206
12207   return std::vector<unsigned>();
12208 }
12209
12210 std::pair<unsigned, const TargetRegisterClass*>
12211 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12212                                                 EVT VT) const {
12213   // First, see if this is a constraint that directly corresponds to an LLVM
12214   // register class.
12215   if (Constraint.size() == 1) {
12216     // GCC Constraint Letters
12217     switch (Constraint[0]) {
12218     default: break;
12219     case 'r':   // GENERAL_REGS
12220     case 'l':   // INDEX_REGS
12221       if (VT == MVT::i8)
12222         return std::make_pair(0U, X86::GR8RegisterClass);
12223       if (VT == MVT::i16)
12224         return std::make_pair(0U, X86::GR16RegisterClass);
12225       if (VT == MVT::i32 || !Subtarget->is64Bit())
12226         return std::make_pair(0U, X86::GR32RegisterClass);
12227       return std::make_pair(0U, X86::GR64RegisterClass);
12228     case 'R':   // LEGACY_REGS
12229       if (VT == MVT::i8)
12230         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12231       if (VT == MVT::i16)
12232         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12233       if (VT == MVT::i32 || !Subtarget->is64Bit())
12234         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12235       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12236     case 'f':  // FP Stack registers.
12237       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12238       // value to the correct fpstack register class.
12239       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12240         return std::make_pair(0U, X86::RFP32RegisterClass);
12241       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12242         return std::make_pair(0U, X86::RFP64RegisterClass);
12243       return std::make_pair(0U, X86::RFP80RegisterClass);
12244     case 'y':   // MMX_REGS if MMX allowed.
12245       if (!Subtarget->hasMMX()) break;
12246       return std::make_pair(0U, X86::VR64RegisterClass);
12247     case 'Y':   // SSE_REGS if SSE2 allowed
12248       if (!Subtarget->hasXMMInt()) break;
12249       // FALL THROUGH.
12250     case 'x':   // SSE_REGS if SSE1 allowed
12251       if (!Subtarget->hasXMM()) break;
12252
12253       switch (VT.getSimpleVT().SimpleTy) {
12254       default: break;
12255       // Scalar SSE types.
12256       case MVT::f32:
12257       case MVT::i32:
12258         return std::make_pair(0U, X86::FR32RegisterClass);
12259       case MVT::f64:
12260       case MVT::i64:
12261         return std::make_pair(0U, X86::FR64RegisterClass);
12262       // Vector types.
12263       case MVT::v16i8:
12264       case MVT::v8i16:
12265       case MVT::v4i32:
12266       case MVT::v2i64:
12267       case MVT::v4f32:
12268       case MVT::v2f64:
12269         return std::make_pair(0U, X86::VR128RegisterClass);
12270       }
12271       break;
12272     }
12273   }
12274
12275   // Use the default implementation in TargetLowering to convert the register
12276   // constraint into a member of a register class.
12277   std::pair<unsigned, const TargetRegisterClass*> Res;
12278   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12279
12280   // Not found as a standard register?
12281   if (Res.second == 0) {
12282     // Map st(0) -> st(7) -> ST0
12283     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12284         tolower(Constraint[1]) == 's' &&
12285         tolower(Constraint[2]) == 't' &&
12286         Constraint[3] == '(' &&
12287         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12288         Constraint[5] == ')' &&
12289         Constraint[6] == '}') {
12290
12291       Res.first = X86::ST0+Constraint[4]-'0';
12292       Res.second = X86::RFP80RegisterClass;
12293       return Res;
12294     }
12295
12296     // GCC allows "st(0)" to be called just plain "st".
12297     if (StringRef("{st}").equals_lower(Constraint)) {
12298       Res.first = X86::ST0;
12299       Res.second = X86::RFP80RegisterClass;
12300       return Res;
12301     }
12302
12303     // flags -> EFLAGS
12304     if (StringRef("{flags}").equals_lower(Constraint)) {
12305       Res.first = X86::EFLAGS;
12306       Res.second = X86::CCRRegisterClass;
12307       return Res;
12308     }
12309
12310     // 'A' means EAX + EDX.
12311     if (Constraint == "A") {
12312       Res.first = X86::EAX;
12313       Res.second = X86::GR32_ADRegisterClass;
12314       return Res;
12315     }
12316     return Res;
12317   }
12318
12319   // Otherwise, check to see if this is a register class of the wrong value
12320   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12321   // turn into {ax},{dx}.
12322   if (Res.second->hasType(VT))
12323     return Res;   // Correct type already, nothing to do.
12324
12325   // All of the single-register GCC register classes map their values onto
12326   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12327   // really want an 8-bit or 32-bit register, map to the appropriate register
12328   // class and return the appropriate register.
12329   if (Res.second == X86::GR16RegisterClass) {
12330     if (VT == MVT::i8) {
12331       unsigned DestReg = 0;
12332       switch (Res.first) {
12333       default: break;
12334       case X86::AX: DestReg = X86::AL; break;
12335       case X86::DX: DestReg = X86::DL; break;
12336       case X86::CX: DestReg = X86::CL; break;
12337       case X86::BX: DestReg = X86::BL; break;
12338       }
12339       if (DestReg) {
12340         Res.first = DestReg;
12341         Res.second = X86::GR8RegisterClass;
12342       }
12343     } else if (VT == MVT::i32) {
12344       unsigned DestReg = 0;
12345       switch (Res.first) {
12346       default: break;
12347       case X86::AX: DestReg = X86::EAX; break;
12348       case X86::DX: DestReg = X86::EDX; break;
12349       case X86::CX: DestReg = X86::ECX; break;
12350       case X86::BX: DestReg = X86::EBX; break;
12351       case X86::SI: DestReg = X86::ESI; break;
12352       case X86::DI: DestReg = X86::EDI; break;
12353       case X86::BP: DestReg = X86::EBP; break;
12354       case X86::SP: DestReg = X86::ESP; break;
12355       }
12356       if (DestReg) {
12357         Res.first = DestReg;
12358         Res.second = X86::GR32RegisterClass;
12359       }
12360     } else if (VT == MVT::i64) {
12361       unsigned DestReg = 0;
12362       switch (Res.first) {
12363       default: break;
12364       case X86::AX: DestReg = X86::RAX; break;
12365       case X86::DX: DestReg = X86::RDX; break;
12366       case X86::CX: DestReg = X86::RCX; break;
12367       case X86::BX: DestReg = X86::RBX; break;
12368       case X86::SI: DestReg = X86::RSI; break;
12369       case X86::DI: DestReg = X86::RDI; break;
12370       case X86::BP: DestReg = X86::RBP; break;
12371       case X86::SP: DestReg = X86::RSP; break;
12372       }
12373       if (DestReg) {
12374         Res.first = DestReg;
12375         Res.second = X86::GR64RegisterClass;
12376       }
12377     }
12378   } else if (Res.second == X86::FR32RegisterClass ||
12379              Res.second == X86::FR64RegisterClass ||
12380              Res.second == X86::VR128RegisterClass) {
12381     // Handle references to XMM physical registers that got mapped into the
12382     // wrong class.  This can happen with constraints like {xmm0} where the
12383     // target independent register mapper will just pick the first match it can
12384     // find, ignoring the required type.
12385     if (VT == MVT::f32)
12386       Res.second = X86::FR32RegisterClass;
12387     else if (VT == MVT::f64)
12388       Res.second = X86::FR64RegisterClass;
12389     else if (X86::VR128RegisterClass->hasType(VT))
12390       Res.second = X86::VR128RegisterClass;
12391   }
12392
12393   return Res;
12394 }