ba357ed76cf5ecdf1d20491a1d24d7367dd880d9
[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::STORE);
973   setTargetDAGCombine(ISD::ZERO_EXTEND);
974   if (Subtarget->is64Bit())
975     setTargetDAGCombine(ISD::MUL);
976
977   computeRegisterProperties();
978
979   // FIXME: These should be based on subtarget info. Plus, the values should
980   // be smaller when we are in optimizing for size mode.
981   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
982   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
983   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
984   setPrefLoopAlignment(16);
985   benefitFromCodePlacementOpt = true;
986 }
987
988
989 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
990   return MVT::i8;
991 }
992
993
994 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
995 /// the desired ByVal argument alignment.
996 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
997   if (MaxAlign == 16)
998     return;
999   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1000     if (VTy->getBitWidth() == 128)
1001       MaxAlign = 16;
1002   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1003     unsigned EltAlign = 0;
1004     getMaxByValAlign(ATy->getElementType(), EltAlign);
1005     if (EltAlign > MaxAlign)
1006       MaxAlign = EltAlign;
1007   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1008     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1009       unsigned EltAlign = 0;
1010       getMaxByValAlign(STy->getElementType(i), EltAlign);
1011       if (EltAlign > MaxAlign)
1012         MaxAlign = EltAlign;
1013       if (MaxAlign == 16)
1014         break;
1015     }
1016   }
1017   return;
1018 }
1019
1020 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1021 /// function arguments in the caller parameter area. For X86, aggregates
1022 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1023 /// are at 4-byte boundaries.
1024 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1025   if (Subtarget->is64Bit()) {
1026     // Max of 8 and alignment of type.
1027     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1028     if (TyAlign > 8)
1029       return TyAlign;
1030     return 8;
1031   }
1032
1033   unsigned Align = 4;
1034   if (Subtarget->hasXMM())
1035     getMaxByValAlign(Ty, Align);
1036   return Align;
1037 }
1038
1039 /// getOptimalMemOpType - Returns the target specific optimal type for load
1040 /// and store operations as a result of memset, memcpy, and memmove
1041 /// lowering. If DstAlign is zero that means it's safe to destination
1042 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1043 /// means there isn't a need to check it against alignment requirement,
1044 /// probably because the source does not need to be loaded. If
1045 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1046 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1047 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1048 /// constant so it does not need to be loaded.
1049 /// It returns EVT::Other if the type should be determined using generic
1050 /// target-independent logic.
1051 EVT
1052 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1053                                        unsigned DstAlign, unsigned SrcAlign,
1054                                        bool NonScalarIntSafe,
1055                                        bool MemcpyStrSrc,
1056                                        MachineFunction &MF) const {
1057   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1058   // linux.  This is because the stack realignment code can't handle certain
1059   // cases like PR2962.  This should be removed when PR2962 is fixed.
1060   const Function *F = MF.getFunction();
1061   if (NonScalarIntSafe &&
1062       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1063     if (Size >= 16 &&
1064         (Subtarget->isUnalignedMemAccessFast() ||
1065          ((DstAlign == 0 || DstAlign >= 16) &&
1066           (SrcAlign == 0 || SrcAlign >= 16))) &&
1067         Subtarget->getStackAlignment() >= 16) {
1068       if (Subtarget->hasSSE2())
1069         return MVT::v4i32;
1070       if (Subtarget->hasSSE1())
1071         return MVT::v4f32;
1072     } else if (!MemcpyStrSrc && Size >= 8 &&
1073                !Subtarget->is64Bit() &&
1074                Subtarget->getStackAlignment() >= 8 &&
1075                Subtarget->hasXMMInt()) {
1076       // Do not use f64 to lower memcpy if source is string constant. It's
1077       // better to use i32 to avoid the loads.
1078       return MVT::f64;
1079     }
1080   }
1081   if (Subtarget->is64Bit() && Size >= 8)
1082     return MVT::i64;
1083   return MVT::i32;
1084 }
1085
1086 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1087 /// current function.  The returned value is a member of the
1088 /// MachineJumpTableInfo::JTEntryKind enum.
1089 unsigned X86TargetLowering::getJumpTableEncoding() const {
1090   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1091   // symbol.
1092   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1093       Subtarget->isPICStyleGOT())
1094     return MachineJumpTableInfo::EK_Custom32;
1095
1096   // Otherwise, use the normal jump table encoding heuristics.
1097   return TargetLowering::getJumpTableEncoding();
1098 }
1099
1100 const MCExpr *
1101 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1102                                              const MachineBasicBlock *MBB,
1103                                              unsigned uid,MCContext &Ctx) const{
1104   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1105          Subtarget->isPICStyleGOT());
1106   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1107   // entries.
1108   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1109                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1110 }
1111
1112 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1113 /// jumptable.
1114 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1115                                                     SelectionDAG &DAG) const {
1116   if (!Subtarget->is64Bit())
1117     // This doesn't have DebugLoc associated with it, but is not really the
1118     // same as a Register.
1119     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1120   return Table;
1121 }
1122
1123 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1124 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1125 /// MCExpr.
1126 const MCExpr *X86TargetLowering::
1127 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1128                              MCContext &Ctx) const {
1129   // X86-64 uses RIP relative addressing based on the jump table label.
1130   if (Subtarget->isPICStyleRIPRel())
1131     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1132
1133   // Otherwise, the reference is relative to the PIC base.
1134   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1135 }
1136
1137 /// getFunctionAlignment - Return the Log2 alignment of this function.
1138 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1139   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1140 }
1141
1142 std::pair<const TargetRegisterClass*, uint8_t>
1143 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1144   const TargetRegisterClass *RRC = 0;
1145   uint8_t Cost = 1;
1146   switch (VT.getSimpleVT().SimpleTy) {
1147   default:
1148     return TargetLowering::findRepresentativeClass(VT);
1149   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1150     RRC = (Subtarget->is64Bit()
1151            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1152     break;
1153   case MVT::x86mmx:
1154     RRC = X86::VR64RegisterClass;
1155     break;
1156   case MVT::f32: case MVT::f64:
1157   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1158   case MVT::v4f32: case MVT::v2f64:
1159   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1160   case MVT::v4f64:
1161     RRC = X86::VR128RegisterClass;
1162     break;
1163   }
1164   return std::make_pair(RRC, Cost);
1165 }
1166
1167 unsigned
1168 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1169                                        MachineFunction &MF) const {
1170   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1171
1172   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1173   switch (RC->getID()) {
1174   default:
1175     return 0;
1176   case X86::GR32RegClassID:
1177     return 4 - FPDiff;
1178   case X86::GR64RegClassID:
1179     return 8 - FPDiff;
1180   case X86::VR128RegClassID:
1181     return Subtarget->is64Bit() ? 10 : 4;
1182   case X86::VR64RegClassID:
1183     return 4;
1184   }
1185 }
1186
1187 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1188                                                unsigned &Offset) const {
1189   if (!Subtarget->isTargetLinux())
1190     return false;
1191
1192   if (Subtarget->is64Bit()) {
1193     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1194     Offset = 0x28;
1195     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1196       AddressSpace = 256;
1197     else
1198       AddressSpace = 257;
1199   } else {
1200     // %gs:0x14 on i386
1201     Offset = 0x14;
1202     AddressSpace = 256;
1203   }
1204   return true;
1205 }
1206
1207
1208 //===----------------------------------------------------------------------===//
1209 //               Return Value Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1211
1212 #include "X86GenCallingConv.inc"
1213
1214 bool
1215 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1216                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1217                         LLVMContext &Context) const {
1218   SmallVector<CCValAssign, 16> RVLocs;
1219   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1220                  RVLocs, Context);
1221   return CCInfo.CheckReturn(Outs, RetCC_X86);
1222 }
1223
1224 SDValue
1225 X86TargetLowering::LowerReturn(SDValue Chain,
1226                                CallingConv::ID CallConv, bool isVarArg,
1227                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1228                                const SmallVectorImpl<SDValue> &OutVals,
1229                                DebugLoc dl, SelectionDAG &DAG) const {
1230   MachineFunction &MF = DAG.getMachineFunction();
1231   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1232
1233   SmallVector<CCValAssign, 16> RVLocs;
1234   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1235                  RVLocs, *DAG.getContext());
1236   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1237
1238   // Add the regs to the liveout set for the function.
1239   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1240   for (unsigned i = 0; i != RVLocs.size(); ++i)
1241     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1242       MRI.addLiveOut(RVLocs[i].getLocReg());
1243
1244   SDValue Flag;
1245
1246   SmallVector<SDValue, 6> RetOps;
1247   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1248   // Operand #1 = Bytes To Pop
1249   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1250                    MVT::i16));
1251
1252   // Copy the result values into the output registers.
1253   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1254     CCValAssign &VA = RVLocs[i];
1255     assert(VA.isRegLoc() && "Can only return in registers!");
1256     SDValue ValToCopy = OutVals[i];
1257     EVT ValVT = ValToCopy.getValueType();
1258
1259     // If this is x86-64, and we disabled SSE, we can't return FP values,
1260     // or SSE or MMX vectors.
1261     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1262          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1263           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1264       report_fatal_error("SSE register return with SSE disabled");
1265     }
1266     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1267     // llvm-gcc has never done it right and no one has noticed, so this
1268     // should be OK for now.
1269     if (ValVT == MVT::f64 &&
1270         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1271       report_fatal_error("SSE2 register return with SSE2 disabled");
1272
1273     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1274     // the RET instruction and handled by the FP Stackifier.
1275     if (VA.getLocReg() == X86::ST0 ||
1276         VA.getLocReg() == X86::ST1) {
1277       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1278       // change the value to the FP stack register class.
1279       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1280         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1281       RetOps.push_back(ValToCopy);
1282       // Don't emit a copytoreg.
1283       continue;
1284     }
1285
1286     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1287     // which is returned in RAX / RDX.
1288     if (Subtarget->is64Bit()) {
1289       if (ValVT == MVT::x86mmx) {
1290         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1291           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1292           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1293                                   ValToCopy);
1294           // If we don't have SSE2 available, convert to v4f32 so the generated
1295           // register is legal.
1296           if (!Subtarget->hasSSE2())
1297             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1298         }
1299       }
1300     }
1301
1302     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1303     Flag = Chain.getValue(1);
1304   }
1305
1306   // The x86-64 ABI for returning structs by value requires that we copy
1307   // the sret argument into %rax for the return. We saved the argument into
1308   // a virtual register in the entry block, so now we copy the value out
1309   // and into %rax.
1310   if (Subtarget->is64Bit() &&
1311       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1312     MachineFunction &MF = DAG.getMachineFunction();
1313     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1314     unsigned Reg = FuncInfo->getSRetReturnReg();
1315     assert(Reg &&
1316            "SRetReturnReg should have been set in LowerFormalArguments().");
1317     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1318
1319     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1320     Flag = Chain.getValue(1);
1321
1322     // RAX now acts like a return value.
1323     MRI.addLiveOut(X86::RAX);
1324   }
1325
1326   RetOps[0] = Chain;  // Update chain.
1327
1328   // Add the flag if we have it.
1329   if (Flag.getNode())
1330     RetOps.push_back(Flag);
1331
1332   return DAG.getNode(X86ISD::RET_FLAG, dl,
1333                      MVT::Other, &RetOps[0], RetOps.size());
1334 }
1335
1336 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1337   if (N->getNumValues() != 1)
1338     return false;
1339   if (!N->hasNUsesOfValue(1, 0))
1340     return false;
1341
1342   SDNode *Copy = *N->use_begin();
1343   if (Copy->getOpcode() != ISD::CopyToReg &&
1344       Copy->getOpcode() != ISD::FP_EXTEND)
1345     return false;
1346
1347   bool HasRet = false;
1348   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1349        UI != UE; ++UI) {
1350     if (UI->getOpcode() != X86ISD::RET_FLAG)
1351       return false;
1352     HasRet = true;
1353   }
1354
1355   return HasRet;
1356 }
1357
1358 /// LowerCallResult - Lower the result values of a call into the
1359 /// appropriate copies out of appropriate physical registers.
1360 ///
1361 SDValue
1362 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1363                                    CallingConv::ID CallConv, bool isVarArg,
1364                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1365                                    DebugLoc dl, SelectionDAG &DAG,
1366                                    SmallVectorImpl<SDValue> &InVals) const {
1367
1368   // Assign locations to each value returned by this call.
1369   SmallVector<CCValAssign, 16> RVLocs;
1370   bool Is64Bit = Subtarget->is64Bit();
1371   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1372                  RVLocs, *DAG.getContext());
1373   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1374
1375   // Copy all of the result registers out of their specified physreg.
1376   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1377     CCValAssign &VA = RVLocs[i];
1378     EVT CopyVT = VA.getValVT();
1379
1380     // If this is x86-64, and we disabled SSE, we can't return FP values
1381     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1382         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1383       report_fatal_error("SSE register return with SSE disabled");
1384     }
1385
1386     SDValue Val;
1387
1388     // If this is a call to a function that returns an fp value on the floating
1389     // point stack, we must guarantee the the value is popped from the stack, so
1390     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1391     // if the return value is not used. We use the FpGET_ST0 instructions
1392     // instead.
1393     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1394       // If we prefer to use the value in xmm registers, copy it out as f80 and
1395       // use a truncate to move it from fp stack reg to xmm reg.
1396       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1397       bool isST0 = VA.getLocReg() == X86::ST0;
1398       unsigned Opc = 0;
1399       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1400       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1401       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1402       SDValue Ops[] = { Chain, InFlag };
1403       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Glue,
1404                                          Ops, 2), 1);
1405       Val = Chain.getValue(0);
1406
1407       // Round the f80 to the right size, which also moves it to the appropriate
1408       // xmm register.
1409       if (CopyVT != VA.getValVT())
1410         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1411                           // This truncation won't change the value.
1412                           DAG.getIntPtrConstant(1));
1413     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1414       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1415       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1416         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1417                                    MVT::v2i64, InFlag).getValue(1);
1418         Val = Chain.getValue(0);
1419         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1420                           Val, DAG.getConstant(0, MVT::i64));
1421       } else {
1422         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1423                                    MVT::i64, InFlag).getValue(1);
1424         Val = Chain.getValue(0);
1425       }
1426       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1427     } else {
1428       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1429                                  CopyVT, InFlag).getValue(1);
1430       Val = Chain.getValue(0);
1431     }
1432     InFlag = Chain.getValue(2);
1433     InVals.push_back(Val);
1434   }
1435
1436   return Chain;
1437 }
1438
1439
1440 //===----------------------------------------------------------------------===//
1441 //                C & StdCall & Fast Calling Convention implementation
1442 //===----------------------------------------------------------------------===//
1443 //  StdCall calling convention seems to be standard for many Windows' API
1444 //  routines and around. It differs from C calling convention just a little:
1445 //  callee should clean up the stack, not caller. Symbols should be also
1446 //  decorated in some fancy way :) It doesn't support any vector arguments.
1447 //  For info on fast calling convention see Fast Calling Convention (tail call)
1448 //  implementation LowerX86_32FastCCCallTo.
1449
1450 /// CallIsStructReturn - Determines whether a call uses struct return
1451 /// semantics.
1452 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1453   if (Outs.empty())
1454     return false;
1455
1456   return Outs[0].Flags.isSRet();
1457 }
1458
1459 /// ArgsAreStructReturn - Determines whether a function uses struct
1460 /// return semantics.
1461 static bool
1462 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1463   if (Ins.empty())
1464     return false;
1465
1466   return Ins[0].Flags.isSRet();
1467 }
1468
1469 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1470 /// by "Src" to address "Dst" with size and alignment information specified by
1471 /// the specific parameter attribute. The copy will be passed as a byval
1472 /// function parameter.
1473 static SDValue
1474 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1475                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1476                           DebugLoc dl) {
1477   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1478
1479   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1480                        /*isVolatile*/false, /*AlwaysInline=*/true,
1481                        MachinePointerInfo(), MachinePointerInfo());
1482 }
1483
1484 /// IsTailCallConvention - Return true if the calling convention is one that
1485 /// supports tail call optimization.
1486 static bool IsTailCallConvention(CallingConv::ID CC) {
1487   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1488 }
1489
1490 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1491 /// a tailcall target by changing its ABI.
1492 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1493   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1494 }
1495
1496 SDValue
1497 X86TargetLowering::LowerMemArgument(SDValue Chain,
1498                                     CallingConv::ID CallConv,
1499                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1500                                     DebugLoc dl, SelectionDAG &DAG,
1501                                     const CCValAssign &VA,
1502                                     MachineFrameInfo *MFI,
1503                                     unsigned i) const {
1504   // Create the nodes corresponding to a load from this parameter slot.
1505   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1506   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1507   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1508   EVT ValVT;
1509
1510   // If value is passed by pointer we have address passed instead of the value
1511   // itself.
1512   if (VA.getLocInfo() == CCValAssign::Indirect)
1513     ValVT = VA.getLocVT();
1514   else
1515     ValVT = VA.getValVT();
1516
1517   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1518   // changed with more analysis.
1519   // In case of tail call optimization mark all arguments mutable. Since they
1520   // could be overwritten by lowering of arguments in case of a tail call.
1521   if (Flags.isByVal()) {
1522     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1523                                     VA.getLocMemOffset(), isImmutable);
1524     return DAG.getFrameIndex(FI, getPointerTy());
1525   } else {
1526     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1527                                     VA.getLocMemOffset(), isImmutable);
1528     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1529     return DAG.getLoad(ValVT, dl, Chain, FIN,
1530                        MachinePointerInfo::getFixedStack(FI),
1531                        false, false, 0);
1532   }
1533 }
1534
1535 SDValue
1536 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1537                                         CallingConv::ID CallConv,
1538                                         bool isVarArg,
1539                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1540                                         DebugLoc dl,
1541                                         SelectionDAG &DAG,
1542                                         SmallVectorImpl<SDValue> &InVals)
1543                                           const {
1544   MachineFunction &MF = DAG.getMachineFunction();
1545   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1546
1547   const Function* Fn = MF.getFunction();
1548   if (Fn->hasExternalLinkage() &&
1549       Subtarget->isTargetCygMing() &&
1550       Fn->getName() == "main")
1551     FuncInfo->setForceFramePointer(true);
1552
1553   MachineFrameInfo *MFI = MF.getFrameInfo();
1554   bool Is64Bit = Subtarget->is64Bit();
1555   bool IsWin64 = Subtarget->isTargetWin64();
1556
1557   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1558          "Var args not supported with calling convention fastcc or ghc");
1559
1560   // Assign locations to all of the incoming arguments.
1561   SmallVector<CCValAssign, 16> ArgLocs;
1562   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1563                  ArgLocs, *DAG.getContext());
1564   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1565
1566   unsigned LastVal = ~0U;
1567   SDValue ArgValue;
1568   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1569     CCValAssign &VA = ArgLocs[i];
1570     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1571     // places.
1572     assert(VA.getValNo() != LastVal &&
1573            "Don't support value assigned to multiple locs yet");
1574     LastVal = VA.getValNo();
1575
1576     if (VA.isRegLoc()) {
1577       EVT RegVT = VA.getLocVT();
1578       TargetRegisterClass *RC = NULL;
1579       if (RegVT == MVT::i32)
1580         RC = X86::GR32RegisterClass;
1581       else if (Is64Bit && RegVT == MVT::i64)
1582         RC = X86::GR64RegisterClass;
1583       else if (RegVT == MVT::f32)
1584         RC = X86::FR32RegisterClass;
1585       else if (RegVT == MVT::f64)
1586         RC = X86::FR64RegisterClass;
1587       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1588         RC = X86::VR256RegisterClass;
1589       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1590         RC = X86::VR128RegisterClass;
1591       else if (RegVT == MVT::x86mmx)
1592         RC = X86::VR64RegisterClass;
1593       else
1594         llvm_unreachable("Unknown argument type!");
1595
1596       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1597       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1598
1599       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1600       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1601       // right size.
1602       if (VA.getLocInfo() == CCValAssign::SExt)
1603         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1604                                DAG.getValueType(VA.getValVT()));
1605       else if (VA.getLocInfo() == CCValAssign::ZExt)
1606         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1607                                DAG.getValueType(VA.getValVT()));
1608       else if (VA.getLocInfo() == CCValAssign::BCvt)
1609         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1610
1611       if (VA.isExtInLoc()) {
1612         // Handle MMX values passed in XMM regs.
1613         if (RegVT.isVector()) {
1614           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1615                                  ArgValue);
1616         } else
1617           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1618       }
1619     } else {
1620       assert(VA.isMemLoc());
1621       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1622     }
1623
1624     // If value is passed via pointer - do a load.
1625     if (VA.getLocInfo() == CCValAssign::Indirect)
1626       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1627                              MachinePointerInfo(), false, false, 0);
1628
1629     InVals.push_back(ArgValue);
1630   }
1631
1632   // The x86-64 ABI for returning structs by value requires that we copy
1633   // the sret argument into %rax for the return. Save the argument into
1634   // a virtual register so that we can access it from the return points.
1635   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1636     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1637     unsigned Reg = FuncInfo->getSRetReturnReg();
1638     if (!Reg) {
1639       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1640       FuncInfo->setSRetReturnReg(Reg);
1641     }
1642     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1644   }
1645
1646   unsigned StackSize = CCInfo.getNextStackOffset();
1647   // Align stack specially for tail calls.
1648   if (FuncIsMadeTailCallSafe(CallConv))
1649     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1650
1651   // If the function takes variable number of arguments, make a frame index for
1652   // the start of the first vararg value... for expansion of llvm.va_start.
1653   if (isVarArg) {
1654     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1655                     CallConv != CallingConv::X86_ThisCall))) {
1656       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1657     }
1658     if (Is64Bit) {
1659       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1660
1661       // FIXME: We should really autogenerate these arrays
1662       static const unsigned GPR64ArgRegsWin64[] = {
1663         X86::RCX, X86::RDX, X86::R8,  X86::R9
1664       };
1665       static const unsigned GPR64ArgRegs64Bit[] = {
1666         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1667       };
1668       static const unsigned XMMArgRegs64Bit[] = {
1669         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1670         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1671       };
1672       const unsigned *GPR64ArgRegs;
1673       unsigned NumXMMRegs = 0;
1674
1675       if (IsWin64) {
1676         // The XMM registers which might contain var arg parameters are shadowed
1677         // in their paired GPR.  So we only need to save the GPR to their home
1678         // slots.
1679         TotalNumIntRegs = 4;
1680         GPR64ArgRegs = GPR64ArgRegsWin64;
1681       } else {
1682         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1683         GPR64ArgRegs = GPR64ArgRegs64Bit;
1684
1685         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1686       }
1687       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1688                                                        TotalNumIntRegs);
1689
1690       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1691       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1692              "SSE register cannot be used when SSE is disabled!");
1693       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1694              "SSE register cannot be used when SSE is disabled!");
1695       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1696         // Kernel mode asks for SSE to be disabled, so don't push them
1697         // on the stack.
1698         TotalNumXMMRegs = 0;
1699
1700       if (IsWin64) {
1701         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1702         // Get to the caller-allocated home save location.  Add 8 to account
1703         // for the return address.
1704         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1705         FuncInfo->setRegSaveFrameIndex(
1706           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1707         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1708       } else {
1709         // For X86-64, if there are vararg parameters that are passed via
1710         // registers, then we must store them to their spots on the stack so they
1711         // may be loaded by deferencing the result of va_next.
1712         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1713         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1714         FuncInfo->setRegSaveFrameIndex(
1715           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1716                                false));
1717       }
1718
1719       // Store the integer parameter registers.
1720       SmallVector<SDValue, 8> MemOps;
1721       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1722                                         getPointerTy());
1723       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1724       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1725         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1726                                   DAG.getIntPtrConstant(Offset));
1727         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1728                                      X86::GR64RegisterClass);
1729         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1730         SDValue Store =
1731           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1732                        MachinePointerInfo::getFixedStack(
1733                          FuncInfo->getRegSaveFrameIndex(), Offset),
1734                        false, false, 0);
1735         MemOps.push_back(Store);
1736         Offset += 8;
1737       }
1738
1739       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1740         // Now store the XMM (fp + vector) parameter registers.
1741         SmallVector<SDValue, 11> SaveXMMOps;
1742         SaveXMMOps.push_back(Chain);
1743
1744         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1745         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1746         SaveXMMOps.push_back(ALVal);
1747
1748         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1749                                FuncInfo->getRegSaveFrameIndex()));
1750         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1751                                FuncInfo->getVarArgsFPOffset()));
1752
1753         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1754           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1755                                        X86::VR128RegisterClass);
1756           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1757           SaveXMMOps.push_back(Val);
1758         }
1759         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1760                                      MVT::Other,
1761                                      &SaveXMMOps[0], SaveXMMOps.size()));
1762       }
1763
1764       if (!MemOps.empty())
1765         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1766                             &MemOps[0], MemOps.size());
1767     }
1768   }
1769
1770   // Some CCs need callee pop.
1771   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1772     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1773   } else {
1774     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1775     // If this is an sret function, the return should pop the hidden pointer.
1776     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1777       FuncInfo->setBytesToPopOnReturn(4);
1778   }
1779
1780   if (!Is64Bit) {
1781     // RegSaveFrameIndex is X86-64 only.
1782     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1783     if (CallConv == CallingConv::X86_FastCall ||
1784         CallConv == CallingConv::X86_ThisCall)
1785       // fastcc functions can't have varargs.
1786       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1787   }
1788
1789   return Chain;
1790 }
1791
1792 SDValue
1793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1794                                     SDValue StackPtr, SDValue Arg,
1795                                     DebugLoc dl, SelectionDAG &DAG,
1796                                     const CCValAssign &VA,
1797                                     ISD::ArgFlagsTy Flags) const {
1798   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1799   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1800   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1801   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1802   if (Flags.isByVal())
1803     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1804
1805   return DAG.getStore(Chain, dl, Arg, PtrOff,
1806                       MachinePointerInfo::getStack(LocMemOffset),
1807                       false, false, 0);
1808 }
1809
1810 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1811 /// optimization is performed and it is required.
1812 SDValue
1813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1814                                            SDValue &OutRetAddr, SDValue Chain,
1815                                            bool IsTailCall, bool Is64Bit,
1816                                            int FPDiff, DebugLoc dl) const {
1817   // Adjust the Return address stack slot.
1818   EVT VT = getPointerTy();
1819   OutRetAddr = getReturnAddressFrameIndex(DAG);
1820
1821   // Load the "old" Return address.
1822   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1823                            false, false, 0);
1824   return SDValue(OutRetAddr.getNode(), 1);
1825 }
1826
1827 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1828 /// optimization is performed and it is required (FPDiff!=0).
1829 static SDValue
1830 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1831                          SDValue Chain, SDValue RetAddrFrIdx,
1832                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1833   // Store the return address to the appropriate stack slot.
1834   if (!FPDiff) return Chain;
1835   // Calculate the new stack slot for the return address.
1836   int SlotSize = Is64Bit ? 8 : 4;
1837   int NewReturnAddrFI =
1838     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1839   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1840   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1841   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1842                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1843                        false, false, 0);
1844   return Chain;
1845 }
1846
1847 SDValue
1848 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1849                              CallingConv::ID CallConv, bool isVarArg,
1850                              bool &isTailCall,
1851                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1852                              const SmallVectorImpl<SDValue> &OutVals,
1853                              const SmallVectorImpl<ISD::InputArg> &Ins,
1854                              DebugLoc dl, SelectionDAG &DAG,
1855                              SmallVectorImpl<SDValue> &InVals) const {
1856   MachineFunction &MF = DAG.getMachineFunction();
1857   bool Is64Bit        = Subtarget->is64Bit();
1858   bool IsStructRet    = CallIsStructReturn(Outs);
1859   bool IsSibcall      = false;
1860
1861   if (isTailCall) {
1862     // Check if it's really possible to do a tail call.
1863     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1864                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1865                                                    Outs, OutVals, Ins, DAG);
1866
1867     // Sibcalls are automatically detected tailcalls which do not require
1868     // ABI changes.
1869     if (!GuaranteedTailCallOpt && isTailCall)
1870       IsSibcall = true;
1871
1872     if (isTailCall)
1873       ++NumTailCalls;
1874   }
1875
1876   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1877          "Var args not supported with calling convention fastcc or ghc");
1878
1879   // Analyze operands of the call, assigning locations to each operand.
1880   SmallVector<CCValAssign, 16> ArgLocs;
1881   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1882                  ArgLocs, *DAG.getContext());
1883   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1884
1885   // Get a count of how many bytes are to be pushed on the stack.
1886   unsigned NumBytes = CCInfo.getNextStackOffset();
1887   if (IsSibcall)
1888     // This is a sibcall. The memory operands are available in caller's
1889     // own caller's stack.
1890     NumBytes = 0;
1891   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1892     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1893
1894   int FPDiff = 0;
1895   if (isTailCall && !IsSibcall) {
1896     // Lower arguments at fp - stackoffset + fpdiff.
1897     unsigned NumBytesCallerPushed =
1898       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1899     FPDiff = NumBytesCallerPushed - NumBytes;
1900
1901     // Set the delta of movement of the returnaddr stackslot.
1902     // But only set if delta is greater than previous delta.
1903     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1904       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1905   }
1906
1907   if (!IsSibcall)
1908     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1909
1910   SDValue RetAddrFrIdx;
1911   // Load return adress for tail calls.
1912   if (isTailCall && FPDiff)
1913     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1914                                     Is64Bit, FPDiff, dl);
1915
1916   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1917   SmallVector<SDValue, 8> MemOpChains;
1918   SDValue StackPtr;
1919
1920   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1921   // of tail call optimization arguments are handle later.
1922   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1923     CCValAssign &VA = ArgLocs[i];
1924     EVT RegVT = VA.getLocVT();
1925     SDValue Arg = OutVals[i];
1926     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1927     bool isByVal = Flags.isByVal();
1928
1929     // Promote the value if needed.
1930     switch (VA.getLocInfo()) {
1931     default: llvm_unreachable("Unknown loc info!");
1932     case CCValAssign::Full: break;
1933     case CCValAssign::SExt:
1934       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1935       break;
1936     case CCValAssign::ZExt:
1937       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1938       break;
1939     case CCValAssign::AExt:
1940       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1941         // Special case: passing MMX values in XMM registers.
1942         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1943         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1944         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1945       } else
1946         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1947       break;
1948     case CCValAssign::BCvt:
1949       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1950       break;
1951     case CCValAssign::Indirect: {
1952       // Store the argument.
1953       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1954       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1955       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1956                            MachinePointerInfo::getFixedStack(FI),
1957                            false, false, 0);
1958       Arg = SpillSlot;
1959       break;
1960     }
1961     }
1962
1963     if (VA.isRegLoc()) {
1964       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1965       if (isVarArg && Subtarget->isTargetWin64()) {
1966         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1967         // shadow reg if callee is a varargs function.
1968         unsigned ShadowReg = 0;
1969         switch (VA.getLocReg()) {
1970         case X86::XMM0: ShadowReg = X86::RCX; break;
1971         case X86::XMM1: ShadowReg = X86::RDX; break;
1972         case X86::XMM2: ShadowReg = X86::R8; break;
1973         case X86::XMM3: ShadowReg = X86::R9; break;
1974         }
1975         if (ShadowReg)
1976           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1977       }
1978     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1979       assert(VA.isMemLoc());
1980       if (StackPtr.getNode() == 0)
1981         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1982       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1983                                              dl, DAG, VA, Flags));
1984     }
1985   }
1986
1987   if (!MemOpChains.empty())
1988     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1989                         &MemOpChains[0], MemOpChains.size());
1990
1991   // Build a sequence of copy-to-reg nodes chained together with token chain
1992   // and flag operands which copy the outgoing args into registers.
1993   SDValue InFlag;
1994   // Tail call byval lowering might overwrite argument registers so in case of
1995   // tail call optimization the copies to registers are lowered later.
1996   if (!isTailCall)
1997     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1998       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1999                                RegsToPass[i].second, InFlag);
2000       InFlag = Chain.getValue(1);
2001     }
2002
2003   if (Subtarget->isPICStyleGOT()) {
2004     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2005     // GOT pointer.
2006     if (!isTailCall) {
2007       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2008                                DAG.getNode(X86ISD::GlobalBaseReg,
2009                                            DebugLoc(), getPointerTy()),
2010                                InFlag);
2011       InFlag = Chain.getValue(1);
2012     } else {
2013       // If we are tail calling and generating PIC/GOT style code load the
2014       // address of the callee into ECX. The value in ecx is used as target of
2015       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2016       // for tail calls on PIC/GOT architectures. Normally we would just put the
2017       // address of GOT into ebx and then call target@PLT. But for tail calls
2018       // ebx would be restored (since ebx is callee saved) before jumping to the
2019       // target@PLT.
2020
2021       // Note: The actual moving to ECX is done further down.
2022       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2023       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2024           !G->getGlobal()->hasProtectedVisibility())
2025         Callee = LowerGlobalAddress(Callee, DAG);
2026       else if (isa<ExternalSymbolSDNode>(Callee))
2027         Callee = LowerExternalSymbol(Callee, DAG);
2028     }
2029   }
2030
2031   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2032     // From AMD64 ABI document:
2033     // For calls that may call functions that use varargs or stdargs
2034     // (prototype-less calls or calls to functions containing ellipsis (...) in
2035     // the declaration) %al is used as hidden argument to specify the number
2036     // of SSE registers used. The contents of %al do not need to match exactly
2037     // the number of registers, but must be an ubound on the number of SSE
2038     // registers used and is in the range 0 - 8 inclusive.
2039
2040     // Count the number of XMM registers allocated.
2041     static const unsigned XMMArgRegs[] = {
2042       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2044     };
2045     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2046     assert((Subtarget->hasXMM() || !NumXMMRegs)
2047            && "SSE registers cannot be used when SSE is disabled");
2048
2049     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2050                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2051     InFlag = Chain.getValue(1);
2052   }
2053
2054
2055   // For tail calls lower the arguments to the 'real' stack slot.
2056   if (isTailCall) {
2057     // Force all the incoming stack arguments to be loaded from the stack
2058     // before any new outgoing arguments are stored to the stack, because the
2059     // outgoing stack slots may alias the incoming argument stack slots, and
2060     // the alias isn't otherwise explicit. This is slightly more conservative
2061     // than necessary, because it means that each store effectively depends
2062     // on every argument instead of just those arguments it would clobber.
2063     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2064
2065     SmallVector<SDValue, 8> MemOpChains2;
2066     SDValue FIN;
2067     int FI = 0;
2068     // Do not flag preceeding copytoreg stuff together with the following stuff.
2069     InFlag = SDValue();
2070     if (GuaranteedTailCallOpt) {
2071       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2072         CCValAssign &VA = ArgLocs[i];
2073         if (VA.isRegLoc())
2074           continue;
2075         assert(VA.isMemLoc());
2076         SDValue Arg = OutVals[i];
2077         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2078         // Create frame index.
2079         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2080         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2081         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2082         FIN = DAG.getFrameIndex(FI, getPointerTy());
2083
2084         if (Flags.isByVal()) {
2085           // Copy relative to framepointer.
2086           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2087           if (StackPtr.getNode() == 0)
2088             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2089                                           getPointerTy());
2090           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2091
2092           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2093                                                            ArgChain,
2094                                                            Flags, DAG, dl));
2095         } else {
2096           // Store relative to framepointer.
2097           MemOpChains2.push_back(
2098             DAG.getStore(ArgChain, dl, Arg, FIN,
2099                          MachinePointerInfo::getFixedStack(FI),
2100                          false, false, 0));
2101         }
2102       }
2103     }
2104
2105     if (!MemOpChains2.empty())
2106       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2107                           &MemOpChains2[0], MemOpChains2.size());
2108
2109     // Copy arguments to their registers.
2110     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2111       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2112                                RegsToPass[i].second, InFlag);
2113       InFlag = Chain.getValue(1);
2114     }
2115     InFlag =SDValue();
2116
2117     // Store the return address to the appropriate stack slot.
2118     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2119                                      FPDiff, dl);
2120   }
2121
2122   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2123     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2124     // In the 64-bit large code model, we have to make all calls
2125     // through a register, since the call instruction's 32-bit
2126     // pc-relative offset may not be large enough to hold the whole
2127     // address.
2128   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2129     // If the callee is a GlobalAddress node (quite common, every direct call
2130     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2131     // it.
2132
2133     // We should use extra load for direct calls to dllimported functions in
2134     // non-JIT mode.
2135     const GlobalValue *GV = G->getGlobal();
2136     if (!GV->hasDLLImportLinkage()) {
2137       unsigned char OpFlags = 0;
2138
2139       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2140       // external symbols most go through the PLT in PIC mode.  If the symbol
2141       // has hidden or protected visibility, or if it is static or local, then
2142       // we don't need to use the PLT - we can directly call it.
2143       if (Subtarget->isTargetELF() &&
2144           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2145           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2146         OpFlags = X86II::MO_PLT;
2147       } else if (Subtarget->isPICStyleStubAny() &&
2148                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2149                  Subtarget->getDarwinVers() < 9) {
2150         // PC-relative references to external symbols should go through $stub,
2151         // unless we're building with the leopard linker or later, which
2152         // automatically synthesizes these stubs.
2153         OpFlags = X86II::MO_DARWIN_STUB;
2154       }
2155
2156       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2157                                           G->getOffset(), OpFlags);
2158     }
2159   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2160     unsigned char OpFlags = 0;
2161
2162     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2163     // external symbols should go through the PLT.
2164     if (Subtarget->isTargetELF() &&
2165         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2166       OpFlags = X86II::MO_PLT;
2167     } else if (Subtarget->isPICStyleStubAny() &&
2168                Subtarget->getDarwinVers() < 9) {
2169       // PC-relative references to external symbols should go through $stub,
2170       // unless we're building with the leopard linker or later, which
2171       // automatically synthesizes these stubs.
2172       OpFlags = X86II::MO_DARWIN_STUB;
2173     }
2174
2175     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2176                                          OpFlags);
2177   }
2178
2179   // Returns a chain & a flag for retval copy to use.
2180   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2181   SmallVector<SDValue, 8> Ops;
2182
2183   if (!IsSibcall && isTailCall) {
2184     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2185                            DAG.getIntPtrConstant(0, true), InFlag);
2186     InFlag = Chain.getValue(1);
2187   }
2188
2189   Ops.push_back(Chain);
2190   Ops.push_back(Callee);
2191
2192   if (isTailCall)
2193     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2194
2195   // Add argument registers to the end of the list so that they are known live
2196   // into the call.
2197   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2198     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2199                                   RegsToPass[i].second.getValueType()));
2200
2201   // Add an implicit use GOT pointer in EBX.
2202   if (!isTailCall && Subtarget->isPICStyleGOT())
2203     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2204
2205   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2206   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2207     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2208
2209   if (InFlag.getNode())
2210     Ops.push_back(InFlag);
2211
2212   if (isTailCall) {
2213     // We used to do:
2214     //// If this is the first return lowered for this function, add the regs
2215     //// to the liveout set for the function.
2216     // This isn't right, although it's probably harmless on x86; liveouts
2217     // should be computed from returns not tail calls.  Consider a void
2218     // function making a tail call to a function returning int.
2219     return DAG.getNode(X86ISD::TC_RETURN, dl,
2220                        NodeTys, &Ops[0], Ops.size());
2221   }
2222
2223   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2224   InFlag = Chain.getValue(1);
2225
2226   // Create the CALLSEQ_END node.
2227   unsigned NumBytesForCalleeToPush;
2228   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2229     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2230   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2231     // If this is a call to a struct-return function, the callee
2232     // pops the hidden struct pointer, so we have to push it back.
2233     // This is common for Darwin/X86, Linux & Mingw32 targets.
2234     NumBytesForCalleeToPush = 4;
2235   else
2236     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2237
2238   // Returns a flag for retval copy to use.
2239   if (!IsSibcall) {
2240     Chain = DAG.getCALLSEQ_END(Chain,
2241                                DAG.getIntPtrConstant(NumBytes, true),
2242                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2243                                                      true),
2244                                InFlag);
2245     InFlag = Chain.getValue(1);
2246   }
2247
2248   // Handle result values, copying them out of physregs into vregs that we
2249   // return.
2250   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2251                          Ins, dl, DAG, InVals);
2252 }
2253
2254
2255 //===----------------------------------------------------------------------===//
2256 //                Fast Calling Convention (tail call) implementation
2257 //===----------------------------------------------------------------------===//
2258
2259 //  Like std call, callee cleans arguments, convention except that ECX is
2260 //  reserved for storing the tail called function address. Only 2 registers are
2261 //  free for argument passing (inreg). Tail call optimization is performed
2262 //  provided:
2263 //                * tailcallopt is enabled
2264 //                * caller/callee are fastcc
2265 //  On X86_64 architecture with GOT-style position independent code only local
2266 //  (within module) calls are supported at the moment.
2267 //  To keep the stack aligned according to platform abi the function
2268 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2269 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2270 //  If a tail called function callee has more arguments than the caller the
2271 //  caller needs to make sure that there is room to move the RETADDR to. This is
2272 //  achieved by reserving an area the size of the argument delta right after the
2273 //  original REtADDR, but before the saved framepointer or the spilled registers
2274 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2275 //  stack layout:
2276 //    arg1
2277 //    arg2
2278 //    RETADDR
2279 //    [ new RETADDR
2280 //      move area ]
2281 //    (possible EBP)
2282 //    ESI
2283 //    EDI
2284 //    local1 ..
2285
2286 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2287 /// for a 16 byte align requirement.
2288 unsigned
2289 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2290                                                SelectionDAG& DAG) const {
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   const TargetMachine &TM = MF.getTarget();
2293   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2294   unsigned StackAlignment = TFI.getStackAlignment();
2295   uint64_t AlignMask = StackAlignment - 1;
2296   int64_t Offset = StackSize;
2297   uint64_t SlotSize = TD->getPointerSize();
2298   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2299     // Number smaller than 12 so just add the difference.
2300     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2301   } else {
2302     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2303     Offset = ((~AlignMask) & Offset) + StackAlignment +
2304       (StackAlignment-SlotSize);
2305   }
2306   return Offset;
2307 }
2308
2309 /// MatchingStackOffset - Return true if the given stack call argument is
2310 /// already available in the same position (relatively) of the caller's
2311 /// incoming argument stack.
2312 static
2313 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2314                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2315                          const X86InstrInfo *TII) {
2316   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2317   int FI = INT_MAX;
2318   if (Arg.getOpcode() == ISD::CopyFromReg) {
2319     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2320     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2321       return false;
2322     MachineInstr *Def = MRI->getVRegDef(VR);
2323     if (!Def)
2324       return false;
2325     if (!Flags.isByVal()) {
2326       if (!TII->isLoadFromStackSlot(Def, FI))
2327         return false;
2328     } else {
2329       unsigned Opcode = Def->getOpcode();
2330       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2331           Def->getOperand(1).isFI()) {
2332         FI = Def->getOperand(1).getIndex();
2333         Bytes = Flags.getByValSize();
2334       } else
2335         return false;
2336     }
2337   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2338     if (Flags.isByVal())
2339       // ByVal argument is passed in as a pointer but it's now being
2340       // dereferenced. e.g.
2341       // define @foo(%struct.X* %A) {
2342       //   tail call @bar(%struct.X* byval %A)
2343       // }
2344       return false;
2345     SDValue Ptr = Ld->getBasePtr();
2346     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2347     if (!FINode)
2348       return false;
2349     FI = FINode->getIndex();
2350   } else
2351     return false;
2352
2353   assert(FI != INT_MAX);
2354   if (!MFI->isFixedObjectIndex(FI))
2355     return false;
2356   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2357 }
2358
2359 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2360 /// for tail call optimization. Targets which want to do tail call
2361 /// optimization should implement this function.
2362 bool
2363 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2364                                                      CallingConv::ID CalleeCC,
2365                                                      bool isVarArg,
2366                                                      bool isCalleeStructRet,
2367                                                      bool isCallerStructRet,
2368                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2369                                     const SmallVectorImpl<SDValue> &OutVals,
2370                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2371                                                      SelectionDAG& DAG) const {
2372   if (!IsTailCallConvention(CalleeCC) &&
2373       CalleeCC != CallingConv::C)
2374     return false;
2375
2376   // If -tailcallopt is specified, make fastcc functions tail-callable.
2377   const MachineFunction &MF = DAG.getMachineFunction();
2378   const Function *CallerF = DAG.getMachineFunction().getFunction();
2379   CallingConv::ID CallerCC = CallerF->getCallingConv();
2380   bool CCMatch = CallerCC == CalleeCC;
2381
2382   if (GuaranteedTailCallOpt) {
2383     if (IsTailCallConvention(CalleeCC) && CCMatch)
2384       return true;
2385     return false;
2386   }
2387
2388   // Look for obvious safe cases to perform tail call optimization that do not
2389   // require ABI changes. This is what gcc calls sibcall.
2390
2391   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2392   // emit a special epilogue.
2393   if (RegInfo->needsStackRealignment(MF))
2394     return false;
2395
2396   // Do not sibcall optimize vararg calls unless the call site is not passing
2397   // any arguments.
2398   if (isVarArg && !Outs.empty())
2399     return false;
2400
2401   // Also avoid sibcall optimization if either caller or callee uses struct
2402   // return semantics.
2403   if (isCalleeStructRet || isCallerStructRet)
2404     return false;
2405
2406   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2407   // Therefore if it's not used by the call it is not safe to optimize this into
2408   // a sibcall.
2409   bool Unused = false;
2410   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2411     if (!Ins[i].Used) {
2412       Unused = true;
2413       break;
2414     }
2415   }
2416   if (Unused) {
2417     SmallVector<CCValAssign, 16> RVLocs;
2418     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2419                    RVLocs, *DAG.getContext());
2420     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2421     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2422       CCValAssign &VA = RVLocs[i];
2423       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2424         return false;
2425     }
2426   }
2427
2428   // If the calling conventions do not match, then we'd better make sure the
2429   // results are returned in the same way as what the caller expects.
2430   if (!CCMatch) {
2431     SmallVector<CCValAssign, 16> RVLocs1;
2432     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2433                     RVLocs1, *DAG.getContext());
2434     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2435
2436     SmallVector<CCValAssign, 16> RVLocs2;
2437     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2438                     RVLocs2, *DAG.getContext());
2439     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2440
2441     if (RVLocs1.size() != RVLocs2.size())
2442       return false;
2443     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2444       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2445         return false;
2446       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2447         return false;
2448       if (RVLocs1[i].isRegLoc()) {
2449         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2450           return false;
2451       } else {
2452         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2453           return false;
2454       }
2455     }
2456   }
2457
2458   // If the callee takes no arguments then go on to check the results of the
2459   // call.
2460   if (!Outs.empty()) {
2461     // Check if stack adjustment is needed. For now, do not do this if any
2462     // argument is passed on the stack.
2463     SmallVector<CCValAssign, 16> ArgLocs;
2464     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2465                    ArgLocs, *DAG.getContext());
2466     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2467     if (CCInfo.getNextStackOffset()) {
2468       MachineFunction &MF = DAG.getMachineFunction();
2469       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2470         return false;
2471       if (Subtarget->isTargetWin64())
2472         // Win64 ABI has additional complications.
2473         return false;
2474
2475       // Check if the arguments are already laid out in the right way as
2476       // the caller's fixed stack objects.
2477       MachineFrameInfo *MFI = MF.getFrameInfo();
2478       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2479       const X86InstrInfo *TII =
2480         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2481       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2482         CCValAssign &VA = ArgLocs[i];
2483         SDValue Arg = OutVals[i];
2484         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2485         if (VA.getLocInfo() == CCValAssign::Indirect)
2486           return false;
2487         if (!VA.isRegLoc()) {
2488           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2489                                    MFI, MRI, TII))
2490             return false;
2491         }
2492       }
2493     }
2494
2495     // If the tailcall address may be in a register, then make sure it's
2496     // possible to register allocate for it. In 32-bit, the call address can
2497     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2498     // callee-saved registers are restored. These happen to be the same
2499     // registers used to pass 'inreg' arguments so watch out for those.
2500     if (!Subtarget->is64Bit() &&
2501         !isa<GlobalAddressSDNode>(Callee) &&
2502         !isa<ExternalSymbolSDNode>(Callee)) {
2503       unsigned NumInRegs = 0;
2504       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2505         CCValAssign &VA = ArgLocs[i];
2506         if (!VA.isRegLoc())
2507           continue;
2508         unsigned Reg = VA.getLocReg();
2509         switch (Reg) {
2510         default: break;
2511         case X86::EAX: case X86::EDX: case X86::ECX:
2512           if (++NumInRegs == 3)
2513             return false;
2514           break;
2515         }
2516       }
2517     }
2518   }
2519
2520   // An stdcall caller is expected to clean up its arguments; the callee
2521   // isn't going to do that.
2522   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2523     return false;
2524
2525   return true;
2526 }
2527
2528 FastISel *
2529 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2530   return X86::createFastISel(funcInfo);
2531 }
2532
2533
2534 //===----------------------------------------------------------------------===//
2535 //                           Other Lowering Hooks
2536 //===----------------------------------------------------------------------===//
2537
2538 static bool MayFoldLoad(SDValue Op) {
2539   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2540 }
2541
2542 static bool MayFoldIntoStore(SDValue Op) {
2543   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2544 }
2545
2546 static bool isTargetShuffle(unsigned Opcode) {
2547   switch(Opcode) {
2548   default: return false;
2549   case X86ISD::PSHUFD:
2550   case X86ISD::PSHUFHW:
2551   case X86ISD::PSHUFLW:
2552   case X86ISD::SHUFPD:
2553   case X86ISD::PALIGN:
2554   case X86ISD::SHUFPS:
2555   case X86ISD::MOVLHPS:
2556   case X86ISD::MOVLHPD:
2557   case X86ISD::MOVHLPS:
2558   case X86ISD::MOVLPS:
2559   case X86ISD::MOVLPD:
2560   case X86ISD::MOVSHDUP:
2561   case X86ISD::MOVSLDUP:
2562   case X86ISD::MOVDDUP:
2563   case X86ISD::MOVSS:
2564   case X86ISD::MOVSD:
2565   case X86ISD::UNPCKLPS:
2566   case X86ISD::UNPCKLPD:
2567   case X86ISD::PUNPCKLWD:
2568   case X86ISD::PUNPCKLBW:
2569   case X86ISD::PUNPCKLDQ:
2570   case X86ISD::PUNPCKLQDQ:
2571   case X86ISD::UNPCKHPS:
2572   case X86ISD::UNPCKHPD:
2573   case X86ISD::PUNPCKHWD:
2574   case X86ISD::PUNPCKHBW:
2575   case X86ISD::PUNPCKHDQ:
2576   case X86ISD::PUNPCKHQDQ:
2577     return true;
2578   }
2579   return false;
2580 }
2581
2582 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2583                                                SDValue V1, SelectionDAG &DAG) {
2584   switch(Opc) {
2585   default: llvm_unreachable("Unknown x86 shuffle node");
2586   case X86ISD::MOVSHDUP:
2587   case X86ISD::MOVSLDUP:
2588   case X86ISD::MOVDDUP:
2589     return DAG.getNode(Opc, dl, VT, V1);
2590   }
2591
2592   return SDValue();
2593 }
2594
2595 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2596                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2597   switch(Opc) {
2598   default: llvm_unreachable("Unknown x86 shuffle node");
2599   case X86ISD::PSHUFD:
2600   case X86ISD::PSHUFHW:
2601   case X86ISD::PSHUFLW:
2602     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2603   }
2604
2605   return SDValue();
2606 }
2607
2608 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2609                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2610   switch(Opc) {
2611   default: llvm_unreachable("Unknown x86 shuffle node");
2612   case X86ISD::PALIGN:
2613   case X86ISD::SHUFPD:
2614   case X86ISD::SHUFPS:
2615     return DAG.getNode(Opc, dl, VT, V1, V2,
2616                        DAG.getConstant(TargetMask, MVT::i8));
2617   }
2618   return SDValue();
2619 }
2620
2621 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2622                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2623   switch(Opc) {
2624   default: llvm_unreachable("Unknown x86 shuffle node");
2625   case X86ISD::MOVLHPS:
2626   case X86ISD::MOVLHPD:
2627   case X86ISD::MOVHLPS:
2628   case X86ISD::MOVLPS:
2629   case X86ISD::MOVLPD:
2630   case X86ISD::MOVSS:
2631   case X86ISD::MOVSD:
2632   case X86ISD::UNPCKLPS:
2633   case X86ISD::UNPCKLPD:
2634   case X86ISD::PUNPCKLWD:
2635   case X86ISD::PUNPCKLBW:
2636   case X86ISD::PUNPCKLDQ:
2637   case X86ISD::PUNPCKLQDQ:
2638   case X86ISD::UNPCKHPS:
2639   case X86ISD::UNPCKHPD:
2640   case X86ISD::PUNPCKHWD:
2641   case X86ISD::PUNPCKHBW:
2642   case X86ISD::PUNPCKHDQ:
2643   case X86ISD::PUNPCKHQDQ:
2644     return DAG.getNode(Opc, dl, VT, V1, V2);
2645   }
2646   return SDValue();
2647 }
2648
2649 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2650   MachineFunction &MF = DAG.getMachineFunction();
2651   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2652   int ReturnAddrIndex = FuncInfo->getRAIndex();
2653
2654   if (ReturnAddrIndex == 0) {
2655     // Set up a frame object for the return address.
2656     uint64_t SlotSize = TD->getPointerSize();
2657     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2658                                                            false);
2659     FuncInfo->setRAIndex(ReturnAddrIndex);
2660   }
2661
2662   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2663 }
2664
2665
2666 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2667                                        bool hasSymbolicDisplacement) {
2668   // Offset should fit into 32 bit immediate field.
2669   if (!isInt<32>(Offset))
2670     return false;
2671
2672   // If we don't have a symbolic displacement - we don't have any extra
2673   // restrictions.
2674   if (!hasSymbolicDisplacement)
2675     return true;
2676
2677   // FIXME: Some tweaks might be needed for medium code model.
2678   if (M != CodeModel::Small && M != CodeModel::Kernel)
2679     return false;
2680
2681   // For small code model we assume that latest object is 16MB before end of 31
2682   // bits boundary. We may also accept pretty large negative constants knowing
2683   // that all objects are in the positive half of address space.
2684   if (M == CodeModel::Small && Offset < 16*1024*1024)
2685     return true;
2686
2687   // For kernel code model we know that all object resist in the negative half
2688   // of 32bits address space. We may not accept negative offsets, since they may
2689   // be just off and we may accept pretty large positive ones.
2690   if (M == CodeModel::Kernel && Offset > 0)
2691     return true;
2692
2693   return false;
2694 }
2695
2696 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2697 /// specific condition code, returning the condition code and the LHS/RHS of the
2698 /// comparison to make.
2699 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2700                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2701   if (!isFP) {
2702     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2703       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2704         // X > -1   -> X == 0, jump !sign.
2705         RHS = DAG.getConstant(0, RHS.getValueType());
2706         return X86::COND_NS;
2707       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2708         // X < 0   -> X == 0, jump on sign.
2709         return X86::COND_S;
2710       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2711         // X < 1   -> X <= 0
2712         RHS = DAG.getConstant(0, RHS.getValueType());
2713         return X86::COND_LE;
2714       }
2715     }
2716
2717     switch (SetCCOpcode) {
2718     default: llvm_unreachable("Invalid integer condition!");
2719     case ISD::SETEQ:  return X86::COND_E;
2720     case ISD::SETGT:  return X86::COND_G;
2721     case ISD::SETGE:  return X86::COND_GE;
2722     case ISD::SETLT:  return X86::COND_L;
2723     case ISD::SETLE:  return X86::COND_LE;
2724     case ISD::SETNE:  return X86::COND_NE;
2725     case ISD::SETULT: return X86::COND_B;
2726     case ISD::SETUGT: return X86::COND_A;
2727     case ISD::SETULE: return X86::COND_BE;
2728     case ISD::SETUGE: return X86::COND_AE;
2729     }
2730   }
2731
2732   // First determine if it is required or is profitable to flip the operands.
2733
2734   // If LHS is a foldable load, but RHS is not, flip the condition.
2735   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2736       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2737     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2738     std::swap(LHS, RHS);
2739   }
2740
2741   switch (SetCCOpcode) {
2742   default: break;
2743   case ISD::SETOLT:
2744   case ISD::SETOLE:
2745   case ISD::SETUGT:
2746   case ISD::SETUGE:
2747     std::swap(LHS, RHS);
2748     break;
2749   }
2750
2751   // On a floating point condition, the flags are set as follows:
2752   // ZF  PF  CF   op
2753   //  0 | 0 | 0 | X > Y
2754   //  0 | 0 | 1 | X < Y
2755   //  1 | 0 | 0 | X == Y
2756   //  1 | 1 | 1 | unordered
2757   switch (SetCCOpcode) {
2758   default: llvm_unreachable("Condcode should be pre-legalized away");
2759   case ISD::SETUEQ:
2760   case ISD::SETEQ:   return X86::COND_E;
2761   case ISD::SETOLT:              // flipped
2762   case ISD::SETOGT:
2763   case ISD::SETGT:   return X86::COND_A;
2764   case ISD::SETOLE:              // flipped
2765   case ISD::SETOGE:
2766   case ISD::SETGE:   return X86::COND_AE;
2767   case ISD::SETUGT:              // flipped
2768   case ISD::SETULT:
2769   case ISD::SETLT:   return X86::COND_B;
2770   case ISD::SETUGE:              // flipped
2771   case ISD::SETULE:
2772   case ISD::SETLE:   return X86::COND_BE;
2773   case ISD::SETONE:
2774   case ISD::SETNE:   return X86::COND_NE;
2775   case ISD::SETUO:   return X86::COND_P;
2776   case ISD::SETO:    return X86::COND_NP;
2777   case ISD::SETOEQ:
2778   case ISD::SETUNE:  return X86::COND_INVALID;
2779   }
2780 }
2781
2782 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2783 /// code. Current x86 isa includes the following FP cmov instructions:
2784 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2785 static bool hasFPCMov(unsigned X86CC) {
2786   switch (X86CC) {
2787   default:
2788     return false;
2789   case X86::COND_B:
2790   case X86::COND_BE:
2791   case X86::COND_E:
2792   case X86::COND_P:
2793   case X86::COND_A:
2794   case X86::COND_AE:
2795   case X86::COND_NE:
2796   case X86::COND_NP:
2797     return true;
2798   }
2799 }
2800
2801 /// isFPImmLegal - Returns true if the target can instruction select the
2802 /// specified FP immediate natively. If false, the legalizer will
2803 /// materialize the FP immediate as a load from a constant pool.
2804 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2805   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2806     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2807       return true;
2808   }
2809   return false;
2810 }
2811
2812 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2813 /// the specified range (L, H].
2814 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2815   return (Val < 0) || (Val >= Low && Val < Hi);
2816 }
2817
2818 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2819 /// specified value.
2820 static bool isUndefOrEqual(int Val, int CmpVal) {
2821   if (Val < 0 || Val == CmpVal)
2822     return true;
2823   return false;
2824 }
2825
2826 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2827 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2828 /// the second operand.
2829 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2830   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2831     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2832   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2833     return (Mask[0] < 2 && Mask[1] < 2);
2834   return false;
2835 }
2836
2837 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2838   SmallVector<int, 8> M;
2839   N->getMask(M);
2840   return ::isPSHUFDMask(M, N->getValueType(0));
2841 }
2842
2843 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2844 /// is suitable for input to PSHUFHW.
2845 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2846   if (VT != MVT::v8i16)
2847     return false;
2848
2849   // Lower quadword copied in order or undef.
2850   for (int i = 0; i != 4; ++i)
2851     if (Mask[i] >= 0 && Mask[i] != i)
2852       return false;
2853
2854   // Upper quadword shuffled.
2855   for (int i = 4; i != 8; ++i)
2856     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2857       return false;
2858
2859   return true;
2860 }
2861
2862 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2863   SmallVector<int, 8> M;
2864   N->getMask(M);
2865   return ::isPSHUFHWMask(M, N->getValueType(0));
2866 }
2867
2868 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2869 /// is suitable for input to PSHUFLW.
2870 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2871   if (VT != MVT::v8i16)
2872     return false;
2873
2874   // Upper quadword copied in order.
2875   for (int i = 4; i != 8; ++i)
2876     if (Mask[i] >= 0 && Mask[i] != i)
2877       return false;
2878
2879   // Lower quadword shuffled.
2880   for (int i = 0; i != 4; ++i)
2881     if (Mask[i] >= 4)
2882       return false;
2883
2884   return true;
2885 }
2886
2887 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2888   SmallVector<int, 8> M;
2889   N->getMask(M);
2890   return ::isPSHUFLWMask(M, N->getValueType(0));
2891 }
2892
2893 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2894 /// is suitable for input to PALIGNR.
2895 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2896                           bool hasSSSE3) {
2897   int i, e = VT.getVectorNumElements();
2898
2899   // Do not handle v2i64 / v2f64 shuffles with palignr.
2900   if (e < 4 || !hasSSSE3)
2901     return false;
2902
2903   for (i = 0; i != e; ++i)
2904     if (Mask[i] >= 0)
2905       break;
2906
2907   // All undef, not a palignr.
2908   if (i == e)
2909     return false;
2910
2911   // Determine if it's ok to perform a palignr with only the LHS, since we
2912   // don't have access to the actual shuffle elements to see if RHS is undef.
2913   bool Unary = Mask[i] < (int)e;
2914   bool NeedsUnary = false;
2915
2916   int s = Mask[i] - i;
2917
2918   // Check the rest of the elements to see if they are consecutive.
2919   for (++i; i != e; ++i) {
2920     int m = Mask[i];
2921     if (m < 0)
2922       continue;
2923
2924     Unary = Unary && (m < (int)e);
2925     NeedsUnary = NeedsUnary || (m < s);
2926
2927     if (NeedsUnary && !Unary)
2928       return false;
2929     if (Unary && m != ((s+i) & (e-1)))
2930       return false;
2931     if (!Unary && m != (s+i))
2932       return false;
2933   }
2934   return true;
2935 }
2936
2937 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2938   SmallVector<int, 8> M;
2939   N->getMask(M);
2940   return ::isPALIGNRMask(M, N->getValueType(0), true);
2941 }
2942
2943 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2944 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2945 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2946   int NumElems = VT.getVectorNumElements();
2947   if (NumElems != 2 && NumElems != 4)
2948     return false;
2949
2950   int Half = NumElems / 2;
2951   for (int i = 0; i < Half; ++i)
2952     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2953       return false;
2954   for (int i = Half; i < NumElems; ++i)
2955     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2956       return false;
2957
2958   return true;
2959 }
2960
2961 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2962   SmallVector<int, 8> M;
2963   N->getMask(M);
2964   return ::isSHUFPMask(M, N->getValueType(0));
2965 }
2966
2967 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2968 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2969 /// half elements to come from vector 1 (which would equal the dest.) and
2970 /// the upper half to come from vector 2.
2971 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2972   int NumElems = VT.getVectorNumElements();
2973
2974   if (NumElems != 2 && NumElems != 4)
2975     return false;
2976
2977   int Half = NumElems / 2;
2978   for (int i = 0; i < Half; ++i)
2979     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2980       return false;
2981   for (int i = Half; i < NumElems; ++i)
2982     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2983       return false;
2984   return true;
2985 }
2986
2987 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2988   SmallVector<int, 8> M;
2989   N->getMask(M);
2990   return isCommutedSHUFPMask(M, N->getValueType(0));
2991 }
2992
2993 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2994 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2995 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2996   if (N->getValueType(0).getVectorNumElements() != 4)
2997     return false;
2998
2999   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3000   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3001          isUndefOrEqual(N->getMaskElt(1), 7) &&
3002          isUndefOrEqual(N->getMaskElt(2), 2) &&
3003          isUndefOrEqual(N->getMaskElt(3), 3);
3004 }
3005
3006 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3007 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3008 /// <2, 3, 2, 3>
3009 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3010   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3011
3012   if (NumElems != 4)
3013     return false;
3014
3015   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3016   isUndefOrEqual(N->getMaskElt(1), 3) &&
3017   isUndefOrEqual(N->getMaskElt(2), 2) &&
3018   isUndefOrEqual(N->getMaskElt(3), 3);
3019 }
3020
3021 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3022 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3023 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3024   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3025
3026   if (NumElems != 2 && NumElems != 4)
3027     return false;
3028
3029   for (unsigned i = 0; i < NumElems/2; ++i)
3030     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3031       return false;
3032
3033   for (unsigned i = NumElems/2; i < NumElems; ++i)
3034     if (!isUndefOrEqual(N->getMaskElt(i), i))
3035       return false;
3036
3037   return true;
3038 }
3039
3040 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3041 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3042 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3043   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3044
3045   if (NumElems != 2 && NumElems != 4)
3046     return false;
3047
3048   for (unsigned i = 0; i < NumElems/2; ++i)
3049     if (!isUndefOrEqual(N->getMaskElt(i), i))
3050       return false;
3051
3052   for (unsigned i = 0; i < NumElems/2; ++i)
3053     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3054       return false;
3055
3056   return true;
3057 }
3058
3059 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3060 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3061 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3062                          bool V2IsSplat = false) {
3063   int NumElts = VT.getVectorNumElements();
3064   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3065     return false;
3066
3067   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3068     int BitI  = Mask[i];
3069     int BitI1 = Mask[i+1];
3070     if (!isUndefOrEqual(BitI, j))
3071       return false;
3072     if (V2IsSplat) {
3073       if (!isUndefOrEqual(BitI1, NumElts))
3074         return false;
3075     } else {
3076       if (!isUndefOrEqual(BitI1, j + NumElts))
3077         return false;
3078     }
3079   }
3080   return true;
3081 }
3082
3083 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3084   SmallVector<int, 8> M;
3085   N->getMask(M);
3086   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3087 }
3088
3089 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3090 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3091 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3092                          bool V2IsSplat = false) {
3093   int NumElts = VT.getVectorNumElements();
3094   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3095     return false;
3096
3097   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3098     int BitI  = Mask[i];
3099     int BitI1 = Mask[i+1];
3100     if (!isUndefOrEqual(BitI, j + NumElts/2))
3101       return false;
3102     if (V2IsSplat) {
3103       if (isUndefOrEqual(BitI1, NumElts))
3104         return false;
3105     } else {
3106       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3107         return false;
3108     }
3109   }
3110   return true;
3111 }
3112
3113 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3114   SmallVector<int, 8> M;
3115   N->getMask(M);
3116   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3117 }
3118
3119 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3120 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3121 /// <0, 0, 1, 1>
3122 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3123   int NumElems = VT.getVectorNumElements();
3124   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3125     return false;
3126
3127   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3128     int BitI  = Mask[i];
3129     int BitI1 = Mask[i+1];
3130     if (!isUndefOrEqual(BitI, j))
3131       return false;
3132     if (!isUndefOrEqual(BitI1, j))
3133       return false;
3134   }
3135   return true;
3136 }
3137
3138 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3139   SmallVector<int, 8> M;
3140   N->getMask(M);
3141   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3142 }
3143
3144 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3145 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3146 /// <2, 2, 3, 3>
3147 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148   int NumElems = VT.getVectorNumElements();
3149   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3150     return false;
3151
3152   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3153     int BitI  = Mask[i];
3154     int BitI1 = Mask[i+1];
3155     if (!isUndefOrEqual(BitI, j))
3156       return false;
3157     if (!isUndefOrEqual(BitI1, j))
3158       return false;
3159   }
3160   return true;
3161 }
3162
3163 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3164   SmallVector<int, 8> M;
3165   N->getMask(M);
3166   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3167 }
3168
3169 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3170 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3171 /// MOVSD, and MOVD, i.e. setting the lowest element.
3172 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3173   if (VT.getVectorElementType().getSizeInBits() < 32)
3174     return false;
3175
3176   int NumElts = VT.getVectorNumElements();
3177
3178   if (!isUndefOrEqual(Mask[0], NumElts))
3179     return false;
3180
3181   for (int i = 1; i < NumElts; ++i)
3182     if (!isUndefOrEqual(Mask[i], i))
3183       return false;
3184
3185   return true;
3186 }
3187
3188 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3189   SmallVector<int, 8> M;
3190   N->getMask(M);
3191   return ::isMOVLMask(M, N->getValueType(0));
3192 }
3193
3194 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3195 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3196 /// element of vector 2 and the other elements to come from vector 1 in order.
3197 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3198                                bool V2IsSplat = false, bool V2IsUndef = false) {
3199   int NumOps = VT.getVectorNumElements();
3200   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3201     return false;
3202
3203   if (!isUndefOrEqual(Mask[0], 0))
3204     return false;
3205
3206   for (int i = 1; i < NumOps; ++i)
3207     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3208           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3209           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3210       return false;
3211
3212   return true;
3213 }
3214
3215 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3216                            bool V2IsUndef = false) {
3217   SmallVector<int, 8> M;
3218   N->getMask(M);
3219   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3220 }
3221
3222 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3223 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3224 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3225   if (N->getValueType(0).getVectorNumElements() != 4)
3226     return false;
3227
3228   // Expect 1, 1, 3, 3
3229   for (unsigned i = 0; i < 2; ++i) {
3230     int Elt = N->getMaskElt(i);
3231     if (Elt >= 0 && Elt != 1)
3232       return false;
3233   }
3234
3235   bool HasHi = false;
3236   for (unsigned i = 2; i < 4; ++i) {
3237     int Elt = N->getMaskElt(i);
3238     if (Elt >= 0 && Elt != 3)
3239       return false;
3240     if (Elt == 3)
3241       HasHi = true;
3242   }
3243   // Don't use movshdup if it can be done with a shufps.
3244   // FIXME: verify that matching u, u, 3, 3 is what we want.
3245   return HasHi;
3246 }
3247
3248 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3249 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3250 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3251   if (N->getValueType(0).getVectorNumElements() != 4)
3252     return false;
3253
3254   // Expect 0, 0, 2, 2
3255   for (unsigned i = 0; i < 2; ++i)
3256     if (N->getMaskElt(i) > 0)
3257       return false;
3258
3259   bool HasHi = false;
3260   for (unsigned i = 2; i < 4; ++i) {
3261     int Elt = N->getMaskElt(i);
3262     if (Elt >= 0 && Elt != 2)
3263       return false;
3264     if (Elt == 2)
3265       HasHi = true;
3266   }
3267   // Don't use movsldup if it can be done with a shufps.
3268   return HasHi;
3269 }
3270
3271 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3273 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3274   int e = N->getValueType(0).getVectorNumElements() / 2;
3275
3276   for (int i = 0; i < e; ++i)
3277     if (!isUndefOrEqual(N->getMaskElt(i), i))
3278       return false;
3279   for (int i = 0; i < e; ++i)
3280     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3281       return false;
3282   return true;
3283 }
3284
3285 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3286 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3287 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3288   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3289   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3290
3291   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3292   unsigned Mask = 0;
3293   for (int i = 0; i < NumOperands; ++i) {
3294     int Val = SVOp->getMaskElt(NumOperands-i-1);
3295     if (Val < 0) Val = 0;
3296     if (Val >= NumOperands) Val -= NumOperands;
3297     Mask |= Val;
3298     if (i != NumOperands - 1)
3299       Mask <<= Shift;
3300   }
3301   return Mask;
3302 }
3303
3304 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3305 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3306 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3308   unsigned Mask = 0;
3309   // 8 nodes, but we only care about the last 4.
3310   for (unsigned i = 7; i >= 4; --i) {
3311     int Val = SVOp->getMaskElt(i);
3312     if (Val >= 0)
3313       Mask |= (Val - 4);
3314     if (i != 4)
3315       Mask <<= 2;
3316   }
3317   return Mask;
3318 }
3319
3320 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3321 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3322 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3323   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3324   unsigned Mask = 0;
3325   // 8 nodes, but we only care about the first 4.
3326   for (int i = 3; i >= 0; --i) {
3327     int Val = SVOp->getMaskElt(i);
3328     if (Val >= 0)
3329       Mask |= Val;
3330     if (i != 0)
3331       Mask <<= 2;
3332   }
3333   return Mask;
3334 }
3335
3336 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3337 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3338 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3339   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3340   EVT VVT = N->getValueType(0);
3341   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3342   int Val = 0;
3343
3344   unsigned i, e;
3345   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3346     Val = SVOp->getMaskElt(i);
3347     if (Val >= 0)
3348       break;
3349   }
3350   return (Val - i) * EltSize;
3351 }
3352
3353 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3354 /// constant +0.0.
3355 bool X86::isZeroNode(SDValue Elt) {
3356   return ((isa<ConstantSDNode>(Elt) &&
3357            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3358           (isa<ConstantFPSDNode>(Elt) &&
3359            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3360 }
3361
3362 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3363 /// their permute mask.
3364 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3365                                     SelectionDAG &DAG) {
3366   EVT VT = SVOp->getValueType(0);
3367   unsigned NumElems = VT.getVectorNumElements();
3368   SmallVector<int, 8> MaskVec;
3369
3370   for (unsigned i = 0; i != NumElems; ++i) {
3371     int idx = SVOp->getMaskElt(i);
3372     if (idx < 0)
3373       MaskVec.push_back(idx);
3374     else if (idx < (int)NumElems)
3375       MaskVec.push_back(idx + NumElems);
3376     else
3377       MaskVec.push_back(idx - NumElems);
3378   }
3379   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3380                               SVOp->getOperand(0), &MaskVec[0]);
3381 }
3382
3383 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3384 /// the two vector operands have swapped position.
3385 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3386   unsigned NumElems = VT.getVectorNumElements();
3387   for (unsigned i = 0; i != NumElems; ++i) {
3388     int idx = Mask[i];
3389     if (idx < 0)
3390       continue;
3391     else if (idx < (int)NumElems)
3392       Mask[i] = idx + NumElems;
3393     else
3394       Mask[i] = idx - NumElems;
3395   }
3396 }
3397
3398 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3399 /// match movhlps. The lower half elements should come from upper half of
3400 /// V1 (and in order), and the upper half elements should come from the upper
3401 /// half of V2 (and in order).
3402 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3403   if (Op->getValueType(0).getVectorNumElements() != 4)
3404     return false;
3405   for (unsigned i = 0, e = 2; i != e; ++i)
3406     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3407       return false;
3408   for (unsigned i = 2; i != 4; ++i)
3409     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3410       return false;
3411   return true;
3412 }
3413
3414 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3415 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3416 /// required.
3417 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3418   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3419     return false;
3420   N = N->getOperand(0).getNode();
3421   if (!ISD::isNON_EXTLoad(N))
3422     return false;
3423   if (LD)
3424     *LD = cast<LoadSDNode>(N);
3425   return true;
3426 }
3427
3428 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3429 /// match movlp{s|d}. The lower half elements should come from lower half of
3430 /// V1 (and in order), and the upper half elements should come from the upper
3431 /// half of V2 (and in order). And since V1 will become the source of the
3432 /// MOVLP, it must be either a vector load or a scalar load to vector.
3433 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3434                                ShuffleVectorSDNode *Op) {
3435   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3436     return false;
3437   // Is V2 is a vector load, don't do this transformation. We will try to use
3438   // load folding shufps op.
3439   if (ISD::isNON_EXTLoad(V2))
3440     return false;
3441
3442   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3443
3444   if (NumElems != 2 && NumElems != 4)
3445     return false;
3446   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3447     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3448       return false;
3449   for (unsigned i = NumElems/2; i != NumElems; ++i)
3450     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3451       return false;
3452   return true;
3453 }
3454
3455 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3456 /// all the same.
3457 static bool isSplatVector(SDNode *N) {
3458   if (N->getOpcode() != ISD::BUILD_VECTOR)
3459     return false;
3460
3461   SDValue SplatValue = N->getOperand(0);
3462   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3463     if (N->getOperand(i) != SplatValue)
3464       return false;
3465   return true;
3466 }
3467
3468 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3469 /// to an zero vector.
3470 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3471 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3472   SDValue V1 = N->getOperand(0);
3473   SDValue V2 = N->getOperand(1);
3474   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3475   for (unsigned i = 0; i != NumElems; ++i) {
3476     int Idx = N->getMaskElt(i);
3477     if (Idx >= (int)NumElems) {
3478       unsigned Opc = V2.getOpcode();
3479       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3480         continue;
3481       if (Opc != ISD::BUILD_VECTOR ||
3482           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3483         return false;
3484     } else if (Idx >= 0) {
3485       unsigned Opc = V1.getOpcode();
3486       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3487         continue;
3488       if (Opc != ISD::BUILD_VECTOR ||
3489           !X86::isZeroNode(V1.getOperand(Idx)))
3490         return false;
3491     }
3492   }
3493   return true;
3494 }
3495
3496 /// getZeroVector - Returns a vector of specified type with all zero elements.
3497 ///
3498 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3499                              DebugLoc dl) {
3500   assert(VT.isVector() && "Expected a vector type");
3501
3502   // Always build SSE zero vectors as <4 x i32> bitcasted
3503   // to their dest type. This ensures they get CSE'd.
3504   SDValue Vec;
3505   if (VT.getSizeInBits() == 128) {  // SSE
3506     if (HasSSE2) {  // SSE2
3507       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3508       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3509     } else { // SSE1
3510       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3511       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3512     }
3513   } else if (VT.getSizeInBits() == 256) { // AVX
3514     // 256-bit logic and arithmetic instructions in AVX are
3515     // all floating-point, no support for integer ops. Default
3516     // to emitting fp zeroed vectors then.
3517     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3518     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3519     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3520   }
3521   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3522 }
3523
3524 /// getOnesVector - Returns a vector of specified type with all bits set.
3525 ///
3526 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3527   assert(VT.isVector() && "Expected a vector type");
3528
3529   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3530   // type.  This ensures they get CSE'd.
3531   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3532   SDValue Vec;
3533   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3534   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3535 }
3536
3537
3538 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3539 /// that point to V2 points to its first element.
3540 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3541   EVT VT = SVOp->getValueType(0);
3542   unsigned NumElems = VT.getVectorNumElements();
3543
3544   bool Changed = false;
3545   SmallVector<int, 8> MaskVec;
3546   SVOp->getMask(MaskVec);
3547
3548   for (unsigned i = 0; i != NumElems; ++i) {
3549     if (MaskVec[i] > (int)NumElems) {
3550       MaskVec[i] = NumElems;
3551       Changed = true;
3552     }
3553   }
3554   if (Changed)
3555     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3556                                 SVOp->getOperand(1), &MaskVec[0]);
3557   return SDValue(SVOp, 0);
3558 }
3559
3560 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3561 /// operation of specified width.
3562 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3563                        SDValue V2) {
3564   unsigned NumElems = VT.getVectorNumElements();
3565   SmallVector<int, 8> Mask;
3566   Mask.push_back(NumElems);
3567   for (unsigned i = 1; i != NumElems; ++i)
3568     Mask.push_back(i);
3569   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3570 }
3571
3572 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3573 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3574                           SDValue V2) {
3575   unsigned NumElems = VT.getVectorNumElements();
3576   SmallVector<int, 8> Mask;
3577   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3578     Mask.push_back(i);
3579     Mask.push_back(i + NumElems);
3580   }
3581   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3582 }
3583
3584 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3585 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3586                           SDValue V2) {
3587   unsigned NumElems = VT.getVectorNumElements();
3588   unsigned Half = NumElems/2;
3589   SmallVector<int, 8> Mask;
3590   for (unsigned i = 0; i != Half; ++i) {
3591     Mask.push_back(i + Half);
3592     Mask.push_back(i + NumElems + Half);
3593   }
3594   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3595 }
3596
3597 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3598 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3599   EVT PVT = MVT::v4f32;
3600   EVT VT = SV->getValueType(0);
3601   DebugLoc dl = SV->getDebugLoc();
3602   SDValue V1 = SV->getOperand(0);
3603   int NumElems = VT.getVectorNumElements();
3604   int EltNo = SV->getSplatIndex();
3605
3606   // unpack elements to the correct location
3607   while (NumElems > 4) {
3608     if (EltNo < NumElems/2) {
3609       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3610     } else {
3611       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3612       EltNo -= NumElems/2;
3613     }
3614     NumElems >>= 1;
3615   }
3616
3617   // Perform the splat.
3618   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3619   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3620   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3621   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3622 }
3623
3624 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3625 /// vector of zero or undef vector.  This produces a shuffle where the low
3626 /// element of V2 is swizzled into the zero/undef vector, landing at element
3627 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3628 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3629                                              bool isZero, bool HasSSE2,
3630                                              SelectionDAG &DAG) {
3631   EVT VT = V2.getValueType();
3632   SDValue V1 = isZero
3633     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3634   unsigned NumElems = VT.getVectorNumElements();
3635   SmallVector<int, 16> MaskVec;
3636   for (unsigned i = 0; i != NumElems; ++i)
3637     // If this is the insertion idx, put the low elt of V2 here.
3638     MaskVec.push_back(i == Idx ? NumElems : i);
3639   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3640 }
3641
3642 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3643 /// element of the result of the vector shuffle.
3644 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3645                             unsigned Depth) {
3646   if (Depth == 6)
3647     return SDValue();  // Limit search depth.
3648
3649   SDValue V = SDValue(N, 0);
3650   EVT VT = V.getValueType();
3651   unsigned Opcode = V.getOpcode();
3652
3653   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3654   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3655     Index = SV->getMaskElt(Index);
3656
3657     if (Index < 0)
3658       return DAG.getUNDEF(VT.getVectorElementType());
3659
3660     int NumElems = VT.getVectorNumElements();
3661     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3662     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3663   }
3664
3665   // Recurse into target specific vector shuffles to find scalars.
3666   if (isTargetShuffle(Opcode)) {
3667     int NumElems = VT.getVectorNumElements();
3668     SmallVector<unsigned, 16> ShuffleMask;
3669     SDValue ImmN;
3670
3671     switch(Opcode) {
3672     case X86ISD::SHUFPS:
3673     case X86ISD::SHUFPD:
3674       ImmN = N->getOperand(N->getNumOperands()-1);
3675       DecodeSHUFPSMask(NumElems,
3676                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3677                        ShuffleMask);
3678       break;
3679     case X86ISD::PUNPCKHBW:
3680     case X86ISD::PUNPCKHWD:
3681     case X86ISD::PUNPCKHDQ:
3682     case X86ISD::PUNPCKHQDQ:
3683       DecodePUNPCKHMask(NumElems, ShuffleMask);
3684       break;
3685     case X86ISD::UNPCKHPS:
3686     case X86ISD::UNPCKHPD:
3687       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3688       break;
3689     case X86ISD::PUNPCKLBW:
3690     case X86ISD::PUNPCKLWD:
3691     case X86ISD::PUNPCKLDQ:
3692     case X86ISD::PUNPCKLQDQ:
3693       DecodePUNPCKLMask(NumElems, ShuffleMask);
3694       break;
3695     case X86ISD::UNPCKLPS:
3696     case X86ISD::UNPCKLPD:
3697       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3698       break;
3699     case X86ISD::MOVHLPS:
3700       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3701       break;
3702     case X86ISD::MOVLHPS:
3703       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3704       break;
3705     case X86ISD::PSHUFD:
3706       ImmN = N->getOperand(N->getNumOperands()-1);
3707       DecodePSHUFMask(NumElems,
3708                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3709                       ShuffleMask);
3710       break;
3711     case X86ISD::PSHUFHW:
3712       ImmN = N->getOperand(N->getNumOperands()-1);
3713       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3714                         ShuffleMask);
3715       break;
3716     case X86ISD::PSHUFLW:
3717       ImmN = N->getOperand(N->getNumOperands()-1);
3718       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3719                         ShuffleMask);
3720       break;
3721     case X86ISD::MOVSS:
3722     case X86ISD::MOVSD: {
3723       // The index 0 always comes from the first element of the second source,
3724       // this is why MOVSS and MOVSD are used in the first place. The other
3725       // elements come from the other positions of the first source vector.
3726       unsigned OpNum = (Index == 0) ? 1 : 0;
3727       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3728                                  Depth+1);
3729     }
3730     default:
3731       assert("not implemented for target shuffle node");
3732       return SDValue();
3733     }
3734
3735     Index = ShuffleMask[Index];
3736     if (Index < 0)
3737       return DAG.getUNDEF(VT.getVectorElementType());
3738
3739     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3740     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3741                                Depth+1);
3742   }
3743
3744   // Actual nodes that may contain scalar elements
3745   if (Opcode == ISD::BITCAST) {
3746     V = V.getOperand(0);
3747     EVT SrcVT = V.getValueType();
3748     unsigned NumElems = VT.getVectorNumElements();
3749
3750     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3751       return SDValue();
3752   }
3753
3754   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3755     return (Index == 0) ? V.getOperand(0)
3756                           : DAG.getUNDEF(VT.getVectorElementType());
3757
3758   if (V.getOpcode() == ISD::BUILD_VECTOR)
3759     return V.getOperand(Index);
3760
3761   return SDValue();
3762 }
3763
3764 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3765 /// shuffle operation which come from a consecutively from a zero. The
3766 /// search can start in two diferent directions, from left or right.
3767 static
3768 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3769                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3770   int i = 0;
3771
3772   while (i < NumElems) {
3773     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3774     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3775     if (!(Elt.getNode() &&
3776          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3777       break;
3778     ++i;
3779   }
3780
3781   return i;
3782 }
3783
3784 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3785 /// MaskE correspond consecutively to elements from one of the vector operands,
3786 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3787 static
3788 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3789                               int OpIdx, int NumElems, unsigned &OpNum) {
3790   bool SeenV1 = false;
3791   bool SeenV2 = false;
3792
3793   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3794     int Idx = SVOp->getMaskElt(i);
3795     // Ignore undef indicies
3796     if (Idx < 0)
3797       continue;
3798
3799     if (Idx < NumElems)
3800       SeenV1 = true;
3801     else
3802       SeenV2 = true;
3803
3804     // Only accept consecutive elements from the same vector
3805     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3806       return false;
3807   }
3808
3809   OpNum = SeenV1 ? 0 : 1;
3810   return true;
3811 }
3812
3813 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3814 /// logical left shift of a vector.
3815 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3816                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3817   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3818   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3819               false /* check zeros from right */, DAG);
3820   unsigned OpSrc;
3821
3822   if (!NumZeros)
3823     return false;
3824
3825   // Considering the elements in the mask that are not consecutive zeros,
3826   // check if they consecutively come from only one of the source vectors.
3827   //
3828   //               V1 = {X, A, B, C}     0
3829   //                         \  \  \    /
3830   //   vector_shuffle V1, V2 <1, 2, 3, X>
3831   //
3832   if (!isShuffleMaskConsecutive(SVOp,
3833             0,                   // Mask Start Index
3834             NumElems-NumZeros-1, // Mask End Index
3835             NumZeros,            // Where to start looking in the src vector
3836             NumElems,            // Number of elements in vector
3837             OpSrc))              // Which source operand ?
3838     return false;
3839
3840   isLeft = false;
3841   ShAmt = NumZeros;
3842   ShVal = SVOp->getOperand(OpSrc);
3843   return true;
3844 }
3845
3846 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3847 /// logical left shift of a vector.
3848 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3849                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3850   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3851   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3852               true /* check zeros from left */, DAG);
3853   unsigned OpSrc;
3854
3855   if (!NumZeros)
3856     return false;
3857
3858   // Considering the elements in the mask that are not consecutive zeros,
3859   // check if they consecutively come from only one of the source vectors.
3860   //
3861   //                           0    { A, B, X, X } = V2
3862   //                          / \    /  /
3863   //   vector_shuffle V1, V2 <X, X, 4, 5>
3864   //
3865   if (!isShuffleMaskConsecutive(SVOp,
3866             NumZeros,     // Mask Start Index
3867             NumElems-1,   // Mask End Index
3868             0,            // Where to start looking in the src vector
3869             NumElems,     // Number of elements in vector
3870             OpSrc))       // Which source operand ?
3871     return false;
3872
3873   isLeft = true;
3874   ShAmt = NumZeros;
3875   ShVal = SVOp->getOperand(OpSrc);
3876   return true;
3877 }
3878
3879 /// isVectorShift - Returns true if the shuffle can be implemented as a
3880 /// logical left or right shift of a vector.
3881 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3882                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3883   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3884       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3885     return true;
3886
3887   return false;
3888 }
3889
3890 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3891 ///
3892 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3893                                        unsigned NumNonZero, unsigned NumZero,
3894                                        SelectionDAG &DAG,
3895                                        const TargetLowering &TLI) {
3896   if (NumNonZero > 8)
3897     return SDValue();
3898
3899   DebugLoc dl = Op.getDebugLoc();
3900   SDValue V(0, 0);
3901   bool First = true;
3902   for (unsigned i = 0; i < 16; ++i) {
3903     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3904     if (ThisIsNonZero && First) {
3905       if (NumZero)
3906         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3907       else
3908         V = DAG.getUNDEF(MVT::v8i16);
3909       First = false;
3910     }
3911
3912     if ((i & 1) != 0) {
3913       SDValue ThisElt(0, 0), LastElt(0, 0);
3914       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3915       if (LastIsNonZero) {
3916         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3917                               MVT::i16, Op.getOperand(i-1));
3918       }
3919       if (ThisIsNonZero) {
3920         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3921         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3922                               ThisElt, DAG.getConstant(8, MVT::i8));
3923         if (LastIsNonZero)
3924           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3925       } else
3926         ThisElt = LastElt;
3927
3928       if (ThisElt.getNode())
3929         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3930                         DAG.getIntPtrConstant(i/2));
3931     }
3932   }
3933
3934   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3935 }
3936
3937 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3938 ///
3939 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3940                                      unsigned NumNonZero, unsigned NumZero,
3941                                      SelectionDAG &DAG,
3942                                      const TargetLowering &TLI) {
3943   if (NumNonZero > 4)
3944     return SDValue();
3945
3946   DebugLoc dl = Op.getDebugLoc();
3947   SDValue V(0, 0);
3948   bool First = true;
3949   for (unsigned i = 0; i < 8; ++i) {
3950     bool isNonZero = (NonZeros & (1 << i)) != 0;
3951     if (isNonZero) {
3952       if (First) {
3953         if (NumZero)
3954           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3955         else
3956           V = DAG.getUNDEF(MVT::v8i16);
3957         First = false;
3958       }
3959       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3960                       MVT::v8i16, V, Op.getOperand(i),
3961                       DAG.getIntPtrConstant(i));
3962     }
3963   }
3964
3965   return V;
3966 }
3967
3968 /// getVShift - Return a vector logical shift node.
3969 ///
3970 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3971                          unsigned NumBits, SelectionDAG &DAG,
3972                          const TargetLowering &TLI, DebugLoc dl) {
3973   EVT ShVT = MVT::v2i64;
3974   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3975   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3976   return DAG.getNode(ISD::BITCAST, dl, VT,
3977                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3978                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3979 }
3980
3981 SDValue
3982 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3983                                           SelectionDAG &DAG) const {
3984
3985   // Check if the scalar load can be widened into a vector load. And if
3986   // the address is "base + cst" see if the cst can be "absorbed" into
3987   // the shuffle mask.
3988   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3989     SDValue Ptr = LD->getBasePtr();
3990     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3991       return SDValue();
3992     EVT PVT = LD->getValueType(0);
3993     if (PVT != MVT::i32 && PVT != MVT::f32)
3994       return SDValue();
3995
3996     int FI = -1;
3997     int64_t Offset = 0;
3998     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3999       FI = FINode->getIndex();
4000       Offset = 0;
4001     } else if (Ptr.getOpcode() == ISD::ADD &&
4002                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4003                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4004       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4005       Offset = Ptr.getConstantOperandVal(1);
4006       Ptr = Ptr.getOperand(0);
4007     } else {
4008       return SDValue();
4009     }
4010
4011     SDValue Chain = LD->getChain();
4012     // Make sure the stack object alignment is at least 16.
4013     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4014     if (DAG.InferPtrAlignment(Ptr) < 16) {
4015       if (MFI->isFixedObjectIndex(FI)) {
4016         // Can't change the alignment. FIXME: It's possible to compute
4017         // the exact stack offset and reference FI + adjust offset instead.
4018         // If someone *really* cares about this. That's the way to implement it.
4019         return SDValue();
4020       } else {
4021         MFI->setObjectAlignment(FI, 16);
4022       }
4023     }
4024
4025     // (Offset % 16) must be multiple of 4. Then address is then
4026     // Ptr + (Offset & ~15).
4027     if (Offset < 0)
4028       return SDValue();
4029     if ((Offset % 16) & 3)
4030       return SDValue();
4031     int64_t StartOffset = Offset & ~15;
4032     if (StartOffset)
4033       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4034                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4035
4036     int EltNo = (Offset - StartOffset) >> 2;
4037     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4038     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4039     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4040                              LD->getPointerInfo().getWithOffset(StartOffset),
4041                              false, false, 0);
4042     // Canonicalize it to a v4i32 shuffle.
4043     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4044     return DAG.getNode(ISD::BITCAST, dl, VT,
4045                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4046                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4047   }
4048
4049   return SDValue();
4050 }
4051
4052 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4053 /// vector of type 'VT', see if the elements can be replaced by a single large
4054 /// load which has the same value as a build_vector whose operands are 'elts'.
4055 ///
4056 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4057 ///
4058 /// FIXME: we'd also like to handle the case where the last elements are zero
4059 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4060 /// There's even a handy isZeroNode for that purpose.
4061 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4062                                         DebugLoc &DL, SelectionDAG &DAG) {
4063   EVT EltVT = VT.getVectorElementType();
4064   unsigned NumElems = Elts.size();
4065
4066   LoadSDNode *LDBase = NULL;
4067   unsigned LastLoadedElt = -1U;
4068
4069   // For each element in the initializer, see if we've found a load or an undef.
4070   // If we don't find an initial load element, or later load elements are
4071   // non-consecutive, bail out.
4072   for (unsigned i = 0; i < NumElems; ++i) {
4073     SDValue Elt = Elts[i];
4074
4075     if (!Elt.getNode() ||
4076         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4077       return SDValue();
4078     if (!LDBase) {
4079       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4080         return SDValue();
4081       LDBase = cast<LoadSDNode>(Elt.getNode());
4082       LastLoadedElt = i;
4083       continue;
4084     }
4085     if (Elt.getOpcode() == ISD::UNDEF)
4086       continue;
4087
4088     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4089     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4090       return SDValue();
4091     LastLoadedElt = i;
4092   }
4093
4094   // If we have found an entire vector of loads and undefs, then return a large
4095   // load of the entire vector width starting at the base pointer.  If we found
4096   // consecutive loads for the low half, generate a vzext_load node.
4097   if (LastLoadedElt == NumElems - 1) {
4098     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4099       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4100                          LDBase->getPointerInfo(),
4101                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4102     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4103                        LDBase->getPointerInfo(),
4104                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4105                        LDBase->getAlignment());
4106   } else if (NumElems == 4 && LastLoadedElt == 1) {
4107     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4108     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4109     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4110                                               Ops, 2, MVT::i32,
4111                                               LDBase->getMemOperand());
4112     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4113   }
4114   return SDValue();
4115 }
4116
4117 SDValue
4118 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4119   DebugLoc dl = Op.getDebugLoc();
4120   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4121   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4122   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4123   // is present, so AllOnes is ignored.
4124   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4125       (Op.getValueType().getSizeInBits() != 256 &&
4126        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4127     // Canonicalize this to <4 x i32> (SSE) to
4128     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4129     // eliminated on x86-32 hosts.
4130     if (Op.getValueType() == MVT::v4i32)
4131       return Op;
4132
4133     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4134       return getOnesVector(Op.getValueType(), DAG, dl);
4135     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4136   }
4137
4138   EVT VT = Op.getValueType();
4139   EVT ExtVT = VT.getVectorElementType();
4140   unsigned EVTBits = ExtVT.getSizeInBits();
4141
4142   unsigned NumElems = Op.getNumOperands();
4143   unsigned NumZero  = 0;
4144   unsigned NumNonZero = 0;
4145   unsigned NonZeros = 0;
4146   bool IsAllConstants = true;
4147   SmallSet<SDValue, 8> Values;
4148   for (unsigned i = 0; i < NumElems; ++i) {
4149     SDValue Elt = Op.getOperand(i);
4150     if (Elt.getOpcode() == ISD::UNDEF)
4151       continue;
4152     Values.insert(Elt);
4153     if (Elt.getOpcode() != ISD::Constant &&
4154         Elt.getOpcode() != ISD::ConstantFP)
4155       IsAllConstants = false;
4156     if (X86::isZeroNode(Elt))
4157       NumZero++;
4158     else {
4159       NonZeros |= (1 << i);
4160       NumNonZero++;
4161     }
4162   }
4163
4164   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4165   if (NumNonZero == 0)
4166     return DAG.getUNDEF(VT);
4167
4168   // Special case for single non-zero, non-undef, element.
4169   if (NumNonZero == 1) {
4170     unsigned Idx = CountTrailingZeros_32(NonZeros);
4171     SDValue Item = Op.getOperand(Idx);
4172
4173     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4174     // the value are obviously zero, truncate the value to i32 and do the
4175     // insertion that way.  Only do this if the value is non-constant or if the
4176     // value is a constant being inserted into element 0.  It is cheaper to do
4177     // a constant pool load than it is to do a movd + shuffle.
4178     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4179         (!IsAllConstants || Idx == 0)) {
4180       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4181         // Handle SSE only.
4182         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4183         EVT VecVT = MVT::v4i32;
4184         unsigned VecElts = 4;
4185
4186         // Truncate the value (which may itself be a constant) to i32, and
4187         // convert it to a vector with movd (S2V+shuffle to zero extend).
4188         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4189         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4190         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4191                                            Subtarget->hasSSE2(), DAG);
4192
4193         // Now we have our 32-bit value zero extended in the low element of
4194         // a vector.  If Idx != 0, swizzle it into place.
4195         if (Idx != 0) {
4196           SmallVector<int, 4> Mask;
4197           Mask.push_back(Idx);
4198           for (unsigned i = 1; i != VecElts; ++i)
4199             Mask.push_back(i);
4200           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4201                                       DAG.getUNDEF(Item.getValueType()),
4202                                       &Mask[0]);
4203         }
4204         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4205       }
4206     }
4207
4208     // If we have a constant or non-constant insertion into the low element of
4209     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4210     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4211     // depending on what the source datatype is.
4212     if (Idx == 0) {
4213       if (NumZero == 0) {
4214         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4215       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4216           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4217         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4218         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4219         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4220                                            DAG);
4221       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4222         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4223         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4224         EVT MiddleVT = MVT::v4i32;
4225         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4226         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4227                                            Subtarget->hasSSE2(), DAG);
4228         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4229       }
4230     }
4231
4232     // Is it a vector logical left shift?
4233     if (NumElems == 2 && Idx == 1 &&
4234         X86::isZeroNode(Op.getOperand(0)) &&
4235         !X86::isZeroNode(Op.getOperand(1))) {
4236       unsigned NumBits = VT.getSizeInBits();
4237       return getVShift(true, VT,
4238                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4239                                    VT, Op.getOperand(1)),
4240                        NumBits/2, DAG, *this, dl);
4241     }
4242
4243     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4244       return SDValue();
4245
4246     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4247     // is a non-constant being inserted into an element other than the low one,
4248     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4249     // movd/movss) to move this into the low element, then shuffle it into
4250     // place.
4251     if (EVTBits == 32) {
4252       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4253
4254       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4255       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4256                                          Subtarget->hasSSE2(), DAG);
4257       SmallVector<int, 8> MaskVec;
4258       for (unsigned i = 0; i < NumElems; i++)
4259         MaskVec.push_back(i == Idx ? 0 : 1);
4260       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4261     }
4262   }
4263
4264   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4265   if (Values.size() == 1) {
4266     if (EVTBits == 32) {
4267       // Instead of a shuffle like this:
4268       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4269       // Check if it's possible to issue this instead.
4270       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4271       unsigned Idx = CountTrailingZeros_32(NonZeros);
4272       SDValue Item = Op.getOperand(Idx);
4273       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4274         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4275     }
4276     return SDValue();
4277   }
4278
4279   // A vector full of immediates; various special cases are already
4280   // handled, so this is best done with a single constant-pool load.
4281   if (IsAllConstants)
4282     return SDValue();
4283
4284   // Let legalizer expand 2-wide build_vectors.
4285   if (EVTBits == 64) {
4286     if (NumNonZero == 1) {
4287       // One half is zero or undef.
4288       unsigned Idx = CountTrailingZeros_32(NonZeros);
4289       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4290                                  Op.getOperand(Idx));
4291       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4292                                          Subtarget->hasSSE2(), DAG);
4293     }
4294     return SDValue();
4295   }
4296
4297   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4298   if (EVTBits == 8 && NumElems == 16) {
4299     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4300                                         *this);
4301     if (V.getNode()) return V;
4302   }
4303
4304   if (EVTBits == 16 && NumElems == 8) {
4305     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4306                                       *this);
4307     if (V.getNode()) return V;
4308   }
4309
4310   // If element VT is == 32 bits, turn it into a number of shuffles.
4311   SmallVector<SDValue, 8> V;
4312   V.resize(NumElems);
4313   if (NumElems == 4 && NumZero > 0) {
4314     for (unsigned i = 0; i < 4; ++i) {
4315       bool isZero = !(NonZeros & (1 << i));
4316       if (isZero)
4317         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4318       else
4319         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4320     }
4321
4322     for (unsigned i = 0; i < 2; ++i) {
4323       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4324         default: break;
4325         case 0:
4326           V[i] = V[i*2];  // Must be a zero vector.
4327           break;
4328         case 1:
4329           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4330           break;
4331         case 2:
4332           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4333           break;
4334         case 3:
4335           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4336           break;
4337       }
4338     }
4339
4340     SmallVector<int, 8> MaskVec;
4341     bool Reverse = (NonZeros & 0x3) == 2;
4342     for (unsigned i = 0; i < 2; ++i)
4343       MaskVec.push_back(Reverse ? 1-i : i);
4344     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4345     for (unsigned i = 0; i < 2; ++i)
4346       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4347     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4348   }
4349
4350   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4351     // Check for a build vector of consecutive loads.
4352     for (unsigned i = 0; i < NumElems; ++i)
4353       V[i] = Op.getOperand(i);
4354
4355     // Check for elements which are consecutive loads.
4356     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4357     if (LD.getNode())
4358       return LD;
4359
4360     // For SSE 4.1, use insertps to put the high elements into the low element.
4361     if (getSubtarget()->hasSSE41()) {
4362       SDValue Result;
4363       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4364         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4365       else
4366         Result = DAG.getUNDEF(VT);
4367
4368       for (unsigned i = 1; i < NumElems; ++i) {
4369         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4370         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4371                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4372       }
4373       return Result;
4374     }
4375
4376     // Otherwise, expand into a number of unpckl*, start by extending each of
4377     // our (non-undef) elements to the full vector width with the element in the
4378     // bottom slot of the vector (which generates no code for SSE).
4379     for (unsigned i = 0; i < NumElems; ++i) {
4380       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4381         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4382       else
4383         V[i] = DAG.getUNDEF(VT);
4384     }
4385
4386     // Next, we iteratively mix elements, e.g. for v4f32:
4387     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4388     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4389     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4390     unsigned EltStride = NumElems >> 1;
4391     while (EltStride != 0) {
4392       for (unsigned i = 0; i < EltStride; ++i) {
4393         // If V[i+EltStride] is undef and this is the first round of mixing,
4394         // then it is safe to just drop this shuffle: V[i] is already in the
4395         // right place, the one element (since it's the first round) being
4396         // inserted as undef can be dropped.  This isn't safe for successive
4397         // rounds because they will permute elements within both vectors.
4398         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4399             EltStride == NumElems/2)
4400           continue;
4401
4402         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4403       }
4404       EltStride >>= 1;
4405     }
4406     return V[0];
4407   }
4408   return SDValue();
4409 }
4410
4411 SDValue
4412 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4413   // We support concatenate two MMX registers and place them in a MMX
4414   // register.  This is better than doing a stack convert.
4415   DebugLoc dl = Op.getDebugLoc();
4416   EVT ResVT = Op.getValueType();
4417   assert(Op.getNumOperands() == 2);
4418   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4419          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4420   int Mask[2];
4421   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4422   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4423   InVec = Op.getOperand(1);
4424   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4425     unsigned NumElts = ResVT.getVectorNumElements();
4426     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4427     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4428                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4429   } else {
4430     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4431     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4432     Mask[0] = 0; Mask[1] = 2;
4433     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4434   }
4435   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4436 }
4437
4438 // v8i16 shuffles - Prefer shuffles in the following order:
4439 // 1. [all]   pshuflw, pshufhw, optional move
4440 // 2. [ssse3] 1 x pshufb
4441 // 3. [ssse3] 2 x pshufb + 1 x por
4442 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4443 SDValue
4444 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4445                                             SelectionDAG &DAG) const {
4446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4447   SDValue V1 = SVOp->getOperand(0);
4448   SDValue V2 = SVOp->getOperand(1);
4449   DebugLoc dl = SVOp->getDebugLoc();
4450   SmallVector<int, 8> MaskVals;
4451
4452   // Determine if more than 1 of the words in each of the low and high quadwords
4453   // of the result come from the same quadword of one of the two inputs.  Undef
4454   // mask values count as coming from any quadword, for better codegen.
4455   SmallVector<unsigned, 4> LoQuad(4);
4456   SmallVector<unsigned, 4> HiQuad(4);
4457   BitVector InputQuads(4);
4458   for (unsigned i = 0; i < 8; ++i) {
4459     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4460     int EltIdx = SVOp->getMaskElt(i);
4461     MaskVals.push_back(EltIdx);
4462     if (EltIdx < 0) {
4463       ++Quad[0];
4464       ++Quad[1];
4465       ++Quad[2];
4466       ++Quad[3];
4467       continue;
4468     }
4469     ++Quad[EltIdx / 4];
4470     InputQuads.set(EltIdx / 4);
4471   }
4472
4473   int BestLoQuad = -1;
4474   unsigned MaxQuad = 1;
4475   for (unsigned i = 0; i < 4; ++i) {
4476     if (LoQuad[i] > MaxQuad) {
4477       BestLoQuad = i;
4478       MaxQuad = LoQuad[i];
4479     }
4480   }
4481
4482   int BestHiQuad = -1;
4483   MaxQuad = 1;
4484   for (unsigned i = 0; i < 4; ++i) {
4485     if (HiQuad[i] > MaxQuad) {
4486       BestHiQuad = i;
4487       MaxQuad = HiQuad[i];
4488     }
4489   }
4490
4491   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4492   // of the two input vectors, shuffle them into one input vector so only a
4493   // single pshufb instruction is necessary. If There are more than 2 input
4494   // quads, disable the next transformation since it does not help SSSE3.
4495   bool V1Used = InputQuads[0] || InputQuads[1];
4496   bool V2Used = InputQuads[2] || InputQuads[3];
4497   if (Subtarget->hasSSSE3()) {
4498     if (InputQuads.count() == 2 && V1Used && V2Used) {
4499       BestLoQuad = InputQuads.find_first();
4500       BestHiQuad = InputQuads.find_next(BestLoQuad);
4501     }
4502     if (InputQuads.count() > 2) {
4503       BestLoQuad = -1;
4504       BestHiQuad = -1;
4505     }
4506   }
4507
4508   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4509   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4510   // words from all 4 input quadwords.
4511   SDValue NewV;
4512   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4513     SmallVector<int, 8> MaskV;
4514     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4515     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4516     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4517                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4518                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4519     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4520
4521     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4522     // source words for the shuffle, to aid later transformations.
4523     bool AllWordsInNewV = true;
4524     bool InOrder[2] = { true, true };
4525     for (unsigned i = 0; i != 8; ++i) {
4526       int idx = MaskVals[i];
4527       if (idx != (int)i)
4528         InOrder[i/4] = false;
4529       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4530         continue;
4531       AllWordsInNewV = false;
4532       break;
4533     }
4534
4535     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4536     if (AllWordsInNewV) {
4537       for (int i = 0; i != 8; ++i) {
4538         int idx = MaskVals[i];
4539         if (idx < 0)
4540           continue;
4541         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4542         if ((idx != i) && idx < 4)
4543           pshufhw = false;
4544         if ((idx != i) && idx > 3)
4545           pshuflw = false;
4546       }
4547       V1 = NewV;
4548       V2Used = false;
4549       BestLoQuad = 0;
4550       BestHiQuad = 1;
4551     }
4552
4553     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4554     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4555     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4556       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4557       unsigned TargetMask = 0;
4558       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4559                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4560       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4561                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4562       V1 = NewV.getOperand(0);
4563       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4564     }
4565   }
4566
4567   // If we have SSSE3, and all words of the result are from 1 input vector,
4568   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4569   // is present, fall back to case 4.
4570   if (Subtarget->hasSSSE3()) {
4571     SmallVector<SDValue,16> pshufbMask;
4572
4573     // If we have elements from both input vectors, set the high bit of the
4574     // shuffle mask element to zero out elements that come from V2 in the V1
4575     // mask, and elements that come from V1 in the V2 mask, so that the two
4576     // results can be OR'd together.
4577     bool TwoInputs = V1Used && V2Used;
4578     for (unsigned i = 0; i != 8; ++i) {
4579       int EltIdx = MaskVals[i] * 2;
4580       if (TwoInputs && (EltIdx >= 16)) {
4581         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4582         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4583         continue;
4584       }
4585       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4586       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4587     }
4588     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4589     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4590                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4591                                  MVT::v16i8, &pshufbMask[0], 16));
4592     if (!TwoInputs)
4593       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4594
4595     // Calculate the shuffle mask for the second input, shuffle it, and
4596     // OR it with the first shuffled input.
4597     pshufbMask.clear();
4598     for (unsigned i = 0; i != 8; ++i) {
4599       int EltIdx = MaskVals[i] * 2;
4600       if (EltIdx < 16) {
4601         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4602         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4603         continue;
4604       }
4605       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4606       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4607     }
4608     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4609     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4610                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4611                                  MVT::v16i8, &pshufbMask[0], 16));
4612     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4613     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4614   }
4615
4616   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4617   // and update MaskVals with new element order.
4618   BitVector InOrder(8);
4619   if (BestLoQuad >= 0) {
4620     SmallVector<int, 8> MaskV;
4621     for (int i = 0; i != 4; ++i) {
4622       int idx = MaskVals[i];
4623       if (idx < 0) {
4624         MaskV.push_back(-1);
4625         InOrder.set(i);
4626       } else if ((idx / 4) == BestLoQuad) {
4627         MaskV.push_back(idx & 3);
4628         InOrder.set(i);
4629       } else {
4630         MaskV.push_back(-1);
4631       }
4632     }
4633     for (unsigned i = 4; i != 8; ++i)
4634       MaskV.push_back(i);
4635     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4636                                 &MaskV[0]);
4637
4638     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4639       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4640                                NewV.getOperand(0),
4641                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4642                                DAG);
4643   }
4644
4645   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4646   // and update MaskVals with the new element order.
4647   if (BestHiQuad >= 0) {
4648     SmallVector<int, 8> MaskV;
4649     for (unsigned i = 0; i != 4; ++i)
4650       MaskV.push_back(i);
4651     for (unsigned i = 4; i != 8; ++i) {
4652       int idx = MaskVals[i];
4653       if (idx < 0) {
4654         MaskV.push_back(-1);
4655         InOrder.set(i);
4656       } else if ((idx / 4) == BestHiQuad) {
4657         MaskV.push_back((idx & 3) + 4);
4658         InOrder.set(i);
4659       } else {
4660         MaskV.push_back(-1);
4661       }
4662     }
4663     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4664                                 &MaskV[0]);
4665
4666     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4667       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4668                               NewV.getOperand(0),
4669                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4670                               DAG);
4671   }
4672
4673   // In case BestHi & BestLo were both -1, which means each quadword has a word
4674   // from each of the four input quadwords, calculate the InOrder bitvector now
4675   // before falling through to the insert/extract cleanup.
4676   if (BestLoQuad == -1 && BestHiQuad == -1) {
4677     NewV = V1;
4678     for (int i = 0; i != 8; ++i)
4679       if (MaskVals[i] < 0 || MaskVals[i] == i)
4680         InOrder.set(i);
4681   }
4682
4683   // The other elements are put in the right place using pextrw and pinsrw.
4684   for (unsigned i = 0; i != 8; ++i) {
4685     if (InOrder[i])
4686       continue;
4687     int EltIdx = MaskVals[i];
4688     if (EltIdx < 0)
4689       continue;
4690     SDValue ExtOp = (EltIdx < 8)
4691     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4692                   DAG.getIntPtrConstant(EltIdx))
4693     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4694                   DAG.getIntPtrConstant(EltIdx - 8));
4695     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4696                        DAG.getIntPtrConstant(i));
4697   }
4698   return NewV;
4699 }
4700
4701 // v16i8 shuffles - Prefer shuffles in the following order:
4702 // 1. [ssse3] 1 x pshufb
4703 // 2. [ssse3] 2 x pshufb + 1 x por
4704 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4705 static
4706 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4707                                  SelectionDAG &DAG,
4708                                  const X86TargetLowering &TLI) {
4709   SDValue V1 = SVOp->getOperand(0);
4710   SDValue V2 = SVOp->getOperand(1);
4711   DebugLoc dl = SVOp->getDebugLoc();
4712   SmallVector<int, 16> MaskVals;
4713   SVOp->getMask(MaskVals);
4714
4715   // If we have SSSE3, case 1 is generated when all result bytes come from
4716   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4717   // present, fall back to case 3.
4718   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4719   bool V1Only = true;
4720   bool V2Only = true;
4721   for (unsigned i = 0; i < 16; ++i) {
4722     int EltIdx = MaskVals[i];
4723     if (EltIdx < 0)
4724       continue;
4725     if (EltIdx < 16)
4726       V2Only = false;
4727     else
4728       V1Only = false;
4729   }
4730
4731   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4732   if (TLI.getSubtarget()->hasSSSE3()) {
4733     SmallVector<SDValue,16> pshufbMask;
4734
4735     // If all result elements are from one input vector, then only translate
4736     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4737     //
4738     // Otherwise, we have elements from both input vectors, and must zero out
4739     // elements that come from V2 in the first mask, and V1 in the second mask
4740     // so that we can OR them together.
4741     bool TwoInputs = !(V1Only || V2Only);
4742     for (unsigned i = 0; i != 16; ++i) {
4743       int EltIdx = MaskVals[i];
4744       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4745         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4746         continue;
4747       }
4748       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4749     }
4750     // If all the elements are from V2, assign it to V1 and return after
4751     // building the first pshufb.
4752     if (V2Only)
4753       V1 = V2;
4754     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4755                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4756                                  MVT::v16i8, &pshufbMask[0], 16));
4757     if (!TwoInputs)
4758       return V1;
4759
4760     // Calculate the shuffle mask for the second input, shuffle it, and
4761     // OR it with the first shuffled input.
4762     pshufbMask.clear();
4763     for (unsigned i = 0; i != 16; ++i) {
4764       int EltIdx = MaskVals[i];
4765       if (EltIdx < 16) {
4766         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4767         continue;
4768       }
4769       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4770     }
4771     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4772                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4773                                  MVT::v16i8, &pshufbMask[0], 16));
4774     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4775   }
4776
4777   // No SSSE3 - Calculate in place words and then fix all out of place words
4778   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4779   // the 16 different words that comprise the two doublequadword input vectors.
4780   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4781   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4782   SDValue NewV = V2Only ? V2 : V1;
4783   for (int i = 0; i != 8; ++i) {
4784     int Elt0 = MaskVals[i*2];
4785     int Elt1 = MaskVals[i*2+1];
4786
4787     // This word of the result is all undef, skip it.
4788     if (Elt0 < 0 && Elt1 < 0)
4789       continue;
4790
4791     // This word of the result is already in the correct place, skip it.
4792     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4793       continue;
4794     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4795       continue;
4796
4797     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4798     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4799     SDValue InsElt;
4800
4801     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4802     // using a single extract together, load it and store it.
4803     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4804       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4805                            DAG.getIntPtrConstant(Elt1 / 2));
4806       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4807                         DAG.getIntPtrConstant(i));
4808       continue;
4809     }
4810
4811     // If Elt1 is defined, extract it from the appropriate source.  If the
4812     // source byte is not also odd, shift the extracted word left 8 bits
4813     // otherwise clear the bottom 8 bits if we need to do an or.
4814     if (Elt1 >= 0) {
4815       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4816                            DAG.getIntPtrConstant(Elt1 / 2));
4817       if ((Elt1 & 1) == 0)
4818         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4819                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4820       else if (Elt0 >= 0)
4821         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4822                              DAG.getConstant(0xFF00, MVT::i16));
4823     }
4824     // If Elt0 is defined, extract it from the appropriate source.  If the
4825     // source byte is not also even, shift the extracted word right 8 bits. If
4826     // Elt1 was also defined, OR the extracted values together before
4827     // inserting them in the result.
4828     if (Elt0 >= 0) {
4829       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4830                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4831       if ((Elt0 & 1) != 0)
4832         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4833                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4834       else if (Elt1 >= 0)
4835         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4836                              DAG.getConstant(0x00FF, MVT::i16));
4837       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4838                          : InsElt0;
4839     }
4840     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4841                        DAG.getIntPtrConstant(i));
4842   }
4843   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4844 }
4845
4846 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4847 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4848 /// done when every pair / quad of shuffle mask elements point to elements in
4849 /// the right sequence. e.g.
4850 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4851 static
4852 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4853                                  SelectionDAG &DAG, DebugLoc dl) {
4854   EVT VT = SVOp->getValueType(0);
4855   SDValue V1 = SVOp->getOperand(0);
4856   SDValue V2 = SVOp->getOperand(1);
4857   unsigned NumElems = VT.getVectorNumElements();
4858   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4859   EVT NewVT;
4860   switch (VT.getSimpleVT().SimpleTy) {
4861   default: assert(false && "Unexpected!");
4862   case MVT::v4f32: NewVT = MVT::v2f64; break;
4863   case MVT::v4i32: NewVT = MVT::v2i64; break;
4864   case MVT::v8i16: NewVT = MVT::v4i32; break;
4865   case MVT::v16i8: NewVT = MVT::v4i32; break;
4866   }
4867
4868   int Scale = NumElems / NewWidth;
4869   SmallVector<int, 8> MaskVec;
4870   for (unsigned i = 0; i < NumElems; i += Scale) {
4871     int StartIdx = -1;
4872     for (int j = 0; j < Scale; ++j) {
4873       int EltIdx = SVOp->getMaskElt(i+j);
4874       if (EltIdx < 0)
4875         continue;
4876       if (StartIdx == -1)
4877         StartIdx = EltIdx - (EltIdx % Scale);
4878       if (EltIdx != StartIdx + j)
4879         return SDValue();
4880     }
4881     if (StartIdx == -1)
4882       MaskVec.push_back(-1);
4883     else
4884       MaskVec.push_back(StartIdx / Scale);
4885   }
4886
4887   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4888   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4889   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4890 }
4891
4892 /// getVZextMovL - Return a zero-extending vector move low node.
4893 ///
4894 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4895                             SDValue SrcOp, SelectionDAG &DAG,
4896                             const X86Subtarget *Subtarget, DebugLoc dl) {
4897   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4898     LoadSDNode *LD = NULL;
4899     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4900       LD = dyn_cast<LoadSDNode>(SrcOp);
4901     if (!LD) {
4902       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4903       // instead.
4904       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4905       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4906           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4907           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4908           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4909         // PR2108
4910         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4911         return DAG.getNode(ISD::BITCAST, dl, VT,
4912                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4913                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4914                                                    OpVT,
4915                                                    SrcOp.getOperand(0)
4916                                                           .getOperand(0))));
4917       }
4918     }
4919   }
4920
4921   return DAG.getNode(ISD::BITCAST, dl, VT,
4922                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4923                                  DAG.getNode(ISD::BITCAST, dl,
4924                                              OpVT, SrcOp)));
4925 }
4926
4927 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4928 /// shuffles.
4929 static SDValue
4930 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4931   SDValue V1 = SVOp->getOperand(0);
4932   SDValue V2 = SVOp->getOperand(1);
4933   DebugLoc dl = SVOp->getDebugLoc();
4934   EVT VT = SVOp->getValueType(0);
4935
4936   SmallVector<std::pair<int, int>, 8> Locs;
4937   Locs.resize(4);
4938   SmallVector<int, 8> Mask1(4U, -1);
4939   SmallVector<int, 8> PermMask;
4940   SVOp->getMask(PermMask);
4941
4942   unsigned NumHi = 0;
4943   unsigned NumLo = 0;
4944   for (unsigned i = 0; i != 4; ++i) {
4945     int Idx = PermMask[i];
4946     if (Idx < 0) {
4947       Locs[i] = std::make_pair(-1, -1);
4948     } else {
4949       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4950       if (Idx < 4) {
4951         Locs[i] = std::make_pair(0, NumLo);
4952         Mask1[NumLo] = Idx;
4953         NumLo++;
4954       } else {
4955         Locs[i] = std::make_pair(1, NumHi);
4956         if (2+NumHi < 4)
4957           Mask1[2+NumHi] = Idx;
4958         NumHi++;
4959       }
4960     }
4961   }
4962
4963   if (NumLo <= 2 && NumHi <= 2) {
4964     // If no more than two elements come from either vector. This can be
4965     // implemented with two shuffles. First shuffle gather the elements.
4966     // The second shuffle, which takes the first shuffle as both of its
4967     // vector operands, put the elements into the right order.
4968     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4969
4970     SmallVector<int, 8> Mask2(4U, -1);
4971
4972     for (unsigned i = 0; i != 4; ++i) {
4973       if (Locs[i].first == -1)
4974         continue;
4975       else {
4976         unsigned Idx = (i < 2) ? 0 : 4;
4977         Idx += Locs[i].first * 2 + Locs[i].second;
4978         Mask2[i] = Idx;
4979       }
4980     }
4981
4982     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4983   } else if (NumLo == 3 || NumHi == 3) {
4984     // Otherwise, we must have three elements from one vector, call it X, and
4985     // one element from the other, call it Y.  First, use a shufps to build an
4986     // intermediate vector with the one element from Y and the element from X
4987     // that will be in the same half in the final destination (the indexes don't
4988     // matter). Then, use a shufps to build the final vector, taking the half
4989     // containing the element from Y from the intermediate, and the other half
4990     // from X.
4991     if (NumHi == 3) {
4992       // Normalize it so the 3 elements come from V1.
4993       CommuteVectorShuffleMask(PermMask, VT);
4994       std::swap(V1, V2);
4995     }
4996
4997     // Find the element from V2.
4998     unsigned HiIndex;
4999     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5000       int Val = PermMask[HiIndex];
5001       if (Val < 0)
5002         continue;
5003       if (Val >= 4)
5004         break;
5005     }
5006
5007     Mask1[0] = PermMask[HiIndex];
5008     Mask1[1] = -1;
5009     Mask1[2] = PermMask[HiIndex^1];
5010     Mask1[3] = -1;
5011     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5012
5013     if (HiIndex >= 2) {
5014       Mask1[0] = PermMask[0];
5015       Mask1[1] = PermMask[1];
5016       Mask1[2] = HiIndex & 1 ? 6 : 4;
5017       Mask1[3] = HiIndex & 1 ? 4 : 6;
5018       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5019     } else {
5020       Mask1[0] = HiIndex & 1 ? 2 : 0;
5021       Mask1[1] = HiIndex & 1 ? 0 : 2;
5022       Mask1[2] = PermMask[2];
5023       Mask1[3] = PermMask[3];
5024       if (Mask1[2] >= 0)
5025         Mask1[2] += 4;
5026       if (Mask1[3] >= 0)
5027         Mask1[3] += 4;
5028       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5029     }
5030   }
5031
5032   // Break it into (shuffle shuffle_hi, shuffle_lo).
5033   Locs.clear();
5034   SmallVector<int,8> LoMask(4U, -1);
5035   SmallVector<int,8> HiMask(4U, -1);
5036
5037   SmallVector<int,8> *MaskPtr = &LoMask;
5038   unsigned MaskIdx = 0;
5039   unsigned LoIdx = 0;
5040   unsigned HiIdx = 2;
5041   for (unsigned i = 0; i != 4; ++i) {
5042     if (i == 2) {
5043       MaskPtr = &HiMask;
5044       MaskIdx = 1;
5045       LoIdx = 0;
5046       HiIdx = 2;
5047     }
5048     int Idx = PermMask[i];
5049     if (Idx < 0) {
5050       Locs[i] = std::make_pair(-1, -1);
5051     } else if (Idx < 4) {
5052       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5053       (*MaskPtr)[LoIdx] = Idx;
5054       LoIdx++;
5055     } else {
5056       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5057       (*MaskPtr)[HiIdx] = Idx;
5058       HiIdx++;
5059     }
5060   }
5061
5062   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5063   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5064   SmallVector<int, 8> MaskOps;
5065   for (unsigned i = 0; i != 4; ++i) {
5066     if (Locs[i].first == -1) {
5067       MaskOps.push_back(-1);
5068     } else {
5069       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5070       MaskOps.push_back(Idx);
5071     }
5072   }
5073   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5074 }
5075
5076 static bool MayFoldVectorLoad(SDValue V) {
5077   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5078     V = V.getOperand(0);
5079   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5080     V = V.getOperand(0);
5081   if (MayFoldLoad(V))
5082     return true;
5083   return false;
5084 }
5085
5086 // FIXME: the version above should always be used. Since there's
5087 // a bug where several vector shuffles can't be folded because the
5088 // DAG is not updated during lowering and a node claims to have two
5089 // uses while it only has one, use this version, and let isel match
5090 // another instruction if the load really happens to have more than
5091 // one use. Remove this version after this bug get fixed.
5092 // rdar://8434668, PR8156
5093 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5094   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5095     V = V.getOperand(0);
5096   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5097     V = V.getOperand(0);
5098   if (ISD::isNormalLoad(V.getNode()))
5099     return true;
5100   return false;
5101 }
5102
5103 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5104 /// a vector extract, and if both can be later optimized into a single load.
5105 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5106 /// here because otherwise a target specific shuffle node is going to be
5107 /// emitted for this shuffle, and the optimization not done.
5108 /// FIXME: This is probably not the best approach, but fix the problem
5109 /// until the right path is decided.
5110 static
5111 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5112                                          const TargetLowering &TLI) {
5113   EVT VT = V.getValueType();
5114   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5115
5116   // Be sure that the vector shuffle is present in a pattern like this:
5117   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5118   if (!V.hasOneUse())
5119     return false;
5120
5121   SDNode *N = *V.getNode()->use_begin();
5122   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5123     return false;
5124
5125   SDValue EltNo = N->getOperand(1);
5126   if (!isa<ConstantSDNode>(EltNo))
5127     return false;
5128
5129   // If the bit convert changed the number of elements, it is unsafe
5130   // to examine the mask.
5131   bool HasShuffleIntoBitcast = false;
5132   if (V.getOpcode() == ISD::BITCAST) {
5133     EVT SrcVT = V.getOperand(0).getValueType();
5134     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5135       return false;
5136     V = V.getOperand(0);
5137     HasShuffleIntoBitcast = true;
5138   }
5139
5140   // Select the input vector, guarding against out of range extract vector.
5141   unsigned NumElems = VT.getVectorNumElements();
5142   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5143   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5144   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5145
5146   // Skip one more bit_convert if necessary
5147   if (V.getOpcode() == ISD::BITCAST)
5148     V = V.getOperand(0);
5149
5150   if (ISD::isNormalLoad(V.getNode())) {
5151     // Is the original load suitable?
5152     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5153
5154     // FIXME: avoid the multi-use bug that is preventing lots of
5155     // of foldings to be detected, this is still wrong of course, but
5156     // give the temporary desired behavior, and if it happens that
5157     // the load has real more uses, during isel it will not fold, and
5158     // will generate poor code.
5159     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5160       return false;
5161
5162     if (!HasShuffleIntoBitcast)
5163       return true;
5164
5165     // If there's a bitcast before the shuffle, check if the load type and
5166     // alignment is valid.
5167     unsigned Align = LN0->getAlignment();
5168     unsigned NewAlign =
5169       TLI.getTargetData()->getABITypeAlignment(
5170                                     VT.getTypeForEVT(*DAG.getContext()));
5171
5172     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5173       return false;
5174   }
5175
5176   return true;
5177 }
5178
5179 static
5180 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5181   EVT VT = Op.getValueType();
5182
5183   // Canonizalize to v2f64.
5184   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5185   return DAG.getNode(ISD::BITCAST, dl, VT,
5186                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5187                                           V1, DAG));
5188 }
5189
5190 static
5191 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5192                         bool HasSSE2) {
5193   SDValue V1 = Op.getOperand(0);
5194   SDValue V2 = Op.getOperand(1);
5195   EVT VT = Op.getValueType();
5196
5197   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5198
5199   if (HasSSE2 && VT == MVT::v2f64)
5200     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5201
5202   // v4f32 or v4i32
5203   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5204 }
5205
5206 static
5207 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5208   SDValue V1 = Op.getOperand(0);
5209   SDValue V2 = Op.getOperand(1);
5210   EVT VT = Op.getValueType();
5211
5212   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5213          "unsupported shuffle type");
5214
5215   if (V2.getOpcode() == ISD::UNDEF)
5216     V2 = V1;
5217
5218   // v4i32 or v4f32
5219   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5220 }
5221
5222 static
5223 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5224   SDValue V1 = Op.getOperand(0);
5225   SDValue V2 = Op.getOperand(1);
5226   EVT VT = Op.getValueType();
5227   unsigned NumElems = VT.getVectorNumElements();
5228
5229   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5230   // operand of these instructions is only memory, so check if there's a
5231   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5232   // same masks.
5233   bool CanFoldLoad = false;
5234
5235   // Trivial case, when V2 comes from a load.
5236   if (MayFoldVectorLoad(V2))
5237     CanFoldLoad = true;
5238
5239   // When V1 is a load, it can be folded later into a store in isel, example:
5240   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5241   //    turns into:
5242   //  (MOVLPSmr addr:$src1, VR128:$src2)
5243   // So, recognize this potential and also use MOVLPS or MOVLPD
5244   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5245     CanFoldLoad = true;
5246
5247   if (CanFoldLoad) {
5248     if (HasSSE2 && NumElems == 2)
5249       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5250
5251     if (NumElems == 4)
5252       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5253   }
5254
5255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5256   // movl and movlp will both match v2i64, but v2i64 is never matched by
5257   // movl earlier because we make it strict to avoid messing with the movlp load
5258   // folding logic (see the code above getMOVLP call). Match it here then,
5259   // this is horrible, but will stay like this until we move all shuffle
5260   // matching to x86 specific nodes. Note that for the 1st condition all
5261   // types are matched with movsd.
5262   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5263     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5264   else if (HasSSE2)
5265     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5266
5267
5268   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5269
5270   // Invert the operand order and use SHUFPS to match it.
5271   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5272                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5273 }
5274
5275 static inline unsigned getUNPCKLOpcode(EVT VT) {
5276   switch(VT.getSimpleVT().SimpleTy) {
5277   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5278   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5279   case MVT::v4f32: return X86ISD::UNPCKLPS;
5280   case MVT::v2f64: return X86ISD::UNPCKLPD;
5281   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5282   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5283   default:
5284     llvm_unreachable("Unknow type for unpckl");
5285   }
5286   return 0;
5287 }
5288
5289 static inline unsigned getUNPCKHOpcode(EVT VT) {
5290   switch(VT.getSimpleVT().SimpleTy) {
5291   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5292   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5293   case MVT::v4f32: return X86ISD::UNPCKHPS;
5294   case MVT::v2f64: return X86ISD::UNPCKHPD;
5295   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5296   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5297   default:
5298     llvm_unreachable("Unknow type for unpckh");
5299   }
5300   return 0;
5301 }
5302
5303 static
5304 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5305                                const TargetLowering &TLI,
5306                                const X86Subtarget *Subtarget) {
5307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5308   EVT VT = Op.getValueType();
5309   DebugLoc dl = Op.getDebugLoc();
5310   SDValue V1 = Op.getOperand(0);
5311   SDValue V2 = Op.getOperand(1);
5312
5313   if (isZeroShuffle(SVOp))
5314     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5315
5316   // Handle splat operations
5317   if (SVOp->isSplat()) {
5318     // Special case, this is the only place now where it's
5319     // allowed to return a vector_shuffle operation without
5320     // using a target specific node, because *hopefully* it
5321     // will be optimized away by the dag combiner.
5322     if (VT.getVectorNumElements() <= 4 &&
5323         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5324       return Op;
5325
5326     // Handle splats by matching through known masks
5327     if (VT.getVectorNumElements() <= 4)
5328       return SDValue();
5329
5330     // Canonicalize all of the remaining to v4f32.
5331     return PromoteSplat(SVOp, DAG);
5332   }
5333
5334   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5335   // do it!
5336   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5337     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5338     if (NewOp.getNode())
5339       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5340   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5341     // FIXME: Figure out a cleaner way to do this.
5342     // Try to make use of movq to zero out the top part.
5343     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5344       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5345       if (NewOp.getNode()) {
5346         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5347           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5348                               DAG, Subtarget, dl);
5349       }
5350     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5351       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5352       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5353         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5354                             DAG, Subtarget, dl);
5355     }
5356   }
5357   return SDValue();
5358 }
5359
5360 SDValue
5361 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5362   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5363   SDValue V1 = Op.getOperand(0);
5364   SDValue V2 = Op.getOperand(1);
5365   EVT VT = Op.getValueType();
5366   DebugLoc dl = Op.getDebugLoc();
5367   unsigned NumElems = VT.getVectorNumElements();
5368   bool isMMX = VT.getSizeInBits() == 64;
5369   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5370   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5371   bool V1IsSplat = false;
5372   bool V2IsSplat = false;
5373   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5374   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5375   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5376   MachineFunction &MF = DAG.getMachineFunction();
5377   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5378
5379   // Shuffle operations on MMX not supported.
5380   if (isMMX)
5381     return Op;
5382
5383   // Vector shuffle lowering takes 3 steps:
5384   //
5385   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5386   //    narrowing and commutation of operands should be handled.
5387   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5388   //    shuffle nodes.
5389   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5390   //    so the shuffle can be broken into other shuffles and the legalizer can
5391   //    try the lowering again.
5392   //
5393   // The general ideia is that no vector_shuffle operation should be left to
5394   // be matched during isel, all of them must be converted to a target specific
5395   // node here.
5396
5397   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5398   // narrowing and commutation of operands should be handled. The actual code
5399   // doesn't include all of those, work in progress...
5400   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5401   if (NewOp.getNode())
5402     return NewOp;
5403
5404   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5405   // unpckh_undef). Only use pshufd if speed is more important than size.
5406   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5407     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5408       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5409   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5410     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5411       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5412
5413   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5414       RelaxedMayFoldVectorLoad(V1))
5415     return getMOVDDup(Op, dl, V1, DAG);
5416
5417   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5418     return getMOVHighToLow(Op, dl, DAG);
5419
5420   // Use to match splats
5421   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5422       (VT == MVT::v2f64 || VT == MVT::v2i64))
5423     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5424
5425   if (X86::isPSHUFDMask(SVOp)) {
5426     // The actual implementation will match the mask in the if above and then
5427     // during isel it can match several different instructions, not only pshufd
5428     // as its name says, sad but true, emulate the behavior for now...
5429     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5430         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5431
5432     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5433
5434     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5435       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5436
5437     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5438       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5439                                   TargetMask, DAG);
5440
5441     if (VT == MVT::v4f32)
5442       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5443                                   TargetMask, DAG);
5444   }
5445
5446   // Check if this can be converted into a logical shift.
5447   bool isLeft = false;
5448   unsigned ShAmt = 0;
5449   SDValue ShVal;
5450   bool isShift = getSubtarget()->hasSSE2() &&
5451     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5452   if (isShift && ShVal.hasOneUse()) {
5453     // If the shifted value has multiple uses, it may be cheaper to use
5454     // v_set0 + movlhps or movhlps, etc.
5455     EVT EltVT = VT.getVectorElementType();
5456     ShAmt *= EltVT.getSizeInBits();
5457     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5458   }
5459
5460   if (X86::isMOVLMask(SVOp)) {
5461     if (V1IsUndef)
5462       return V2;
5463     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5464       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5465     if (!X86::isMOVLPMask(SVOp)) {
5466       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5467         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5468
5469       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5470         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5471     }
5472   }
5473
5474   // FIXME: fold these into legal mask.
5475   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5476     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5477
5478   if (X86::isMOVHLPSMask(SVOp))
5479     return getMOVHighToLow(Op, dl, DAG);
5480
5481   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5482     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5483
5484   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5485     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5486
5487   if (X86::isMOVLPMask(SVOp))
5488     return getMOVLP(Op, dl, DAG, HasSSE2);
5489
5490   if (ShouldXformToMOVHLPS(SVOp) ||
5491       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5492     return CommuteVectorShuffle(SVOp, DAG);
5493
5494   if (isShift) {
5495     // No better options. Use a vshl / vsrl.
5496     EVT EltVT = VT.getVectorElementType();
5497     ShAmt *= EltVT.getSizeInBits();
5498     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5499   }
5500
5501   bool Commuted = false;
5502   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5503   // 1,1,1,1 -> v8i16 though.
5504   V1IsSplat = isSplatVector(V1.getNode());
5505   V2IsSplat = isSplatVector(V2.getNode());
5506
5507   // Canonicalize the splat or undef, if present, to be on the RHS.
5508   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5509     Op = CommuteVectorShuffle(SVOp, DAG);
5510     SVOp = cast<ShuffleVectorSDNode>(Op);
5511     V1 = SVOp->getOperand(0);
5512     V2 = SVOp->getOperand(1);
5513     std::swap(V1IsSplat, V2IsSplat);
5514     std::swap(V1IsUndef, V2IsUndef);
5515     Commuted = true;
5516   }
5517
5518   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5519     // Shuffling low element of v1 into undef, just return v1.
5520     if (V2IsUndef)
5521       return V1;
5522     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5523     // the instruction selector will not match, so get a canonical MOVL with
5524     // swapped operands to undo the commute.
5525     return getMOVL(DAG, dl, VT, V2, V1);
5526   }
5527
5528   if (X86::isUNPCKLMask(SVOp))
5529     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5530
5531   if (X86::isUNPCKHMask(SVOp))
5532     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5533
5534   if (V2IsSplat) {
5535     // Normalize mask so all entries that point to V2 points to its first
5536     // element then try to match unpck{h|l} again. If match, return a
5537     // new vector_shuffle with the corrected mask.
5538     SDValue NewMask = NormalizeMask(SVOp, DAG);
5539     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5540     if (NSVOp != SVOp) {
5541       if (X86::isUNPCKLMask(NSVOp, true)) {
5542         return NewMask;
5543       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5544         return NewMask;
5545       }
5546     }
5547   }
5548
5549   if (Commuted) {
5550     // Commute is back and try unpck* again.
5551     // FIXME: this seems wrong.
5552     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5553     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5554
5555     if (X86::isUNPCKLMask(NewSVOp))
5556       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5557
5558     if (X86::isUNPCKHMask(NewSVOp))
5559       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5560   }
5561
5562   // Normalize the node to match x86 shuffle ops if needed
5563   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5564     return CommuteVectorShuffle(SVOp, DAG);
5565
5566   // The checks below are all present in isShuffleMaskLegal, but they are
5567   // inlined here right now to enable us to directly emit target specific
5568   // nodes, and remove one by one until they don't return Op anymore.
5569   SmallVector<int, 16> M;
5570   SVOp->getMask(M);
5571
5572   if (isPALIGNRMask(M, VT, HasSSSE3))
5573     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5574                                 X86::getShufflePALIGNRImmediate(SVOp),
5575                                 DAG);
5576
5577   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5578       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5579     if (VT == MVT::v2f64)
5580       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5581     if (VT == MVT::v2i64)
5582       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5583   }
5584
5585   if (isPSHUFHWMask(M, VT))
5586     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5587                                 X86::getShufflePSHUFHWImmediate(SVOp),
5588                                 DAG);
5589
5590   if (isPSHUFLWMask(M, VT))
5591     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5592                                 X86::getShufflePSHUFLWImmediate(SVOp),
5593                                 DAG);
5594
5595   if (isSHUFPMask(M, VT)) {
5596     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5597     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5598       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5599                                   TargetMask, DAG);
5600     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5601       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5602                                   TargetMask, DAG);
5603   }
5604
5605   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5606     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5607       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5608   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5609     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5610       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5611
5612   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5613   if (VT == MVT::v8i16) {
5614     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5615     if (NewOp.getNode())
5616       return NewOp;
5617   }
5618
5619   if (VT == MVT::v16i8) {
5620     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5621     if (NewOp.getNode())
5622       return NewOp;
5623   }
5624
5625   // Handle all 4 wide cases with a number of shuffles.
5626   if (NumElems == 4)
5627     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5628
5629   return SDValue();
5630 }
5631
5632 SDValue
5633 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5634                                                 SelectionDAG &DAG) const {
5635   EVT VT = Op.getValueType();
5636   DebugLoc dl = Op.getDebugLoc();
5637   if (VT.getSizeInBits() == 8) {
5638     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5639                                     Op.getOperand(0), Op.getOperand(1));
5640     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5641                                     DAG.getValueType(VT));
5642     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5643   } else if (VT.getSizeInBits() == 16) {
5644     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5645     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5646     if (Idx == 0)
5647       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5648                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5649                                      DAG.getNode(ISD::BITCAST, dl,
5650                                                  MVT::v4i32,
5651                                                  Op.getOperand(0)),
5652                                      Op.getOperand(1)));
5653     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5654                                     Op.getOperand(0), Op.getOperand(1));
5655     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5656                                     DAG.getValueType(VT));
5657     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5658   } else if (VT == MVT::f32) {
5659     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5660     // the result back to FR32 register. It's only worth matching if the
5661     // result has a single use which is a store or a bitcast to i32.  And in
5662     // the case of a store, it's not worth it if the index is a constant 0,
5663     // because a MOVSSmr can be used instead, which is smaller and faster.
5664     if (!Op.hasOneUse())
5665       return SDValue();
5666     SDNode *User = *Op.getNode()->use_begin();
5667     if ((User->getOpcode() != ISD::STORE ||
5668          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5669           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5670         (User->getOpcode() != ISD::BITCAST ||
5671          User->getValueType(0) != MVT::i32))
5672       return SDValue();
5673     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5674                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5675                                               Op.getOperand(0)),
5676                                               Op.getOperand(1));
5677     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5678   } else if (VT == MVT::i32) {
5679     // ExtractPS works with constant index.
5680     if (isa<ConstantSDNode>(Op.getOperand(1)))
5681       return Op;
5682   }
5683   return SDValue();
5684 }
5685
5686
5687 SDValue
5688 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5689                                            SelectionDAG &DAG) const {
5690   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5691     return SDValue();
5692
5693   if (Subtarget->hasSSE41()) {
5694     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5695     if (Res.getNode())
5696       return Res;
5697   }
5698
5699   EVT VT = Op.getValueType();
5700   DebugLoc dl = Op.getDebugLoc();
5701   // TODO: handle v16i8.
5702   if (VT.getSizeInBits() == 16) {
5703     SDValue Vec = Op.getOperand(0);
5704     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5705     if (Idx == 0)
5706       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5707                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5708                                      DAG.getNode(ISD::BITCAST, dl,
5709                                                  MVT::v4i32, Vec),
5710                                      Op.getOperand(1)));
5711     // Transform it so it match pextrw which produces a 32-bit result.
5712     EVT EltVT = MVT::i32;
5713     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5714                                     Op.getOperand(0), Op.getOperand(1));
5715     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5716                                     DAG.getValueType(VT));
5717     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5718   } else if (VT.getSizeInBits() == 32) {
5719     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5720     if (Idx == 0)
5721       return Op;
5722
5723     // SHUFPS the element to the lowest double word, then movss.
5724     int Mask[4] = { Idx, -1, -1, -1 };
5725     EVT VVT = Op.getOperand(0).getValueType();
5726     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5727                                        DAG.getUNDEF(VVT), Mask);
5728     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5729                        DAG.getIntPtrConstant(0));
5730   } else if (VT.getSizeInBits() == 64) {
5731     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5732     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5733     //        to match extract_elt for f64.
5734     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5735     if (Idx == 0)
5736       return Op;
5737
5738     // UNPCKHPD the element to the lowest double word, then movsd.
5739     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5740     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5741     int Mask[2] = { 1, -1 };
5742     EVT VVT = Op.getOperand(0).getValueType();
5743     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5744                                        DAG.getUNDEF(VVT), Mask);
5745     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5746                        DAG.getIntPtrConstant(0));
5747   }
5748
5749   return SDValue();
5750 }
5751
5752 SDValue
5753 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5754                                                SelectionDAG &DAG) const {
5755   EVT VT = Op.getValueType();
5756   EVT EltVT = VT.getVectorElementType();
5757   DebugLoc dl = Op.getDebugLoc();
5758
5759   SDValue N0 = Op.getOperand(0);
5760   SDValue N1 = Op.getOperand(1);
5761   SDValue N2 = Op.getOperand(2);
5762
5763   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5764       isa<ConstantSDNode>(N2)) {
5765     unsigned Opc;
5766     if (VT == MVT::v8i16)
5767       Opc = X86ISD::PINSRW;
5768     else if (VT == MVT::v16i8)
5769       Opc = X86ISD::PINSRB;
5770     else
5771       Opc = X86ISD::PINSRB;
5772
5773     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5774     // argument.
5775     if (N1.getValueType() != MVT::i32)
5776       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5777     if (N2.getValueType() != MVT::i32)
5778       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5779     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5780   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5781     // Bits [7:6] of the constant are the source select.  This will always be
5782     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5783     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5784     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5785     // Bits [5:4] of the constant are the destination select.  This is the
5786     //  value of the incoming immediate.
5787     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5788     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5789     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5790     // Create this as a scalar to vector..
5791     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5792     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5793   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5794     // PINSR* works with constant index.
5795     return Op;
5796   }
5797   return SDValue();
5798 }
5799
5800 SDValue
5801 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5802   EVT VT = Op.getValueType();
5803   EVT EltVT = VT.getVectorElementType();
5804
5805   if (Subtarget->hasSSE41())
5806     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5807
5808   if (EltVT == MVT::i8)
5809     return SDValue();
5810
5811   DebugLoc dl = Op.getDebugLoc();
5812   SDValue N0 = Op.getOperand(0);
5813   SDValue N1 = Op.getOperand(1);
5814   SDValue N2 = Op.getOperand(2);
5815
5816   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5817     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5818     // as its second argument.
5819     if (N1.getValueType() != MVT::i32)
5820       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5821     if (N2.getValueType() != MVT::i32)
5822       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5823     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5824   }
5825   return SDValue();
5826 }
5827
5828 SDValue
5829 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5830   DebugLoc dl = Op.getDebugLoc();
5831
5832   if (Op.getValueType() == MVT::v1i64 &&
5833       Op.getOperand(0).getValueType() == MVT::i64)
5834     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5835
5836   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5837   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5838          "Expected an SSE type!");
5839   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5840                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5841 }
5842
5843 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5844 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5845 // one of the above mentioned nodes. It has to be wrapped because otherwise
5846 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5847 // be used to form addressing mode. These wrapped nodes will be selected
5848 // into MOV32ri.
5849 SDValue
5850 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5851   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5852
5853   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5854   // global base reg.
5855   unsigned char OpFlag = 0;
5856   unsigned WrapperKind = X86ISD::Wrapper;
5857   CodeModel::Model M = getTargetMachine().getCodeModel();
5858
5859   if (Subtarget->isPICStyleRIPRel() &&
5860       (M == CodeModel::Small || M == CodeModel::Kernel))
5861     WrapperKind = X86ISD::WrapperRIP;
5862   else if (Subtarget->isPICStyleGOT())
5863     OpFlag = X86II::MO_GOTOFF;
5864   else if (Subtarget->isPICStyleStubPIC())
5865     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5866
5867   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5868                                              CP->getAlignment(),
5869                                              CP->getOffset(), OpFlag);
5870   DebugLoc DL = CP->getDebugLoc();
5871   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5872   // With PIC, the address is actually $g + Offset.
5873   if (OpFlag) {
5874     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5875                          DAG.getNode(X86ISD::GlobalBaseReg,
5876                                      DebugLoc(), getPointerTy()),
5877                          Result);
5878   }
5879
5880   return Result;
5881 }
5882
5883 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5884   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5885
5886   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5887   // global base reg.
5888   unsigned char OpFlag = 0;
5889   unsigned WrapperKind = X86ISD::Wrapper;
5890   CodeModel::Model M = getTargetMachine().getCodeModel();
5891
5892   if (Subtarget->isPICStyleRIPRel() &&
5893       (M == CodeModel::Small || M == CodeModel::Kernel))
5894     WrapperKind = X86ISD::WrapperRIP;
5895   else if (Subtarget->isPICStyleGOT())
5896     OpFlag = X86II::MO_GOTOFF;
5897   else if (Subtarget->isPICStyleStubPIC())
5898     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5899
5900   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5901                                           OpFlag);
5902   DebugLoc DL = JT->getDebugLoc();
5903   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5904
5905   // With PIC, the address is actually $g + Offset.
5906   if (OpFlag)
5907     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5908                          DAG.getNode(X86ISD::GlobalBaseReg,
5909                                      DebugLoc(), getPointerTy()),
5910                          Result);
5911
5912   return Result;
5913 }
5914
5915 SDValue
5916 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5917   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5918
5919   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5920   // global base reg.
5921   unsigned char OpFlag = 0;
5922   unsigned WrapperKind = X86ISD::Wrapper;
5923   CodeModel::Model M = getTargetMachine().getCodeModel();
5924
5925   if (Subtarget->isPICStyleRIPRel() &&
5926       (M == CodeModel::Small || M == CodeModel::Kernel))
5927     WrapperKind = X86ISD::WrapperRIP;
5928   else if (Subtarget->isPICStyleGOT())
5929     OpFlag = X86II::MO_GOTOFF;
5930   else if (Subtarget->isPICStyleStubPIC())
5931     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5932
5933   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5934
5935   DebugLoc DL = Op.getDebugLoc();
5936   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5937
5938
5939   // With PIC, the address is actually $g + Offset.
5940   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5941       !Subtarget->is64Bit()) {
5942     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5943                          DAG.getNode(X86ISD::GlobalBaseReg,
5944                                      DebugLoc(), getPointerTy()),
5945                          Result);
5946   }
5947
5948   return Result;
5949 }
5950
5951 SDValue
5952 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5953   // Create the TargetBlockAddressAddress node.
5954   unsigned char OpFlags =
5955     Subtarget->ClassifyBlockAddressReference();
5956   CodeModel::Model M = getTargetMachine().getCodeModel();
5957   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5958   DebugLoc dl = Op.getDebugLoc();
5959   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5960                                        /*isTarget=*/true, OpFlags);
5961
5962   if (Subtarget->isPICStyleRIPRel() &&
5963       (M == CodeModel::Small || M == CodeModel::Kernel))
5964     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5965   else
5966     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5967
5968   // With PIC, the address is actually $g + Offset.
5969   if (isGlobalRelativeToPICBase(OpFlags)) {
5970     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5971                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5972                          Result);
5973   }
5974
5975   return Result;
5976 }
5977
5978 SDValue
5979 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5980                                       int64_t Offset,
5981                                       SelectionDAG &DAG) const {
5982   // Create the TargetGlobalAddress node, folding in the constant
5983   // offset if it is legal.
5984   unsigned char OpFlags =
5985     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5986   CodeModel::Model M = getTargetMachine().getCodeModel();
5987   SDValue Result;
5988   if (OpFlags == X86II::MO_NO_FLAG &&
5989       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5990     // A direct static reference to a global.
5991     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5992     Offset = 0;
5993   } else {
5994     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5995   }
5996
5997   if (Subtarget->isPICStyleRIPRel() &&
5998       (M == CodeModel::Small || M == CodeModel::Kernel))
5999     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6000   else
6001     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6002
6003   // With PIC, the address is actually $g + Offset.
6004   if (isGlobalRelativeToPICBase(OpFlags)) {
6005     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6006                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6007                          Result);
6008   }
6009
6010   // For globals that require a load from a stub to get the address, emit the
6011   // load.
6012   if (isGlobalStubReference(OpFlags))
6013     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6014                          MachinePointerInfo::getGOT(), false, false, 0);
6015
6016   // If there was a non-zero offset that we didn't fold, create an explicit
6017   // addition for it.
6018   if (Offset != 0)
6019     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6020                          DAG.getConstant(Offset, getPointerTy()));
6021
6022   return Result;
6023 }
6024
6025 SDValue
6026 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6027   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6028   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6029   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6030 }
6031
6032 static SDValue
6033 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6034            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6035            unsigned char OperandFlags) {
6036   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6037   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6038   DebugLoc dl = GA->getDebugLoc();
6039   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6040                                            GA->getValueType(0),
6041                                            GA->getOffset(),
6042                                            OperandFlags);
6043   if (InFlag) {
6044     SDValue Ops[] = { Chain,  TGA, *InFlag };
6045     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6046   } else {
6047     SDValue Ops[]  = { Chain, TGA };
6048     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6049   }
6050
6051   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6052   MFI->setAdjustsStack(true);
6053
6054   SDValue Flag = Chain.getValue(1);
6055   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6056 }
6057
6058 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6059 static SDValue
6060 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6061                                 const EVT PtrVT) {
6062   SDValue InFlag;
6063   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6064   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6065                                      DAG.getNode(X86ISD::GlobalBaseReg,
6066                                                  DebugLoc(), PtrVT), InFlag);
6067   InFlag = Chain.getValue(1);
6068
6069   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6070 }
6071
6072 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6073 static SDValue
6074 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6075                                 const EVT PtrVT) {
6076   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6077                     X86::RAX, X86II::MO_TLSGD);
6078 }
6079
6080 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6081 // "local exec" model.
6082 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6083                                    const EVT PtrVT, TLSModel::Model model,
6084                                    bool is64Bit) {
6085   DebugLoc dl = GA->getDebugLoc();
6086
6087   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6088   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6089                                                          is64Bit ? 257 : 256));
6090
6091   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6092                                       DAG.getIntPtrConstant(0),
6093                                       MachinePointerInfo(Ptr), false, false, 0);
6094
6095   unsigned char OperandFlags = 0;
6096   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6097   // initialexec.
6098   unsigned WrapperKind = X86ISD::Wrapper;
6099   if (model == TLSModel::LocalExec) {
6100     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6101   } else if (is64Bit) {
6102     assert(model == TLSModel::InitialExec);
6103     OperandFlags = X86II::MO_GOTTPOFF;
6104     WrapperKind = X86ISD::WrapperRIP;
6105   } else {
6106     assert(model == TLSModel::InitialExec);
6107     OperandFlags = X86II::MO_INDNTPOFF;
6108   }
6109
6110   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6111   // exec)
6112   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6113                                            GA->getValueType(0),
6114                                            GA->getOffset(), OperandFlags);
6115   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6116
6117   if (model == TLSModel::InitialExec)
6118     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6119                          MachinePointerInfo::getGOT(), false, false, 0);
6120
6121   // The address of the thread local variable is the add of the thread
6122   // pointer with the offset of the variable.
6123   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6124 }
6125
6126 SDValue
6127 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6128
6129   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6130   const GlobalValue *GV = GA->getGlobal();
6131
6132   if (Subtarget->isTargetELF()) {
6133     // TODO: implement the "local dynamic" model
6134     // TODO: implement the "initial exec"model for pic executables
6135
6136     // If GV is an alias then use the aliasee for determining
6137     // thread-localness.
6138     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6139       GV = GA->resolveAliasedGlobal(false);
6140
6141     TLSModel::Model model
6142       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6143
6144     switch (model) {
6145       case TLSModel::GeneralDynamic:
6146       case TLSModel::LocalDynamic: // not implemented
6147         if (Subtarget->is64Bit())
6148           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6149         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6150
6151       case TLSModel::InitialExec:
6152       case TLSModel::LocalExec:
6153         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6154                                    Subtarget->is64Bit());
6155     }
6156   } else if (Subtarget->isTargetDarwin()) {
6157     // Darwin only has one model of TLS.  Lower to that.
6158     unsigned char OpFlag = 0;
6159     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6160                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6161
6162     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6163     // global base reg.
6164     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6165                   !Subtarget->is64Bit();
6166     if (PIC32)
6167       OpFlag = X86II::MO_TLVP_PIC_BASE;
6168     else
6169       OpFlag = X86II::MO_TLVP;
6170     DebugLoc DL = Op.getDebugLoc();
6171     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6172                                                 GA->getValueType(0),
6173                                                 GA->getOffset(), OpFlag);
6174     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6175
6176     // With PIC32, the address is actually $g + Offset.
6177     if (PIC32)
6178       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6179                            DAG.getNode(X86ISD::GlobalBaseReg,
6180                                        DebugLoc(), getPointerTy()),
6181                            Offset);
6182
6183     // Lowering the machine isd will make sure everything is in the right
6184     // location.
6185     SDValue Chain = DAG.getEntryNode();
6186     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6187     SDValue Args[] = { Chain, Offset };
6188     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6189
6190     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6191     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6192     MFI->setAdjustsStack(true);
6193     
6194     // And our return value (tls address) is in the standard call return value
6195     // location.
6196     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6197     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6198   }
6199
6200   assert(false &&
6201          "TLS not implemented for this target.");
6202
6203   llvm_unreachable("Unreachable");
6204   return SDValue();
6205 }
6206
6207
6208 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6209 /// take a 2 x i32 value to shift plus a shift amount.
6210 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6211   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6212   EVT VT = Op.getValueType();
6213   unsigned VTBits = VT.getSizeInBits();
6214   DebugLoc dl = Op.getDebugLoc();
6215   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6216   SDValue ShOpLo = Op.getOperand(0);
6217   SDValue ShOpHi = Op.getOperand(1);
6218   SDValue ShAmt  = Op.getOperand(2);
6219   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6220                                      DAG.getConstant(VTBits - 1, MVT::i8))
6221                        : DAG.getConstant(0, VT);
6222
6223   SDValue Tmp2, Tmp3;
6224   if (Op.getOpcode() == ISD::SHL_PARTS) {
6225     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6226     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6227   } else {
6228     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6229     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6230   }
6231
6232   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6233                                 DAG.getConstant(VTBits, MVT::i8));
6234   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6235                              AndNode, DAG.getConstant(0, MVT::i8));
6236
6237   SDValue Hi, Lo;
6238   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6239   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6240   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6241
6242   if (Op.getOpcode() == ISD::SHL_PARTS) {
6243     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6244     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6245   } else {
6246     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6247     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6248   }
6249
6250   SDValue Ops[2] = { Lo, Hi };
6251   return DAG.getMergeValues(Ops, 2, dl);
6252 }
6253
6254 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6255                                            SelectionDAG &DAG) const {
6256   EVT SrcVT = Op.getOperand(0).getValueType();
6257
6258   if (SrcVT.isVector())
6259     return SDValue();
6260
6261   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6262          "Unknown SINT_TO_FP to lower!");
6263
6264   // These are really Legal; return the operand so the caller accepts it as
6265   // Legal.
6266   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6267     return Op;
6268   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6269       Subtarget->is64Bit()) {
6270     return Op;
6271   }
6272
6273   DebugLoc dl = Op.getDebugLoc();
6274   unsigned Size = SrcVT.getSizeInBits()/8;
6275   MachineFunction &MF = DAG.getMachineFunction();
6276   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6277   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6278   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6279                                StackSlot,
6280                                MachinePointerInfo::getFixedStack(SSFI),
6281                                false, false, 0);
6282   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6283 }
6284
6285 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6286                                      SDValue StackSlot,
6287                                      SelectionDAG &DAG) const {
6288   // Build the FILD
6289   DebugLoc DL = Op.getDebugLoc();
6290   SDVTList Tys;
6291   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6292   if (useSSE)
6293     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
6294   else
6295     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6296
6297   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6298
6299   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6300   MachineMemOperand *MMO =
6301     DAG.getMachineFunction()
6302     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6303                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6304
6305   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6306   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6307                                            X86ISD::FILD, DL,
6308                                            Tys, Ops, array_lengthof(Ops),
6309                                            SrcVT, MMO);
6310
6311   if (useSSE) {
6312     Chain = Result.getValue(1);
6313     SDValue InFlag = Result.getValue(2);
6314
6315     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6316     // shouldn't be necessary except that RFP cannot be live across
6317     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6318     MachineFunction &MF = DAG.getMachineFunction();
6319     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6320     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6321     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6322     Tys = DAG.getVTList(MVT::Other);
6323     SDValue Ops[] = {
6324       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6325     };
6326     MachineMemOperand *MMO =
6327       DAG.getMachineFunction()
6328       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6329                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6330
6331     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6332                                     Ops, array_lengthof(Ops),
6333                                     Op.getValueType(), MMO);
6334     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6335                          MachinePointerInfo::getFixedStack(SSFI),
6336                          false, false, 0);
6337   }
6338
6339   return Result;
6340 }
6341
6342 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6343 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6344                                                SelectionDAG &DAG) const {
6345   // This algorithm is not obvious. Here it is in C code, more or less:
6346   /*
6347     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6348       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6349       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6350
6351       // Copy ints to xmm registers.
6352       __m128i xh = _mm_cvtsi32_si128( hi );
6353       __m128i xl = _mm_cvtsi32_si128( lo );
6354
6355       // Combine into low half of a single xmm register.
6356       __m128i x = _mm_unpacklo_epi32( xh, xl );
6357       __m128d d;
6358       double sd;
6359
6360       // Merge in appropriate exponents to give the integer bits the right
6361       // magnitude.
6362       x = _mm_unpacklo_epi32( x, exp );
6363
6364       // Subtract away the biases to deal with the IEEE-754 double precision
6365       // implicit 1.
6366       d = _mm_sub_pd( (__m128d) x, bias );
6367
6368       // All conversions up to here are exact. The correctly rounded result is
6369       // calculated using the current rounding mode using the following
6370       // horizontal add.
6371       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6372       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6373                                 // store doesn't really need to be here (except
6374                                 // maybe to zero the other double)
6375       return sd;
6376     }
6377   */
6378
6379   DebugLoc dl = Op.getDebugLoc();
6380   LLVMContext *Context = DAG.getContext();
6381
6382   // Build some magic constants.
6383   std::vector<Constant*> CV0;
6384   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6385   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6386   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6387   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6388   Constant *C0 = ConstantVector::get(CV0);
6389   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6390
6391   std::vector<Constant*> CV1;
6392   CV1.push_back(
6393     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6394   CV1.push_back(
6395     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6396   Constant *C1 = ConstantVector::get(CV1);
6397   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6398
6399   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6400                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6401                                         Op.getOperand(0),
6402                                         DAG.getIntPtrConstant(1)));
6403   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6404                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6405                                         Op.getOperand(0),
6406                                         DAG.getIntPtrConstant(0)));
6407   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6408   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6409                               MachinePointerInfo::getConstantPool(),
6410                               false, false, 16);
6411   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6412   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6413   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6414                               MachinePointerInfo::getConstantPool(),
6415                               false, false, 16);
6416   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6417
6418   // Add the halves; easiest way is to swap them into another reg first.
6419   int ShufMask[2] = { 1, -1 };
6420   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6421                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6422   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6423   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6424                      DAG.getIntPtrConstant(0));
6425 }
6426
6427 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6428 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6429                                                SelectionDAG &DAG) const {
6430   DebugLoc dl = Op.getDebugLoc();
6431   // FP constant to bias correct the final result.
6432   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6433                                    MVT::f64);
6434
6435   // Load the 32-bit value into an XMM register.
6436   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6437                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6438                                          Op.getOperand(0),
6439                                          DAG.getIntPtrConstant(0)));
6440
6441   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6442                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6443                      DAG.getIntPtrConstant(0));
6444
6445   // Or the load with the bias.
6446   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6447                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6448                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6449                                                    MVT::v2f64, Load)),
6450                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6451                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6452                                                    MVT::v2f64, Bias)));
6453   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6454                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6455                    DAG.getIntPtrConstant(0));
6456
6457   // Subtract the bias.
6458   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6459
6460   // Handle final rounding.
6461   EVT DestVT = Op.getValueType();
6462
6463   if (DestVT.bitsLT(MVT::f64)) {
6464     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6465                        DAG.getIntPtrConstant(0));
6466   } else if (DestVT.bitsGT(MVT::f64)) {
6467     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6468   }
6469
6470   // Handle final rounding.
6471   return Sub;
6472 }
6473
6474 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6475                                            SelectionDAG &DAG) const {
6476   SDValue N0 = Op.getOperand(0);
6477   DebugLoc dl = Op.getDebugLoc();
6478
6479   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6480   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6481   // the optimization here.
6482   if (DAG.SignBitIsZero(N0))
6483     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6484
6485   EVT SrcVT = N0.getValueType();
6486   EVT DstVT = Op.getValueType();
6487   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6488     return LowerUINT_TO_FP_i64(Op, DAG);
6489   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6490     return LowerUINT_TO_FP_i32(Op, DAG);
6491
6492   // Make a 64-bit buffer, and use it to build an FILD.
6493   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6494   if (SrcVT == MVT::i32) {
6495     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6496     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6497                                      getPointerTy(), StackSlot, WordOff);
6498     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6499                                   StackSlot, MachinePointerInfo(),
6500                                   false, false, 0);
6501     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6502                                   OffsetSlot, MachinePointerInfo(),
6503                                   false, false, 0);
6504     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6505     return Fild;
6506   }
6507
6508   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6509   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6510                                 StackSlot, MachinePointerInfo(),
6511                                false, false, 0);
6512   // For i64 source, we need to add the appropriate power of 2 if the input
6513   // was negative.  This is the same as the optimization in
6514   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6515   // we must be careful to do the computation in x87 extended precision, not
6516   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6517   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6518   MachineMemOperand *MMO =
6519     DAG.getMachineFunction()
6520     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6521                           MachineMemOperand::MOLoad, 8, 8);
6522
6523   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6524   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6525   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6526                                          MVT::i64, MMO);
6527
6528   APInt FF(32, 0x5F800000ULL);
6529
6530   // Check whether the sign bit is set.
6531   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6532                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6533                                  ISD::SETLT);
6534
6535   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6536   SDValue FudgePtr = DAG.getConstantPool(
6537                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6538                                          getPointerTy());
6539
6540   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6541   SDValue Zero = DAG.getIntPtrConstant(0);
6542   SDValue Four = DAG.getIntPtrConstant(4);
6543   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6544                                Zero, Four);
6545   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6546
6547   // Load the value out, extending it from f32 to f80.
6548   // FIXME: Avoid the extend by constructing the right constant pool?
6549   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6550                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6551                                  MVT::f32, false, false, 4);
6552   // Extend everything to 80 bits to force it to be done on x87.
6553   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6554   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6555 }
6556
6557 std::pair<SDValue,SDValue> X86TargetLowering::
6558 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6559   DebugLoc DL = Op.getDebugLoc();
6560
6561   EVT DstTy = Op.getValueType();
6562
6563   if (!IsSigned) {
6564     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6565     DstTy = MVT::i64;
6566   }
6567
6568   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6569          DstTy.getSimpleVT() >= MVT::i16 &&
6570          "Unknown FP_TO_SINT to lower!");
6571
6572   // These are really Legal.
6573   if (DstTy == MVT::i32 &&
6574       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6575     return std::make_pair(SDValue(), SDValue());
6576   if (Subtarget->is64Bit() &&
6577       DstTy == MVT::i64 &&
6578       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6579     return std::make_pair(SDValue(), SDValue());
6580
6581   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6582   // stack slot.
6583   MachineFunction &MF = DAG.getMachineFunction();
6584   unsigned MemSize = DstTy.getSizeInBits()/8;
6585   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6586   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6587
6588
6589
6590   unsigned Opc;
6591   switch (DstTy.getSimpleVT().SimpleTy) {
6592   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6593   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6594   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6595   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6596   }
6597
6598   SDValue Chain = DAG.getEntryNode();
6599   SDValue Value = Op.getOperand(0);
6600   EVT TheVT = Op.getOperand(0).getValueType();
6601   if (isScalarFPTypeInSSEReg(TheVT)) {
6602     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6603     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6604                          MachinePointerInfo::getFixedStack(SSFI),
6605                          false, false, 0);
6606     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6607     SDValue Ops[] = {
6608       Chain, StackSlot, DAG.getValueType(TheVT)
6609     };
6610
6611     MachineMemOperand *MMO =
6612       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6613                               MachineMemOperand::MOLoad, MemSize, MemSize);
6614     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6615                                     DstTy, MMO);
6616     Chain = Value.getValue(1);
6617     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6618     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6619   }
6620
6621   MachineMemOperand *MMO =
6622     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6623                             MachineMemOperand::MOStore, MemSize, MemSize);
6624
6625   // Build the FP_TO_INT*_IN_MEM
6626   SDValue Ops[] = { Chain, Value, StackSlot };
6627   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6628                                          Ops, 3, DstTy, MMO);
6629
6630   return std::make_pair(FIST, StackSlot);
6631 }
6632
6633 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6634                                            SelectionDAG &DAG) const {
6635   if (Op.getValueType().isVector())
6636     return SDValue();
6637
6638   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6639   SDValue FIST = Vals.first, StackSlot = Vals.second;
6640   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6641   if (FIST.getNode() == 0) return Op;
6642
6643   // Load the result.
6644   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6645                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6646 }
6647
6648 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6649                                            SelectionDAG &DAG) const {
6650   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6651   SDValue FIST = Vals.first, StackSlot = Vals.second;
6652   assert(FIST.getNode() && "Unexpected failure");
6653
6654   // Load the result.
6655   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6656                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6657 }
6658
6659 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6660                                      SelectionDAG &DAG) const {
6661   LLVMContext *Context = DAG.getContext();
6662   DebugLoc dl = Op.getDebugLoc();
6663   EVT VT = Op.getValueType();
6664   EVT EltVT = VT;
6665   if (VT.isVector())
6666     EltVT = VT.getVectorElementType();
6667   std::vector<Constant*> CV;
6668   if (EltVT == MVT::f64) {
6669     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6670     CV.push_back(C);
6671     CV.push_back(C);
6672   } else {
6673     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6674     CV.push_back(C);
6675     CV.push_back(C);
6676     CV.push_back(C);
6677     CV.push_back(C);
6678   }
6679   Constant *C = ConstantVector::get(CV);
6680   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6681   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6682                              MachinePointerInfo::getConstantPool(),
6683                              false, false, 16);
6684   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6685 }
6686
6687 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6688   LLVMContext *Context = DAG.getContext();
6689   DebugLoc dl = Op.getDebugLoc();
6690   EVT VT = Op.getValueType();
6691   EVT EltVT = VT;
6692   if (VT.isVector())
6693     EltVT = VT.getVectorElementType();
6694   std::vector<Constant*> CV;
6695   if (EltVT == MVT::f64) {
6696     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6697     CV.push_back(C);
6698     CV.push_back(C);
6699   } else {
6700     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6701     CV.push_back(C);
6702     CV.push_back(C);
6703     CV.push_back(C);
6704     CV.push_back(C);
6705   }
6706   Constant *C = ConstantVector::get(CV);
6707   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6708   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6709                              MachinePointerInfo::getConstantPool(),
6710                              false, false, 16);
6711   if (VT.isVector()) {
6712     return DAG.getNode(ISD::BITCAST, dl, VT,
6713                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6714                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6715                                 Op.getOperand(0)),
6716                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6717   } else {
6718     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6719   }
6720 }
6721
6722 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6723   LLVMContext *Context = DAG.getContext();
6724   SDValue Op0 = Op.getOperand(0);
6725   SDValue Op1 = Op.getOperand(1);
6726   DebugLoc dl = Op.getDebugLoc();
6727   EVT VT = Op.getValueType();
6728   EVT SrcVT = Op1.getValueType();
6729
6730   // If second operand is smaller, extend it first.
6731   if (SrcVT.bitsLT(VT)) {
6732     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6733     SrcVT = VT;
6734   }
6735   // And if it is bigger, shrink it first.
6736   if (SrcVT.bitsGT(VT)) {
6737     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6738     SrcVT = VT;
6739   }
6740
6741   // At this point the operands and the result should have the same
6742   // type, and that won't be f80 since that is not custom lowered.
6743
6744   // First get the sign bit of second operand.
6745   std::vector<Constant*> CV;
6746   if (SrcVT == MVT::f64) {
6747     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6748     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6749   } else {
6750     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6751     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6752     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6753     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6754   }
6755   Constant *C = ConstantVector::get(CV);
6756   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6757   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6758                               MachinePointerInfo::getConstantPool(),
6759                               false, false, 16);
6760   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6761
6762   // Shift sign bit right or left if the two operands have different types.
6763   if (SrcVT.bitsGT(VT)) {
6764     // Op0 is MVT::f32, Op1 is MVT::f64.
6765     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6766     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6767                           DAG.getConstant(32, MVT::i32));
6768     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6769     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6770                           DAG.getIntPtrConstant(0));
6771   }
6772
6773   // Clear first operand sign bit.
6774   CV.clear();
6775   if (VT == MVT::f64) {
6776     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6778   } else {
6779     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6780     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6781     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6782     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6783   }
6784   C = ConstantVector::get(CV);
6785   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6786   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6787                               MachinePointerInfo::getConstantPool(),
6788                               false, false, 16);
6789   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6790
6791   // Or the value with the sign bit.
6792   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6793 }
6794
6795 /// Emit nodes that will be selected as "test Op0,Op0", or something
6796 /// equivalent.
6797 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6798                                     SelectionDAG &DAG) const {
6799   DebugLoc dl = Op.getDebugLoc();
6800
6801   // CF and OF aren't always set the way we want. Determine which
6802   // of these we need.
6803   bool NeedCF = false;
6804   bool NeedOF = false;
6805   switch (X86CC) {
6806   default: break;
6807   case X86::COND_A: case X86::COND_AE:
6808   case X86::COND_B: case X86::COND_BE:
6809     NeedCF = true;
6810     break;
6811   case X86::COND_G: case X86::COND_GE:
6812   case X86::COND_L: case X86::COND_LE:
6813   case X86::COND_O: case X86::COND_NO:
6814     NeedOF = true;
6815     break;
6816   }
6817
6818   // See if we can use the EFLAGS value from the operand instead of
6819   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6820   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6821   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6822     // Emit a CMP with 0, which is the TEST pattern.
6823     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6824                        DAG.getConstant(0, Op.getValueType()));
6825
6826   unsigned Opcode = 0;
6827   unsigned NumOperands = 0;
6828   switch (Op.getNode()->getOpcode()) {
6829   case ISD::ADD:
6830     // Due to an isel shortcoming, be conservative if this add is likely to be
6831     // selected as part of a load-modify-store instruction. When the root node
6832     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6833     // uses of other nodes in the match, such as the ADD in this case. This
6834     // leads to the ADD being left around and reselected, with the result being
6835     // two adds in the output.  Alas, even if none our users are stores, that
6836     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6837     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6838     // climbing the DAG back to the root, and it doesn't seem to be worth the
6839     // effort.
6840     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6841            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6842       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6843         goto default_case;
6844
6845     if (ConstantSDNode *C =
6846         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6847       // An add of one will be selected as an INC.
6848       if (C->getAPIntValue() == 1) {
6849         Opcode = X86ISD::INC;
6850         NumOperands = 1;
6851         break;
6852       }
6853
6854       // An add of negative one (subtract of one) will be selected as a DEC.
6855       if (C->getAPIntValue().isAllOnesValue()) {
6856         Opcode = X86ISD::DEC;
6857         NumOperands = 1;
6858         break;
6859       }
6860     }
6861
6862     // Otherwise use a regular EFLAGS-setting add.
6863     Opcode = X86ISD::ADD;
6864     NumOperands = 2;
6865     break;
6866   case ISD::AND: {
6867     // If the primary and result isn't used, don't bother using X86ISD::AND,
6868     // because a TEST instruction will be better.
6869     bool NonFlagUse = false;
6870     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6871            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6872       SDNode *User = *UI;
6873       unsigned UOpNo = UI.getOperandNo();
6874       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6875         // Look pass truncate.
6876         UOpNo = User->use_begin().getOperandNo();
6877         User = *User->use_begin();
6878       }
6879
6880       if (User->getOpcode() != ISD::BRCOND &&
6881           User->getOpcode() != ISD::SETCC &&
6882           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6883         NonFlagUse = true;
6884         break;
6885       }
6886     }
6887
6888     if (!NonFlagUse)
6889       break;
6890   }
6891     // FALL THROUGH
6892   case ISD::SUB:
6893   case ISD::OR:
6894   case ISD::XOR:
6895     // Due to the ISEL shortcoming noted above, be conservative if this op is
6896     // likely to be selected as part of a load-modify-store instruction.
6897     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6898            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6899       if (UI->getOpcode() == ISD::STORE)
6900         goto default_case;
6901
6902     // Otherwise use a regular EFLAGS-setting instruction.
6903     switch (Op.getNode()->getOpcode()) {
6904     default: llvm_unreachable("unexpected operator!");
6905     case ISD::SUB: Opcode = X86ISD::SUB; break;
6906     case ISD::OR:  Opcode = X86ISD::OR;  break;
6907     case ISD::XOR: Opcode = X86ISD::XOR; break;
6908     case ISD::AND: Opcode = X86ISD::AND; break;
6909     }
6910
6911     NumOperands = 2;
6912     break;
6913   case X86ISD::ADD:
6914   case X86ISD::SUB:
6915   case X86ISD::INC:
6916   case X86ISD::DEC:
6917   case X86ISD::OR:
6918   case X86ISD::XOR:
6919   case X86ISD::AND:
6920     return SDValue(Op.getNode(), 1);
6921   default:
6922   default_case:
6923     break;
6924   }
6925
6926   if (Opcode == 0)
6927     // Emit a CMP with 0, which is the TEST pattern.
6928     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6929                        DAG.getConstant(0, Op.getValueType()));
6930
6931   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6932   SmallVector<SDValue, 4> Ops;
6933   for (unsigned i = 0; i != NumOperands; ++i)
6934     Ops.push_back(Op.getOperand(i));
6935
6936   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6937   DAG.ReplaceAllUsesWith(Op, New);
6938   return SDValue(New.getNode(), 1);
6939 }
6940
6941 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6942 /// equivalent.
6943 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6944                                    SelectionDAG &DAG) const {
6945   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6946     if (C->getAPIntValue() == 0)
6947       return EmitTest(Op0, X86CC, DAG);
6948
6949   DebugLoc dl = Op0.getDebugLoc();
6950   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6951 }
6952
6953 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6954 /// if it's possible.
6955 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6956                                      DebugLoc dl, SelectionDAG &DAG) const {
6957   SDValue Op0 = And.getOperand(0);
6958   SDValue Op1 = And.getOperand(1);
6959   if (Op0.getOpcode() == ISD::TRUNCATE)
6960     Op0 = Op0.getOperand(0);
6961   if (Op1.getOpcode() == ISD::TRUNCATE)
6962     Op1 = Op1.getOperand(0);
6963
6964   SDValue LHS, RHS;
6965   if (Op1.getOpcode() == ISD::SHL)
6966     std::swap(Op0, Op1);
6967   if (Op0.getOpcode() == ISD::SHL) {
6968     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6969       if (And00C->getZExtValue() == 1) {
6970         // If we looked past a truncate, check that it's only truncating away
6971         // known zeros.
6972         unsigned BitWidth = Op0.getValueSizeInBits();
6973         unsigned AndBitWidth = And.getValueSizeInBits();
6974         if (BitWidth > AndBitWidth) {
6975           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6976           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6977           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6978             return SDValue();
6979         }
6980         LHS = Op1;
6981         RHS = Op0.getOperand(1);
6982       }
6983   } else if (Op1.getOpcode() == ISD::Constant) {
6984     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6985     SDValue AndLHS = Op0;
6986     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6987       LHS = AndLHS.getOperand(0);
6988       RHS = AndLHS.getOperand(1);
6989     }
6990   }
6991
6992   if (LHS.getNode()) {
6993     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6994     // instruction.  Since the shift amount is in-range-or-undefined, we know
6995     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6996     // the encoding for the i16 version is larger than the i32 version.
6997     // Also promote i16 to i32 for performance / code size reason.
6998     if (LHS.getValueType() == MVT::i8 ||
6999         LHS.getValueType() == MVT::i16)
7000       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7001
7002     // If the operand types disagree, extend the shift amount to match.  Since
7003     // BT ignores high bits (like shifts) we can use anyextend.
7004     if (LHS.getValueType() != RHS.getValueType())
7005       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7006
7007     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7008     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7009     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7010                        DAG.getConstant(Cond, MVT::i8), BT);
7011   }
7012
7013   return SDValue();
7014 }
7015
7016 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7017   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7018   SDValue Op0 = Op.getOperand(0);
7019   SDValue Op1 = Op.getOperand(1);
7020   DebugLoc dl = Op.getDebugLoc();
7021   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7022
7023   // Optimize to BT if possible.
7024   // Lower (X & (1 << N)) == 0 to BT(X, N).
7025   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7026   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7027   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7028       Op1.getOpcode() == ISD::Constant &&
7029       cast<ConstantSDNode>(Op1)->isNullValue() &&
7030       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7031     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7032     if (NewSetCC.getNode())
7033       return NewSetCC;
7034   }
7035
7036   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
7037   // these.
7038   if (Op1.getOpcode() == ISD::Constant &&
7039       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7040        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7041       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7042  
7043     // If the input is a setcc, then reuse the input setcc or use a new one with
7044     // the inverted condition.
7045     if (Op0.getOpcode() == X86ISD::SETCC) {
7046       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7047       bool Invert = (CC == ISD::SETNE) ^
7048         cast<ConstantSDNode>(Op1)->isNullValue();
7049       if (!Invert) return Op0;
7050       
7051       CCode = X86::GetOppositeBranchCondition(CCode);
7052       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7053                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7054     }
7055   }
7056
7057   bool isFP = Op1.getValueType().isFloatingPoint();
7058   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7059   if (X86CC == X86::COND_INVALID)
7060     return SDValue();
7061
7062   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7063   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7064                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7065 }
7066
7067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7068   SDValue Cond;
7069   SDValue Op0 = Op.getOperand(0);
7070   SDValue Op1 = Op.getOperand(1);
7071   SDValue CC = Op.getOperand(2);
7072   EVT VT = Op.getValueType();
7073   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7074   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7075   DebugLoc dl = Op.getDebugLoc();
7076
7077   if (isFP) {
7078     unsigned SSECC = 8;
7079     EVT VT0 = Op0.getValueType();
7080     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7081     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7082     bool Swap = false;
7083
7084     switch (SetCCOpcode) {
7085     default: break;
7086     case ISD::SETOEQ:
7087     case ISD::SETEQ:  SSECC = 0; break;
7088     case ISD::SETOGT:
7089     case ISD::SETGT: Swap = true; // Fallthrough
7090     case ISD::SETLT:
7091     case ISD::SETOLT: SSECC = 1; break;
7092     case ISD::SETOGE:
7093     case ISD::SETGE: Swap = true; // Fallthrough
7094     case ISD::SETLE:
7095     case ISD::SETOLE: SSECC = 2; break;
7096     case ISD::SETUO:  SSECC = 3; break;
7097     case ISD::SETUNE:
7098     case ISD::SETNE:  SSECC = 4; break;
7099     case ISD::SETULE: Swap = true;
7100     case ISD::SETUGE: SSECC = 5; break;
7101     case ISD::SETULT: Swap = true;
7102     case ISD::SETUGT: SSECC = 6; break;
7103     case ISD::SETO:   SSECC = 7; break;
7104     }
7105     if (Swap)
7106       std::swap(Op0, Op1);
7107
7108     // In the two special cases we can't handle, emit two comparisons.
7109     if (SSECC == 8) {
7110       if (SetCCOpcode == ISD::SETUEQ) {
7111         SDValue UNORD, EQ;
7112         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7113         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7114         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7115       }
7116       else if (SetCCOpcode == ISD::SETONE) {
7117         SDValue ORD, NEQ;
7118         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7119         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7120         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7121       }
7122       llvm_unreachable("Illegal FP comparison");
7123     }
7124     // Handle all other FP comparisons here.
7125     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7126   }
7127
7128   // We are handling one of the integer comparisons here.  Since SSE only has
7129   // GT and EQ comparisons for integer, swapping operands and multiple
7130   // operations may be required for some comparisons.
7131   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7132   bool Swap = false, Invert = false, FlipSigns = false;
7133
7134   switch (VT.getSimpleVT().SimpleTy) {
7135   default: break;
7136   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7137   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7138   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7139   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7140   }
7141
7142   switch (SetCCOpcode) {
7143   default: break;
7144   case ISD::SETNE:  Invert = true;
7145   case ISD::SETEQ:  Opc = EQOpc; break;
7146   case ISD::SETLT:  Swap = true;
7147   case ISD::SETGT:  Opc = GTOpc; break;
7148   case ISD::SETGE:  Swap = true;
7149   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7150   case ISD::SETULT: Swap = true;
7151   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7152   case ISD::SETUGE: Swap = true;
7153   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7154   }
7155   if (Swap)
7156     std::swap(Op0, Op1);
7157
7158   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7159   // bits of the inputs before performing those operations.
7160   if (FlipSigns) {
7161     EVT EltVT = VT.getVectorElementType();
7162     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7163                                       EltVT);
7164     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7165     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7166                                     SignBits.size());
7167     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7168     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7169   }
7170
7171   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7172
7173   // If the logical-not of the result is required, perform that now.
7174   if (Invert)
7175     Result = DAG.getNOT(dl, Result, VT);
7176
7177   return Result;
7178 }
7179
7180 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7181 static bool isX86LogicalCmp(SDValue Op) {
7182   unsigned Opc = Op.getNode()->getOpcode();
7183   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7184     return true;
7185   if (Op.getResNo() == 1 &&
7186       (Opc == X86ISD::ADD ||
7187        Opc == X86ISD::SUB ||
7188        Opc == X86ISD::ADC ||
7189        Opc == X86ISD::SBB ||
7190        Opc == X86ISD::SMUL ||
7191        Opc == X86ISD::UMUL ||
7192        Opc == X86ISD::INC ||
7193        Opc == X86ISD::DEC ||
7194        Opc == X86ISD::OR ||
7195        Opc == X86ISD::XOR ||
7196        Opc == X86ISD::AND))
7197     return true;
7198
7199   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7200     return true;
7201     
7202   return false;
7203 }
7204
7205 static bool isZero(SDValue V) {
7206   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7207   return C && C->isNullValue();
7208 }
7209
7210 static bool isAllOnes(SDValue V) {
7211   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7212   return C && C->isAllOnesValue();
7213 }
7214
7215 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7216   bool addTest = true;
7217   SDValue Cond  = Op.getOperand(0);
7218   SDValue Op1 = Op.getOperand(1);
7219   SDValue Op2 = Op.getOperand(2);
7220   DebugLoc DL = Op.getDebugLoc();
7221   SDValue CC;
7222
7223   if (Cond.getOpcode() == ISD::SETCC) {
7224     SDValue NewCond = LowerSETCC(Cond, DAG);
7225     if (NewCond.getNode())
7226       Cond = NewCond;
7227   }
7228
7229   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7230   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7231   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7232   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7233   if (Cond.getOpcode() == X86ISD::SETCC &&
7234       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7235       isZero(Cond.getOperand(1).getOperand(1))) {
7236     SDValue Cmp = Cond.getOperand(1);
7237     
7238     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7239     
7240     if ((isAllOnes(Op1) || isAllOnes(Op2)) && 
7241         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7242       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7243
7244       SDValue CmpOp0 = Cmp.getOperand(0);
7245       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7246                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7247       
7248       SDValue Res =   // Res = 0 or -1.
7249         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7250                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7251       
7252       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7253         Res = DAG.getNOT(DL, Res, Res.getValueType());
7254       
7255       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7256       if (N2C == 0 || !N2C->isNullValue())
7257         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7258       return Res;
7259     }
7260   }
7261
7262   // Look past (and (setcc_carry (cmp ...)), 1).
7263   if (Cond.getOpcode() == ISD::AND &&
7264       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7265     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7266     if (C && C->getAPIntValue() == 1)
7267       Cond = Cond.getOperand(0);
7268   }
7269
7270   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7271   // setting operand in place of the X86ISD::SETCC.
7272   if (Cond.getOpcode() == X86ISD::SETCC ||
7273       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7274     CC = Cond.getOperand(0);
7275
7276     SDValue Cmp = Cond.getOperand(1);
7277     unsigned Opc = Cmp.getOpcode();
7278     EVT VT = Op.getValueType();
7279
7280     bool IllegalFPCMov = false;
7281     if (VT.isFloatingPoint() && !VT.isVector() &&
7282         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7283       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7284
7285     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7286         Opc == X86ISD::BT) { // FIXME
7287       Cond = Cmp;
7288       addTest = false;
7289     }
7290   }
7291
7292   if (addTest) {
7293     // Look pass the truncate.
7294     if (Cond.getOpcode() == ISD::TRUNCATE)
7295       Cond = Cond.getOperand(0);
7296
7297     // We know the result of AND is compared against zero. Try to match
7298     // it to BT.
7299     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7300       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7301       if (NewSetCC.getNode()) {
7302         CC = NewSetCC.getOperand(0);
7303         Cond = NewSetCC.getOperand(1);
7304         addTest = false;
7305       }
7306     }
7307   }
7308
7309   if (addTest) {
7310     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7311     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7312   }
7313
7314   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7315   // condition is true.
7316   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
7317   SDValue Ops[] = { Op2, Op1, CC, Cond };
7318   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7319 }
7320
7321 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7322 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7323 // from the AND / OR.
7324 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7325   Opc = Op.getOpcode();
7326   if (Opc != ISD::OR && Opc != ISD::AND)
7327     return false;
7328   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7329           Op.getOperand(0).hasOneUse() &&
7330           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7331           Op.getOperand(1).hasOneUse());
7332 }
7333
7334 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7335 // 1 and that the SETCC node has a single use.
7336 static bool isXor1OfSetCC(SDValue Op) {
7337   if (Op.getOpcode() != ISD::XOR)
7338     return false;
7339   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7340   if (N1C && N1C->getAPIntValue() == 1) {
7341     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7342       Op.getOperand(0).hasOneUse();
7343   }
7344   return false;
7345 }
7346
7347 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7348   bool addTest = true;
7349   SDValue Chain = Op.getOperand(0);
7350   SDValue Cond  = Op.getOperand(1);
7351   SDValue Dest  = Op.getOperand(2);
7352   DebugLoc dl = Op.getDebugLoc();
7353   SDValue CC;
7354
7355   if (Cond.getOpcode() == ISD::SETCC) {
7356     SDValue NewCond = LowerSETCC(Cond, DAG);
7357     if (NewCond.getNode())
7358       Cond = NewCond;
7359   }
7360 #if 0
7361   // FIXME: LowerXALUO doesn't handle these!!
7362   else if (Cond.getOpcode() == X86ISD::ADD  ||
7363            Cond.getOpcode() == X86ISD::SUB  ||
7364            Cond.getOpcode() == X86ISD::SMUL ||
7365            Cond.getOpcode() == X86ISD::UMUL)
7366     Cond = LowerXALUO(Cond, DAG);
7367 #endif
7368
7369   // Look pass (and (setcc_carry (cmp ...)), 1).
7370   if (Cond.getOpcode() == ISD::AND &&
7371       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7372     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7373     if (C && C->getAPIntValue() == 1)
7374       Cond = Cond.getOperand(0);
7375   }
7376
7377   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7378   // setting operand in place of the X86ISD::SETCC.
7379   if (Cond.getOpcode() == X86ISD::SETCC ||
7380       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7381     CC = Cond.getOperand(0);
7382
7383     SDValue Cmp = Cond.getOperand(1);
7384     unsigned Opc = Cmp.getOpcode();
7385     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7386     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7387       Cond = Cmp;
7388       addTest = false;
7389     } else {
7390       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7391       default: break;
7392       case X86::COND_O:
7393       case X86::COND_B:
7394         // These can only come from an arithmetic instruction with overflow,
7395         // e.g. SADDO, UADDO.
7396         Cond = Cond.getNode()->getOperand(1);
7397         addTest = false;
7398         break;
7399       }
7400     }
7401   } else {
7402     unsigned CondOpc;
7403     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7404       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7405       if (CondOpc == ISD::OR) {
7406         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7407         // two branches instead of an explicit OR instruction with a
7408         // separate test.
7409         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7410             isX86LogicalCmp(Cmp)) {
7411           CC = Cond.getOperand(0).getOperand(0);
7412           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7413                               Chain, Dest, CC, Cmp);
7414           CC = Cond.getOperand(1).getOperand(0);
7415           Cond = Cmp;
7416           addTest = false;
7417         }
7418       } else { // ISD::AND
7419         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7420         // two branches instead of an explicit AND instruction with a
7421         // separate test. However, we only do this if this block doesn't
7422         // have a fall-through edge, because this requires an explicit
7423         // jmp when the condition is false.
7424         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7425             isX86LogicalCmp(Cmp) &&
7426             Op.getNode()->hasOneUse()) {
7427           X86::CondCode CCode =
7428             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7429           CCode = X86::GetOppositeBranchCondition(CCode);
7430           CC = DAG.getConstant(CCode, MVT::i8);
7431           SDNode *User = *Op.getNode()->use_begin();
7432           // Look for an unconditional branch following this conditional branch.
7433           // We need this because we need to reverse the successors in order
7434           // to implement FCMP_OEQ.
7435           if (User->getOpcode() == ISD::BR) {
7436             SDValue FalseBB = User->getOperand(1);
7437             SDNode *NewBR =
7438               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7439             assert(NewBR == User);
7440             (void)NewBR;
7441             Dest = FalseBB;
7442
7443             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7444                                 Chain, Dest, CC, Cmp);
7445             X86::CondCode CCode =
7446               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7447             CCode = X86::GetOppositeBranchCondition(CCode);
7448             CC = DAG.getConstant(CCode, MVT::i8);
7449             Cond = Cmp;
7450             addTest = false;
7451           }
7452         }
7453       }
7454     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7455       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7456       // It should be transformed during dag combiner except when the condition
7457       // is set by a arithmetics with overflow node.
7458       X86::CondCode CCode =
7459         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7460       CCode = X86::GetOppositeBranchCondition(CCode);
7461       CC = DAG.getConstant(CCode, MVT::i8);
7462       Cond = Cond.getOperand(0).getOperand(1);
7463       addTest = false;
7464     }
7465   }
7466
7467   if (addTest) {
7468     // Look pass the truncate.
7469     if (Cond.getOpcode() == ISD::TRUNCATE)
7470       Cond = Cond.getOperand(0);
7471
7472     // We know the result of AND is compared against zero. Try to match
7473     // it to BT.
7474     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7475       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7476       if (NewSetCC.getNode()) {
7477         CC = NewSetCC.getOperand(0);
7478         Cond = NewSetCC.getOperand(1);
7479         addTest = false;
7480       }
7481     }
7482   }
7483
7484   if (addTest) {
7485     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7486     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7487   }
7488   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7489                      Chain, Dest, CC, Cond);
7490 }
7491
7492
7493 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7494 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7495 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7496 // that the guard pages used by the OS virtual memory manager are allocated in
7497 // correct sequence.
7498 SDValue
7499 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7500                                            SelectionDAG &DAG) const {
7501   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7502          "This should be used only on Windows targets");
7503   DebugLoc dl = Op.getDebugLoc();
7504
7505   // Get the inputs.
7506   SDValue Chain = Op.getOperand(0);
7507   SDValue Size  = Op.getOperand(1);
7508   // FIXME: Ensure alignment here
7509
7510   SDValue Flag;
7511
7512   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7513
7514   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7515   Flag = Chain.getValue(1);
7516
7517   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7518
7519   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7520   Flag = Chain.getValue(1);
7521
7522   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7523
7524   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7525   return DAG.getMergeValues(Ops1, 2, dl);
7526 }
7527
7528 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7529   MachineFunction &MF = DAG.getMachineFunction();
7530   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7531
7532   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7533   DebugLoc DL = Op.getDebugLoc();
7534
7535   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7536     // vastart just stores the address of the VarArgsFrameIndex slot into the
7537     // memory location argument.
7538     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7539                                    getPointerTy());
7540     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7541                         MachinePointerInfo(SV), false, false, 0);
7542   }
7543
7544   // __va_list_tag:
7545   //   gp_offset         (0 - 6 * 8)
7546   //   fp_offset         (48 - 48 + 8 * 16)
7547   //   overflow_arg_area (point to parameters coming in memory).
7548   //   reg_save_area
7549   SmallVector<SDValue, 8> MemOps;
7550   SDValue FIN = Op.getOperand(1);
7551   // Store gp_offset
7552   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7553                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7554                                                MVT::i32),
7555                                FIN, MachinePointerInfo(SV), false, false, 0);
7556   MemOps.push_back(Store);
7557
7558   // Store fp_offset
7559   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7560                     FIN, DAG.getIntPtrConstant(4));
7561   Store = DAG.getStore(Op.getOperand(0), DL,
7562                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7563                                        MVT::i32),
7564                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7565   MemOps.push_back(Store);
7566
7567   // Store ptr to overflow_arg_area
7568   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7569                     FIN, DAG.getIntPtrConstant(4));
7570   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7571                                     getPointerTy());
7572   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7573                        MachinePointerInfo(SV, 8),
7574                        false, false, 0);
7575   MemOps.push_back(Store);
7576
7577   // Store ptr to reg_save_area.
7578   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7579                     FIN, DAG.getIntPtrConstant(8));
7580   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7581                                     getPointerTy());
7582   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7583                        MachinePointerInfo(SV, 16), false, false, 0);
7584   MemOps.push_back(Store);
7585   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7586                      &MemOps[0], MemOps.size());
7587 }
7588
7589 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7590   assert(Subtarget->is64Bit() &&
7591          "LowerVAARG only handles 64-bit va_arg!");
7592   assert((Subtarget->isTargetLinux() ||
7593           Subtarget->isTargetDarwin()) &&
7594           "Unhandled target in LowerVAARG");
7595   assert(Op.getNode()->getNumOperands() == 4);
7596   SDValue Chain = Op.getOperand(0);
7597   SDValue SrcPtr = Op.getOperand(1);
7598   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7599   unsigned Align = Op.getConstantOperandVal(3);
7600   DebugLoc dl = Op.getDebugLoc();
7601
7602   EVT ArgVT = Op.getNode()->getValueType(0);
7603   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7604   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7605   uint8_t ArgMode;
7606
7607   // Decide which area this value should be read from.
7608   // TODO: Implement the AMD64 ABI in its entirety. This simple
7609   // selection mechanism works only for the basic types.
7610   if (ArgVT == MVT::f80) {
7611     llvm_unreachable("va_arg for f80 not yet implemented");
7612   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7613     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7614   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7615     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7616   } else {
7617     llvm_unreachable("Unhandled argument type in LowerVAARG");
7618   }
7619
7620   if (ArgMode == 2) {
7621     // Sanity Check: Make sure using fp_offset makes sense.
7622     assert(!UseSoftFloat &&
7623            !(DAG.getMachineFunction()
7624                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7625            Subtarget->hasXMM());
7626   }
7627
7628   // Insert VAARG_64 node into the DAG
7629   // VAARG_64 returns two values: Variable Argument Address, Chain
7630   SmallVector<SDValue, 11> InstOps;
7631   InstOps.push_back(Chain);
7632   InstOps.push_back(SrcPtr);
7633   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7634   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7635   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7636   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7637   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7638                                           VTs, &InstOps[0], InstOps.size(),
7639                                           MVT::i64,
7640                                           MachinePointerInfo(SV),
7641                                           /*Align=*/0,
7642                                           /*Volatile=*/false,
7643                                           /*ReadMem=*/true,
7644                                           /*WriteMem=*/true);
7645   Chain = VAARG.getValue(1);
7646
7647   // Load the next argument and return it
7648   return DAG.getLoad(ArgVT, dl,
7649                      Chain,
7650                      VAARG,
7651                      MachinePointerInfo(),
7652                      false, false, 0);
7653 }
7654
7655 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7656   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7657   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7658   SDValue Chain = Op.getOperand(0);
7659   SDValue DstPtr = Op.getOperand(1);
7660   SDValue SrcPtr = Op.getOperand(2);
7661   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7662   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7663   DebugLoc DL = Op.getDebugLoc();
7664
7665   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7666                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7667                        false,
7668                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7669 }
7670
7671 SDValue
7672 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7673   DebugLoc dl = Op.getDebugLoc();
7674   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7675   switch (IntNo) {
7676   default: return SDValue();    // Don't custom lower most intrinsics.
7677   // Comparison intrinsics.
7678   case Intrinsic::x86_sse_comieq_ss:
7679   case Intrinsic::x86_sse_comilt_ss:
7680   case Intrinsic::x86_sse_comile_ss:
7681   case Intrinsic::x86_sse_comigt_ss:
7682   case Intrinsic::x86_sse_comige_ss:
7683   case Intrinsic::x86_sse_comineq_ss:
7684   case Intrinsic::x86_sse_ucomieq_ss:
7685   case Intrinsic::x86_sse_ucomilt_ss:
7686   case Intrinsic::x86_sse_ucomile_ss:
7687   case Intrinsic::x86_sse_ucomigt_ss:
7688   case Intrinsic::x86_sse_ucomige_ss:
7689   case Intrinsic::x86_sse_ucomineq_ss:
7690   case Intrinsic::x86_sse2_comieq_sd:
7691   case Intrinsic::x86_sse2_comilt_sd:
7692   case Intrinsic::x86_sse2_comile_sd:
7693   case Intrinsic::x86_sse2_comigt_sd:
7694   case Intrinsic::x86_sse2_comige_sd:
7695   case Intrinsic::x86_sse2_comineq_sd:
7696   case Intrinsic::x86_sse2_ucomieq_sd:
7697   case Intrinsic::x86_sse2_ucomilt_sd:
7698   case Intrinsic::x86_sse2_ucomile_sd:
7699   case Intrinsic::x86_sse2_ucomigt_sd:
7700   case Intrinsic::x86_sse2_ucomige_sd:
7701   case Intrinsic::x86_sse2_ucomineq_sd: {
7702     unsigned Opc = 0;
7703     ISD::CondCode CC = ISD::SETCC_INVALID;
7704     switch (IntNo) {
7705     default: break;
7706     case Intrinsic::x86_sse_comieq_ss:
7707     case Intrinsic::x86_sse2_comieq_sd:
7708       Opc = X86ISD::COMI;
7709       CC = ISD::SETEQ;
7710       break;
7711     case Intrinsic::x86_sse_comilt_ss:
7712     case Intrinsic::x86_sse2_comilt_sd:
7713       Opc = X86ISD::COMI;
7714       CC = ISD::SETLT;
7715       break;
7716     case Intrinsic::x86_sse_comile_ss:
7717     case Intrinsic::x86_sse2_comile_sd:
7718       Opc = X86ISD::COMI;
7719       CC = ISD::SETLE;
7720       break;
7721     case Intrinsic::x86_sse_comigt_ss:
7722     case Intrinsic::x86_sse2_comigt_sd:
7723       Opc = X86ISD::COMI;
7724       CC = ISD::SETGT;
7725       break;
7726     case Intrinsic::x86_sse_comige_ss:
7727     case Intrinsic::x86_sse2_comige_sd:
7728       Opc = X86ISD::COMI;
7729       CC = ISD::SETGE;
7730       break;
7731     case Intrinsic::x86_sse_comineq_ss:
7732     case Intrinsic::x86_sse2_comineq_sd:
7733       Opc = X86ISD::COMI;
7734       CC = ISD::SETNE;
7735       break;
7736     case Intrinsic::x86_sse_ucomieq_ss:
7737     case Intrinsic::x86_sse2_ucomieq_sd:
7738       Opc = X86ISD::UCOMI;
7739       CC = ISD::SETEQ;
7740       break;
7741     case Intrinsic::x86_sse_ucomilt_ss:
7742     case Intrinsic::x86_sse2_ucomilt_sd:
7743       Opc = X86ISD::UCOMI;
7744       CC = ISD::SETLT;
7745       break;
7746     case Intrinsic::x86_sse_ucomile_ss:
7747     case Intrinsic::x86_sse2_ucomile_sd:
7748       Opc = X86ISD::UCOMI;
7749       CC = ISD::SETLE;
7750       break;
7751     case Intrinsic::x86_sse_ucomigt_ss:
7752     case Intrinsic::x86_sse2_ucomigt_sd:
7753       Opc = X86ISD::UCOMI;
7754       CC = ISD::SETGT;
7755       break;
7756     case Intrinsic::x86_sse_ucomige_ss:
7757     case Intrinsic::x86_sse2_ucomige_sd:
7758       Opc = X86ISD::UCOMI;
7759       CC = ISD::SETGE;
7760       break;
7761     case Intrinsic::x86_sse_ucomineq_ss:
7762     case Intrinsic::x86_sse2_ucomineq_sd:
7763       Opc = X86ISD::UCOMI;
7764       CC = ISD::SETNE;
7765       break;
7766     }
7767
7768     SDValue LHS = Op.getOperand(1);
7769     SDValue RHS = Op.getOperand(2);
7770     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7771     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7772     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7773     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7774                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7775     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7776   }
7777   // ptest and testp intrinsics. The intrinsic these come from are designed to
7778   // return an integer value, not just an instruction so lower it to the ptest
7779   // or testp pattern and a setcc for the result.
7780   case Intrinsic::x86_sse41_ptestz:
7781   case Intrinsic::x86_sse41_ptestc:
7782   case Intrinsic::x86_sse41_ptestnzc:
7783   case Intrinsic::x86_avx_ptestz_256:
7784   case Intrinsic::x86_avx_ptestc_256:
7785   case Intrinsic::x86_avx_ptestnzc_256:
7786   case Intrinsic::x86_avx_vtestz_ps:
7787   case Intrinsic::x86_avx_vtestc_ps:
7788   case Intrinsic::x86_avx_vtestnzc_ps:
7789   case Intrinsic::x86_avx_vtestz_pd:
7790   case Intrinsic::x86_avx_vtestc_pd:
7791   case Intrinsic::x86_avx_vtestnzc_pd:
7792   case Intrinsic::x86_avx_vtestz_ps_256:
7793   case Intrinsic::x86_avx_vtestc_ps_256:
7794   case Intrinsic::x86_avx_vtestnzc_ps_256:
7795   case Intrinsic::x86_avx_vtestz_pd_256:
7796   case Intrinsic::x86_avx_vtestc_pd_256:
7797   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7798     bool IsTestPacked = false;
7799     unsigned X86CC = 0;
7800     switch (IntNo) {
7801     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7802     case Intrinsic::x86_avx_vtestz_ps:
7803     case Intrinsic::x86_avx_vtestz_pd:
7804     case Intrinsic::x86_avx_vtestz_ps_256:
7805     case Intrinsic::x86_avx_vtestz_pd_256:
7806       IsTestPacked = true; // Fallthrough
7807     case Intrinsic::x86_sse41_ptestz:
7808     case Intrinsic::x86_avx_ptestz_256:
7809       // ZF = 1
7810       X86CC = X86::COND_E;
7811       break;
7812     case Intrinsic::x86_avx_vtestc_ps:
7813     case Intrinsic::x86_avx_vtestc_pd:
7814     case Intrinsic::x86_avx_vtestc_ps_256:
7815     case Intrinsic::x86_avx_vtestc_pd_256:
7816       IsTestPacked = true; // Fallthrough
7817     case Intrinsic::x86_sse41_ptestc:
7818     case Intrinsic::x86_avx_ptestc_256:
7819       // CF = 1
7820       X86CC = X86::COND_B;
7821       break;
7822     case Intrinsic::x86_avx_vtestnzc_ps:
7823     case Intrinsic::x86_avx_vtestnzc_pd:
7824     case Intrinsic::x86_avx_vtestnzc_ps_256:
7825     case Intrinsic::x86_avx_vtestnzc_pd_256:
7826       IsTestPacked = true; // Fallthrough
7827     case Intrinsic::x86_sse41_ptestnzc:
7828     case Intrinsic::x86_avx_ptestnzc_256:
7829       // ZF and CF = 0
7830       X86CC = X86::COND_A;
7831       break;
7832     }
7833
7834     SDValue LHS = Op.getOperand(1);
7835     SDValue RHS = Op.getOperand(2);
7836     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7837     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7838     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7839     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7840     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7841   }
7842
7843   // Fix vector shift instructions where the last operand is a non-immediate
7844   // i32 value.
7845   case Intrinsic::x86_sse2_pslli_w:
7846   case Intrinsic::x86_sse2_pslli_d:
7847   case Intrinsic::x86_sse2_pslli_q:
7848   case Intrinsic::x86_sse2_psrli_w:
7849   case Intrinsic::x86_sse2_psrli_d:
7850   case Intrinsic::x86_sse2_psrli_q:
7851   case Intrinsic::x86_sse2_psrai_w:
7852   case Intrinsic::x86_sse2_psrai_d:
7853   case Intrinsic::x86_mmx_pslli_w:
7854   case Intrinsic::x86_mmx_pslli_d:
7855   case Intrinsic::x86_mmx_pslli_q:
7856   case Intrinsic::x86_mmx_psrli_w:
7857   case Intrinsic::x86_mmx_psrli_d:
7858   case Intrinsic::x86_mmx_psrli_q:
7859   case Intrinsic::x86_mmx_psrai_w:
7860   case Intrinsic::x86_mmx_psrai_d: {
7861     SDValue ShAmt = Op.getOperand(2);
7862     if (isa<ConstantSDNode>(ShAmt))
7863       return SDValue();
7864
7865     unsigned NewIntNo = 0;
7866     EVT ShAmtVT = MVT::v4i32;
7867     switch (IntNo) {
7868     case Intrinsic::x86_sse2_pslli_w:
7869       NewIntNo = Intrinsic::x86_sse2_psll_w;
7870       break;
7871     case Intrinsic::x86_sse2_pslli_d:
7872       NewIntNo = Intrinsic::x86_sse2_psll_d;
7873       break;
7874     case Intrinsic::x86_sse2_pslli_q:
7875       NewIntNo = Intrinsic::x86_sse2_psll_q;
7876       break;
7877     case Intrinsic::x86_sse2_psrli_w:
7878       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7879       break;
7880     case Intrinsic::x86_sse2_psrli_d:
7881       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7882       break;
7883     case Intrinsic::x86_sse2_psrli_q:
7884       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7885       break;
7886     case Intrinsic::x86_sse2_psrai_w:
7887       NewIntNo = Intrinsic::x86_sse2_psra_w;
7888       break;
7889     case Intrinsic::x86_sse2_psrai_d:
7890       NewIntNo = Intrinsic::x86_sse2_psra_d;
7891       break;
7892     default: {
7893       ShAmtVT = MVT::v2i32;
7894       switch (IntNo) {
7895       case Intrinsic::x86_mmx_pslli_w:
7896         NewIntNo = Intrinsic::x86_mmx_psll_w;
7897         break;
7898       case Intrinsic::x86_mmx_pslli_d:
7899         NewIntNo = Intrinsic::x86_mmx_psll_d;
7900         break;
7901       case Intrinsic::x86_mmx_pslli_q:
7902         NewIntNo = Intrinsic::x86_mmx_psll_q;
7903         break;
7904       case Intrinsic::x86_mmx_psrli_w:
7905         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7906         break;
7907       case Intrinsic::x86_mmx_psrli_d:
7908         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7909         break;
7910       case Intrinsic::x86_mmx_psrli_q:
7911         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7912         break;
7913       case Intrinsic::x86_mmx_psrai_w:
7914         NewIntNo = Intrinsic::x86_mmx_psra_w;
7915         break;
7916       case Intrinsic::x86_mmx_psrai_d:
7917         NewIntNo = Intrinsic::x86_mmx_psra_d;
7918         break;
7919       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7920       }
7921       break;
7922     }
7923     }
7924
7925     // The vector shift intrinsics with scalars uses 32b shift amounts but
7926     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7927     // to be zero.
7928     SDValue ShOps[4];
7929     ShOps[0] = ShAmt;
7930     ShOps[1] = DAG.getConstant(0, MVT::i32);
7931     if (ShAmtVT == MVT::v4i32) {
7932       ShOps[2] = DAG.getUNDEF(MVT::i32);
7933       ShOps[3] = DAG.getUNDEF(MVT::i32);
7934       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7935     } else {
7936       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7937 // FIXME this must be lowered to get rid of the invalid type.
7938     }
7939
7940     EVT VT = Op.getValueType();
7941     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7942     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7943                        DAG.getConstant(NewIntNo, MVT::i32),
7944                        Op.getOperand(1), ShAmt);
7945   }
7946   }
7947 }
7948
7949 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7950                                            SelectionDAG &DAG) const {
7951   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7952   MFI->setReturnAddressIsTaken(true);
7953
7954   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7955   DebugLoc dl = Op.getDebugLoc();
7956
7957   if (Depth > 0) {
7958     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7959     SDValue Offset =
7960       DAG.getConstant(TD->getPointerSize(),
7961                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7962     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7963                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7964                                    FrameAddr, Offset),
7965                        MachinePointerInfo(), false, false, 0);
7966   }
7967
7968   // Just load the return address.
7969   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7970   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7971                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7972 }
7973
7974 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7975   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7976   MFI->setFrameAddressIsTaken(true);
7977
7978   EVT VT = Op.getValueType();
7979   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7980   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7981   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7982   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7983   while (Depth--)
7984     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7985                             MachinePointerInfo(),
7986                             false, false, 0);
7987   return FrameAddr;
7988 }
7989
7990 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7991                                                      SelectionDAG &DAG) const {
7992   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7993 }
7994
7995 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7996   MachineFunction &MF = DAG.getMachineFunction();
7997   SDValue Chain     = Op.getOperand(0);
7998   SDValue Offset    = Op.getOperand(1);
7999   SDValue Handler   = Op.getOperand(2);
8000   DebugLoc dl       = Op.getDebugLoc();
8001
8002   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8003                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8004                                      getPointerTy());
8005   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8006
8007   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8008                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8009   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8010   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8011                        false, false, 0);
8012   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8013   MF.getRegInfo().addLiveOut(StoreAddrReg);
8014
8015   return DAG.getNode(X86ISD::EH_RETURN, dl,
8016                      MVT::Other,
8017                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8018 }
8019
8020 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8021                                              SelectionDAG &DAG) const {
8022   SDValue Root = Op.getOperand(0);
8023   SDValue Trmp = Op.getOperand(1); // trampoline
8024   SDValue FPtr = Op.getOperand(2); // nested function
8025   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8026   DebugLoc dl  = Op.getDebugLoc();
8027
8028   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8029
8030   if (Subtarget->is64Bit()) {
8031     SDValue OutChains[6];
8032
8033     // Large code-model.
8034     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8035     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8036
8037     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8038     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8039
8040     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8041
8042     // Load the pointer to the nested function into R11.
8043     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8044     SDValue Addr = Trmp;
8045     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8046                                 Addr, MachinePointerInfo(TrmpAddr),
8047                                 false, false, 0);
8048
8049     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8050                        DAG.getConstant(2, MVT::i64));
8051     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8052                                 MachinePointerInfo(TrmpAddr, 2),
8053                                 false, false, 2);
8054
8055     // Load the 'nest' parameter value into R10.
8056     // R10 is specified in X86CallingConv.td
8057     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8058     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8059                        DAG.getConstant(10, MVT::i64));
8060     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8061                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8062                                 false, false, 0);
8063
8064     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8065                        DAG.getConstant(12, MVT::i64));
8066     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8067                                 MachinePointerInfo(TrmpAddr, 12),
8068                                 false, false, 2);
8069
8070     // Jump to the nested function.
8071     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8072     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8073                        DAG.getConstant(20, MVT::i64));
8074     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8075                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8076                                 false, false, 0);
8077
8078     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8079     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8080                        DAG.getConstant(22, MVT::i64));
8081     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8082                                 MachinePointerInfo(TrmpAddr, 22),
8083                                 false, false, 0);
8084
8085     SDValue Ops[] =
8086       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8087     return DAG.getMergeValues(Ops, 2, dl);
8088   } else {
8089     const Function *Func =
8090       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8091     CallingConv::ID CC = Func->getCallingConv();
8092     unsigned NestReg;
8093
8094     switch (CC) {
8095     default:
8096       llvm_unreachable("Unsupported calling convention");
8097     case CallingConv::C:
8098     case CallingConv::X86_StdCall: {
8099       // Pass 'nest' parameter in ECX.
8100       // Must be kept in sync with X86CallingConv.td
8101       NestReg = X86::ECX;
8102
8103       // Check that ECX wasn't needed by an 'inreg' parameter.
8104       const FunctionType *FTy = Func->getFunctionType();
8105       const AttrListPtr &Attrs = Func->getAttributes();
8106
8107       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8108         unsigned InRegCount = 0;
8109         unsigned Idx = 1;
8110
8111         for (FunctionType::param_iterator I = FTy->param_begin(),
8112              E = FTy->param_end(); I != E; ++I, ++Idx)
8113           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8114             // FIXME: should only count parameters that are lowered to integers.
8115             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8116
8117         if (InRegCount > 2) {
8118           report_fatal_error("Nest register in use - reduce number of inreg"
8119                              " parameters!");
8120         }
8121       }
8122       break;
8123     }
8124     case CallingConv::X86_FastCall:
8125     case CallingConv::X86_ThisCall:
8126     case CallingConv::Fast:
8127       // Pass 'nest' parameter in EAX.
8128       // Must be kept in sync with X86CallingConv.td
8129       NestReg = X86::EAX;
8130       break;
8131     }
8132
8133     SDValue OutChains[4];
8134     SDValue Addr, Disp;
8135
8136     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8137                        DAG.getConstant(10, MVT::i32));
8138     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8139
8140     // This is storing the opcode for MOV32ri.
8141     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8142     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8143     OutChains[0] = DAG.getStore(Root, dl,
8144                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8145                                 Trmp, MachinePointerInfo(TrmpAddr),
8146                                 false, false, 0);
8147
8148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8149                        DAG.getConstant(1, MVT::i32));
8150     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8151                                 MachinePointerInfo(TrmpAddr, 1),
8152                                 false, false, 1);
8153
8154     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8155     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8156                        DAG.getConstant(5, MVT::i32));
8157     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8158                                 MachinePointerInfo(TrmpAddr, 5),
8159                                 false, false, 1);
8160
8161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8162                        DAG.getConstant(6, MVT::i32));
8163     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8164                                 MachinePointerInfo(TrmpAddr, 6),
8165                                 false, false, 1);
8166
8167     SDValue Ops[] =
8168       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8169     return DAG.getMergeValues(Ops, 2, dl);
8170   }
8171 }
8172
8173 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8174                                             SelectionDAG &DAG) const {
8175   /*
8176    The rounding mode is in bits 11:10 of FPSR, and has the following
8177    settings:
8178      00 Round to nearest
8179      01 Round to -inf
8180      10 Round to +inf
8181      11 Round to 0
8182
8183   FLT_ROUNDS, on the other hand, expects the following:
8184     -1 Undefined
8185      0 Round to 0
8186      1 Round to nearest
8187      2 Round to +inf
8188      3 Round to -inf
8189
8190   To perform the conversion, we do:
8191     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8192   */
8193
8194   MachineFunction &MF = DAG.getMachineFunction();
8195   const TargetMachine &TM = MF.getTarget();
8196   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8197   unsigned StackAlignment = TFI.getStackAlignment();
8198   EVT VT = Op.getValueType();
8199   DebugLoc DL = Op.getDebugLoc();
8200
8201   // Save FP Control Word to stack slot
8202   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8203   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8204
8205
8206   MachineMemOperand *MMO =
8207    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8208                            MachineMemOperand::MOStore, 2, 2);
8209
8210   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8211   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8212                                           DAG.getVTList(MVT::Other),
8213                                           Ops, 2, MVT::i16, MMO);
8214
8215   // Load FP Control Word from stack slot
8216   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8217                             MachinePointerInfo(), false, false, 0);
8218
8219   // Transform as necessary
8220   SDValue CWD1 =
8221     DAG.getNode(ISD::SRL, DL, MVT::i16,
8222                 DAG.getNode(ISD::AND, DL, MVT::i16,
8223                             CWD, DAG.getConstant(0x800, MVT::i16)),
8224                 DAG.getConstant(11, MVT::i8));
8225   SDValue CWD2 =
8226     DAG.getNode(ISD::SRL, DL, MVT::i16,
8227                 DAG.getNode(ISD::AND, DL, MVT::i16,
8228                             CWD, DAG.getConstant(0x400, MVT::i16)),
8229                 DAG.getConstant(9, MVT::i8));
8230
8231   SDValue RetVal =
8232     DAG.getNode(ISD::AND, DL, MVT::i16,
8233                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8234                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8235                             DAG.getConstant(1, MVT::i16)),
8236                 DAG.getConstant(3, MVT::i16));
8237
8238
8239   return DAG.getNode((VT.getSizeInBits() < 16 ?
8240                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8241 }
8242
8243 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8244   EVT VT = Op.getValueType();
8245   EVT OpVT = VT;
8246   unsigned NumBits = VT.getSizeInBits();
8247   DebugLoc dl = Op.getDebugLoc();
8248
8249   Op = Op.getOperand(0);
8250   if (VT == MVT::i8) {
8251     // Zero extend to i32 since there is not an i8 bsr.
8252     OpVT = MVT::i32;
8253     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8254   }
8255
8256   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8257   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8258   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8259
8260   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8261   SDValue Ops[] = {
8262     Op,
8263     DAG.getConstant(NumBits+NumBits-1, OpVT),
8264     DAG.getConstant(X86::COND_E, MVT::i8),
8265     Op.getValue(1)
8266   };
8267   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8268
8269   // Finally xor with NumBits-1.
8270   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8271
8272   if (VT == MVT::i8)
8273     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8274   return Op;
8275 }
8276
8277 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8278   EVT VT = Op.getValueType();
8279   EVT OpVT = VT;
8280   unsigned NumBits = VT.getSizeInBits();
8281   DebugLoc dl = Op.getDebugLoc();
8282
8283   Op = Op.getOperand(0);
8284   if (VT == MVT::i8) {
8285     OpVT = MVT::i32;
8286     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8287   }
8288
8289   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8290   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8291   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8292
8293   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8294   SDValue Ops[] = {
8295     Op,
8296     DAG.getConstant(NumBits, OpVT),
8297     DAG.getConstant(X86::COND_E, MVT::i8),
8298     Op.getValue(1)
8299   };
8300   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8301
8302   if (VT == MVT::i8)
8303     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8304   return Op;
8305 }
8306
8307 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8308   EVT VT = Op.getValueType();
8309   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8310   DebugLoc dl = Op.getDebugLoc();
8311
8312   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8313   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8314   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8315   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8316   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8317   //
8318   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8319   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8320   //  return AloBlo + AloBhi + AhiBlo;
8321
8322   SDValue A = Op.getOperand(0);
8323   SDValue B = Op.getOperand(1);
8324
8325   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8326                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8327                        A, DAG.getConstant(32, MVT::i32));
8328   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8329                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8330                        B, DAG.getConstant(32, MVT::i32));
8331   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8332                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8333                        A, B);
8334   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8335                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8336                        A, Bhi);
8337   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8338                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8339                        Ahi, B);
8340   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8342                        AloBhi, DAG.getConstant(32, MVT::i32));
8343   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8344                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8345                        AhiBlo, DAG.getConstant(32, MVT::i32));
8346   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8347   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8348   return Res;
8349 }
8350
8351 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8352   EVT VT = Op.getValueType();
8353   DebugLoc dl = Op.getDebugLoc();
8354   SDValue R = Op.getOperand(0);
8355
8356   LLVMContext *Context = DAG.getContext();
8357
8358   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8359
8360   if (VT == MVT::v4i32) {
8361     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8362                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8363                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8364
8365     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8366
8367     std::vector<Constant*> CV(4, CI);
8368     Constant *C = ConstantVector::get(CV);
8369     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8370     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8371                                  MachinePointerInfo::getConstantPool(),
8372                                  false, false, 16);
8373
8374     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8375     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8376     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8377     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8378   }
8379   if (VT == MVT::v16i8) {
8380     // a = a << 5;
8381     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8382                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8383                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8384
8385     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8386     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8387
8388     std::vector<Constant*> CVM1(16, CM1);
8389     std::vector<Constant*> CVM2(16, CM2);
8390     Constant *C = ConstantVector::get(CVM1);
8391     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8392     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8393                             MachinePointerInfo::getConstantPool(),
8394                             false, false, 16);
8395
8396     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8397     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8398     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8399                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8400                     DAG.getConstant(4, MVT::i32));
8401     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8402     // a += a
8403     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8404
8405     C = ConstantVector::get(CVM2);
8406     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8407     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8408                     MachinePointerInfo::getConstantPool(),
8409                     false, false, 16);
8410
8411     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8412     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8413     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8414                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8415                     DAG.getConstant(2, MVT::i32));
8416     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, R, M, Op);
8417     // a += a
8418     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8419
8420     // return pblendv(r, r+r, a);
8421     R = DAG.getNode(X86ISD::PBLENDVB, dl, VT, 
8422                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8423     return R;
8424   }
8425   return SDValue();
8426 }
8427
8428 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8429   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8430   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8431   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8432   // has only one use.
8433   SDNode *N = Op.getNode();
8434   SDValue LHS = N->getOperand(0);
8435   SDValue RHS = N->getOperand(1);
8436   unsigned BaseOp = 0;
8437   unsigned Cond = 0;
8438   DebugLoc DL = Op.getDebugLoc();
8439   switch (Op.getOpcode()) {
8440   default: llvm_unreachable("Unknown ovf instruction!");
8441   case ISD::SADDO:
8442     // A subtract of one will be selected as a INC. Note that INC doesn't
8443     // set CF, so we can't do this for UADDO.
8444     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8445       if (C->getAPIntValue() == 1) {
8446         BaseOp = X86ISD::INC;
8447         Cond = X86::COND_O;
8448         break;
8449       }
8450     BaseOp = X86ISD::ADD;
8451     Cond = X86::COND_O;
8452     break;
8453   case ISD::UADDO:
8454     BaseOp = X86ISD::ADD;
8455     Cond = X86::COND_B;
8456     break;
8457   case ISD::SSUBO:
8458     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8459     // set CF, so we can't do this for USUBO.
8460     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8461       if (C->getAPIntValue() == 1) {
8462         BaseOp = X86ISD::DEC;
8463         Cond = X86::COND_O;
8464         break;
8465       }
8466     BaseOp = X86ISD::SUB;
8467     Cond = X86::COND_O;
8468     break;
8469   case ISD::USUBO:
8470     BaseOp = X86ISD::SUB;
8471     Cond = X86::COND_B;
8472     break;
8473   case ISD::SMULO:
8474     BaseOp = X86ISD::SMUL;
8475     Cond = X86::COND_O;
8476     break;
8477   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8478     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8479                                  MVT::i32);
8480     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8481     
8482     SDValue SetCC =
8483       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8484                   DAG.getConstant(X86::COND_O, MVT::i32),
8485                   SDValue(Sum.getNode(), 2));
8486     
8487     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8488     return Sum;
8489   }
8490   }
8491
8492   // Also sets EFLAGS.
8493   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8494   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8495
8496   SDValue SetCC =
8497     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8498                 DAG.getConstant(Cond, MVT::i32),
8499                 SDValue(Sum.getNode(), 1));
8500
8501   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8502   return Sum;
8503 }
8504
8505 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8506   DebugLoc dl = Op.getDebugLoc();
8507
8508   if (!Subtarget->hasSSE2()) {
8509     SDValue Chain = Op.getOperand(0);
8510     SDValue Zero = DAG.getConstant(0,
8511                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8512     SDValue Ops[] = {
8513       DAG.getRegister(X86::ESP, MVT::i32), // Base
8514       DAG.getTargetConstant(1, MVT::i8),   // Scale
8515       DAG.getRegister(0, MVT::i32),        // Index
8516       DAG.getTargetConstant(0, MVT::i32),  // Disp
8517       DAG.getRegister(0, MVT::i32),        // Segment.
8518       Zero,
8519       Chain
8520     };
8521     SDNode *Res =
8522       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8523                           array_lengthof(Ops));
8524     return SDValue(Res, 0);
8525   }
8526
8527   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8528   if (!isDev)
8529     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8530
8531   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8532   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8533   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8534   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8535
8536   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8537   if (!Op1 && !Op2 && !Op3 && Op4)
8538     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8539
8540   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8541   if (Op1 && !Op2 && !Op3 && !Op4)
8542     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8543
8544   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8545   //           (MFENCE)>;
8546   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8547 }
8548
8549 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8550   EVT T = Op.getValueType();
8551   DebugLoc DL = Op.getDebugLoc();
8552   unsigned Reg = 0;
8553   unsigned size = 0;
8554   switch(T.getSimpleVT().SimpleTy) {
8555   default:
8556     assert(false && "Invalid value type!");
8557   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8558   case MVT::i16: Reg = X86::AX;  size = 2; break;
8559   case MVT::i32: Reg = X86::EAX; size = 4; break;
8560   case MVT::i64:
8561     assert(Subtarget->is64Bit() && "Node not type legal!");
8562     Reg = X86::RAX; size = 8;
8563     break;
8564   }
8565   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8566                                     Op.getOperand(2), SDValue());
8567   SDValue Ops[] = { cpIn.getValue(0),
8568                     Op.getOperand(1),
8569                     Op.getOperand(3),
8570                     DAG.getTargetConstant(size, MVT::i8),
8571                     cpIn.getValue(1) };
8572   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8573   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8574   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8575                                            Ops, 5, T, MMO);
8576   SDValue cpOut =
8577     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8578   return cpOut;
8579 }
8580
8581 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8582                                                  SelectionDAG &DAG) const {
8583   assert(Subtarget->is64Bit() && "Result not type legalized?");
8584   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8585   SDValue TheChain = Op.getOperand(0);
8586   DebugLoc dl = Op.getDebugLoc();
8587   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8588   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8589   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8590                                    rax.getValue(2));
8591   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8592                             DAG.getConstant(32, MVT::i8));
8593   SDValue Ops[] = {
8594     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8595     rdx.getValue(1)
8596   };
8597   return DAG.getMergeValues(Ops, 2, dl);
8598 }
8599
8600 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8601                                             SelectionDAG &DAG) const {
8602   EVT SrcVT = Op.getOperand(0).getValueType();
8603   EVT DstVT = Op.getValueType();
8604   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8605          Subtarget->hasMMX() && "Unexpected custom BITCAST");
8606   assert((DstVT == MVT::i64 ||
8607           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8608          "Unexpected custom BITCAST");
8609   // i64 <=> MMX conversions are Legal.
8610   if (SrcVT==MVT::i64 && DstVT.isVector())
8611     return Op;
8612   if (DstVT==MVT::i64 && SrcVT.isVector())
8613     return Op;
8614   // MMX <=> MMX conversions are Legal.
8615   if (SrcVT.isVector() && DstVT.isVector())
8616     return Op;
8617   // All other conversions need to be expanded.
8618   return SDValue();
8619 }
8620
8621 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8622   SDNode *Node = Op.getNode();
8623   DebugLoc dl = Node->getDebugLoc();
8624   EVT T = Node->getValueType(0);
8625   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8626                               DAG.getConstant(0, T), Node->getOperand(2));
8627   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8628                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8629                        Node->getOperand(0),
8630                        Node->getOperand(1), negOp,
8631                        cast<AtomicSDNode>(Node)->getSrcValue(),
8632                        cast<AtomicSDNode>(Node)->getAlignment());
8633 }
8634
8635 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8636   EVT VT = Op.getNode()->getValueType(0);
8637
8638   // Let legalize expand this if it isn't a legal type yet.
8639   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8640     return SDValue();
8641   
8642   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8643   
8644   unsigned Opc;
8645   bool ExtraOp = false;
8646   switch (Op.getOpcode()) {
8647   default: assert(0 && "Invalid code");
8648   case ISD::ADDC: Opc = X86ISD::ADD; break;
8649   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8650   case ISD::SUBC: Opc = X86ISD::SUB; break;
8651   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8652   }
8653   
8654   if (!ExtraOp)
8655     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8656                        Op.getOperand(1));
8657   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8658                      Op.getOperand(1), Op.getOperand(2));
8659 }
8660
8661 /// LowerOperation - Provide custom lowering hooks for some operations.
8662 ///
8663 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8664   switch (Op.getOpcode()) {
8665   default: llvm_unreachable("Should not custom lower this!");
8666   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8667   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8668   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8669   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8670   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8671   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8672   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8673   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8674   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8675   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8676   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8677   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8678   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8679   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8680   case ISD::SHL_PARTS:
8681   case ISD::SRA_PARTS:
8682   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8683   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8684   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8685   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8686   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8687   case ISD::FABS:               return LowerFABS(Op, DAG);
8688   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8689   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8690   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8691   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8692   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8693   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8694   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8695   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8696   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8697   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8698   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8699   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8700   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8701   case ISD::FRAME_TO_ARGS_OFFSET:
8702                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8703   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8704   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8705   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8706   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8707   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8708   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8709   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8710   case ISD::SHL:                return LowerSHL(Op, DAG);
8711   case ISD::SADDO:
8712   case ISD::UADDO:
8713   case ISD::SSUBO:
8714   case ISD::USUBO:
8715   case ISD::SMULO:
8716   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8717   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8718   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8719   case ISD::ADDC:
8720   case ISD::ADDE:
8721   case ISD::SUBC:
8722   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8723   }
8724 }
8725
8726 void X86TargetLowering::
8727 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8728                         SelectionDAG &DAG, unsigned NewOp) const {
8729   EVT T = Node->getValueType(0);
8730   DebugLoc dl = Node->getDebugLoc();
8731   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8732
8733   SDValue Chain = Node->getOperand(0);
8734   SDValue In1 = Node->getOperand(1);
8735   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8736                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8737   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8738                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8739   SDValue Ops[] = { Chain, In1, In2L, In2H };
8740   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8741   SDValue Result =
8742     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8743                             cast<MemSDNode>(Node)->getMemOperand());
8744   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8745   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8746   Results.push_back(Result.getValue(2));
8747 }
8748
8749 /// ReplaceNodeResults - Replace a node with an illegal result type
8750 /// with a new node built out of custom code.
8751 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8752                                            SmallVectorImpl<SDValue>&Results,
8753                                            SelectionDAG &DAG) const {
8754   DebugLoc dl = N->getDebugLoc();
8755   switch (N->getOpcode()) {
8756   default:
8757     assert(false && "Do not know how to custom type legalize this operation!");
8758     return;
8759   case ISD::ADDC:
8760   case ISD::ADDE:
8761   case ISD::SUBC:
8762   case ISD::SUBE:
8763     // We don't want to expand or promote these.
8764     return;
8765   case ISD::FP_TO_SINT: {
8766     std::pair<SDValue,SDValue> Vals =
8767         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8768     SDValue FIST = Vals.first, StackSlot = Vals.second;
8769     if (FIST.getNode() != 0) {
8770       EVT VT = N->getValueType(0);
8771       // Return a load from the stack slot.
8772       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8773                                     MachinePointerInfo(), false, false, 0));
8774     }
8775     return;
8776   }
8777   case ISD::READCYCLECOUNTER: {
8778     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8779     SDValue TheChain = N->getOperand(0);
8780     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8781     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8782                                      rd.getValue(1));
8783     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8784                                      eax.getValue(2));
8785     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8786     SDValue Ops[] = { eax, edx };
8787     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8788     Results.push_back(edx.getValue(1));
8789     return;
8790   }
8791   case ISD::ATOMIC_CMP_SWAP: {
8792     EVT T = N->getValueType(0);
8793     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8794     SDValue cpInL, cpInH;
8795     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8796                         DAG.getConstant(0, MVT::i32));
8797     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8798                         DAG.getConstant(1, MVT::i32));
8799     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8800     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8801                              cpInL.getValue(1));
8802     SDValue swapInL, swapInH;
8803     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8804                           DAG.getConstant(0, MVT::i32));
8805     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8806                           DAG.getConstant(1, MVT::i32));
8807     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8808                                cpInH.getValue(1));
8809     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8810                                swapInL.getValue(1));
8811     SDValue Ops[] = { swapInH.getValue(0),
8812                       N->getOperand(1),
8813                       swapInH.getValue(1) };
8814     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
8815     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8816     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8817                                              Ops, 3, T, MMO);
8818     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8819                                         MVT::i32, Result.getValue(1));
8820     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8821                                         MVT::i32, cpOutL.getValue(2));
8822     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8823     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8824     Results.push_back(cpOutH.getValue(1));
8825     return;
8826   }
8827   case ISD::ATOMIC_LOAD_ADD:
8828     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8829     return;
8830   case ISD::ATOMIC_LOAD_AND:
8831     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8832     return;
8833   case ISD::ATOMIC_LOAD_NAND:
8834     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8835     return;
8836   case ISD::ATOMIC_LOAD_OR:
8837     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8838     return;
8839   case ISD::ATOMIC_LOAD_SUB:
8840     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8841     return;
8842   case ISD::ATOMIC_LOAD_XOR:
8843     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8844     return;
8845   case ISD::ATOMIC_SWAP:
8846     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8847     return;
8848   }
8849 }
8850
8851 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8852   switch (Opcode) {
8853   default: return NULL;
8854   case X86ISD::BSF:                return "X86ISD::BSF";
8855   case X86ISD::BSR:                return "X86ISD::BSR";
8856   case X86ISD::SHLD:               return "X86ISD::SHLD";
8857   case X86ISD::SHRD:               return "X86ISD::SHRD";
8858   case X86ISD::FAND:               return "X86ISD::FAND";
8859   case X86ISD::FOR:                return "X86ISD::FOR";
8860   case X86ISD::FXOR:               return "X86ISD::FXOR";
8861   case X86ISD::FSRL:               return "X86ISD::FSRL";
8862   case X86ISD::FILD:               return "X86ISD::FILD";
8863   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8864   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8865   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8866   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8867   case X86ISD::FLD:                return "X86ISD::FLD";
8868   case X86ISD::FST:                return "X86ISD::FST";
8869   case X86ISD::CALL:               return "X86ISD::CALL";
8870   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8871   case X86ISD::BT:                 return "X86ISD::BT";
8872   case X86ISD::CMP:                return "X86ISD::CMP";
8873   case X86ISD::COMI:               return "X86ISD::COMI";
8874   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8875   case X86ISD::SETCC:              return "X86ISD::SETCC";
8876   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8877   case X86ISD::CMOV:               return "X86ISD::CMOV";
8878   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8879   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8880   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8881   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8882   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8883   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8884   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8885   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8886   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8887   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8888   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8889   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8890   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8891   case X86ISD::PANDN:              return "X86ISD::PANDN";
8892   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
8893   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
8894   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
8895   case X86ISD::PBLENDVB:           return "X86ISD::PBLENDVB";
8896   case X86ISD::FMAX:               return "X86ISD::FMAX";
8897   case X86ISD::FMIN:               return "X86ISD::FMIN";
8898   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8899   case X86ISD::FRCP:               return "X86ISD::FRCP";
8900   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8901   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8902   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8903   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8904   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8905   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8906   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8907   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8908   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8909   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8910   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8911   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8912   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8913   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8914   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8915   case X86ISD::VSHL:               return "X86ISD::VSHL";
8916   case X86ISD::VSRL:               return "X86ISD::VSRL";
8917   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8918   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8919   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8920   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8921   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8922   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8923   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8924   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8925   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8926   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8927   case X86ISD::ADD:                return "X86ISD::ADD";
8928   case X86ISD::SUB:                return "X86ISD::SUB";
8929   case X86ISD::ADC:                return "X86ISD::ADC";
8930   case X86ISD::SBB:                return "X86ISD::SBB";
8931   case X86ISD::SMUL:               return "X86ISD::SMUL";
8932   case X86ISD::UMUL:               return "X86ISD::UMUL";
8933   case X86ISD::INC:                return "X86ISD::INC";
8934   case X86ISD::DEC:                return "X86ISD::DEC";
8935   case X86ISD::OR:                 return "X86ISD::OR";
8936   case X86ISD::XOR:                return "X86ISD::XOR";
8937   case X86ISD::AND:                return "X86ISD::AND";
8938   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8939   case X86ISD::PTEST:              return "X86ISD::PTEST";
8940   case X86ISD::TESTP:              return "X86ISD::TESTP";
8941   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8942   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8943   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8944   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8945   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8946   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8947   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8948   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8949   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8950   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8951   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8952   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8953   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8954   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8955   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8956   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8957   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8958   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8959   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8960   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8961   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8962   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8963   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8964   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8965   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8966   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8967   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8968   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8969   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8970   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8971   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8972   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8973   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8974   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8975   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
8976   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
8977   }
8978 }
8979
8980 // isLegalAddressingMode - Return true if the addressing mode represented
8981 // by AM is legal for this target, for a load/store of the specified type.
8982 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8983                                               const Type *Ty) const {
8984   // X86 supports extremely general addressing modes.
8985   CodeModel::Model M = getTargetMachine().getCodeModel();
8986   Reloc::Model R = getTargetMachine().getRelocationModel();
8987
8988   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8989   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8990     return false;
8991
8992   if (AM.BaseGV) {
8993     unsigned GVFlags =
8994       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8995
8996     // If a reference to this global requires an extra load, we can't fold it.
8997     if (isGlobalStubReference(GVFlags))
8998       return false;
8999
9000     // If BaseGV requires a register for the PIC base, we cannot also have a
9001     // BaseReg specified.
9002     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9003       return false;
9004
9005     // If lower 4G is not available, then we must use rip-relative addressing.
9006     if ((M != CodeModel::Small || R != Reloc::Static) &&
9007         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9008       return false;
9009   }
9010
9011   switch (AM.Scale) {
9012   case 0:
9013   case 1:
9014   case 2:
9015   case 4:
9016   case 8:
9017     // These scales always work.
9018     break;
9019   case 3:
9020   case 5:
9021   case 9:
9022     // These scales are formed with basereg+scalereg.  Only accept if there is
9023     // no basereg yet.
9024     if (AM.HasBaseReg)
9025       return false;
9026     break;
9027   default:  // Other stuff never works.
9028     return false;
9029   }
9030
9031   return true;
9032 }
9033
9034
9035 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9036   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9037     return false;
9038   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9039   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9040   if (NumBits1 <= NumBits2)
9041     return false;
9042   return true;
9043 }
9044
9045 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9046   if (!VT1.isInteger() || !VT2.isInteger())
9047     return false;
9048   unsigned NumBits1 = VT1.getSizeInBits();
9049   unsigned NumBits2 = VT2.getSizeInBits();
9050   if (NumBits1 <= NumBits2)
9051     return false;
9052   return true;
9053 }
9054
9055 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9056   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9057   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9058 }
9059
9060 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9061   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9062   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9063 }
9064
9065 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9066   // i16 instructions are longer (0x66 prefix) and potentially slower.
9067   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9068 }
9069
9070 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9071 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9072 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9073 /// are assumed to be legal.
9074 bool
9075 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9076                                       EVT VT) const {
9077   // Very little shuffling can be done for 64-bit vectors right now.
9078   if (VT.getSizeInBits() == 64)
9079     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9080
9081   // FIXME: pshufb, blends, shifts.
9082   return (VT.getVectorNumElements() == 2 ||
9083           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9084           isMOVLMask(M, VT) ||
9085           isSHUFPMask(M, VT) ||
9086           isPSHUFDMask(M, VT) ||
9087           isPSHUFHWMask(M, VT) ||
9088           isPSHUFLWMask(M, VT) ||
9089           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9090           isUNPCKLMask(M, VT) ||
9091           isUNPCKHMask(M, VT) ||
9092           isUNPCKL_v_undef_Mask(M, VT) ||
9093           isUNPCKH_v_undef_Mask(M, VT));
9094 }
9095
9096 bool
9097 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9098                                           EVT VT) const {
9099   unsigned NumElts = VT.getVectorNumElements();
9100   // FIXME: This collection of masks seems suspect.
9101   if (NumElts == 2)
9102     return true;
9103   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9104     return (isMOVLMask(Mask, VT)  ||
9105             isCommutedMOVLMask(Mask, VT, true) ||
9106             isSHUFPMask(Mask, VT) ||
9107             isCommutedSHUFPMask(Mask, VT));
9108   }
9109   return false;
9110 }
9111
9112 //===----------------------------------------------------------------------===//
9113 //                           X86 Scheduler Hooks
9114 //===----------------------------------------------------------------------===//
9115
9116 // private utility function
9117 MachineBasicBlock *
9118 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9119                                                        MachineBasicBlock *MBB,
9120                                                        unsigned regOpc,
9121                                                        unsigned immOpc,
9122                                                        unsigned LoadOpc,
9123                                                        unsigned CXchgOpc,
9124                                                        unsigned notOpc,
9125                                                        unsigned EAXreg,
9126                                                        TargetRegisterClass *RC,
9127                                                        bool invSrc) const {
9128   // For the atomic bitwise operator, we generate
9129   //   thisMBB:
9130   //   newMBB:
9131   //     ld  t1 = [bitinstr.addr]
9132   //     op  t2 = t1, [bitinstr.val]
9133   //     mov EAX = t1
9134   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9135   //     bz  newMBB
9136   //     fallthrough -->nextMBB
9137   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9138   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9139   MachineFunction::iterator MBBIter = MBB;
9140   ++MBBIter;
9141
9142   /// First build the CFG
9143   MachineFunction *F = MBB->getParent();
9144   MachineBasicBlock *thisMBB = MBB;
9145   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9146   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9147   F->insert(MBBIter, newMBB);
9148   F->insert(MBBIter, nextMBB);
9149
9150   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9151   nextMBB->splice(nextMBB->begin(), thisMBB,
9152                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9153                   thisMBB->end());
9154   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9155
9156   // Update thisMBB to fall through to newMBB
9157   thisMBB->addSuccessor(newMBB);
9158
9159   // newMBB jumps to itself and fall through to nextMBB
9160   newMBB->addSuccessor(nextMBB);
9161   newMBB->addSuccessor(newMBB);
9162
9163   // Insert instructions into newMBB based on incoming instruction
9164   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9165          "unexpected number of operands");
9166   DebugLoc dl = bInstr->getDebugLoc();
9167   MachineOperand& destOper = bInstr->getOperand(0);
9168   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9169   int numArgs = bInstr->getNumOperands() - 1;
9170   for (int i=0; i < numArgs; ++i)
9171     argOpers[i] = &bInstr->getOperand(i+1);
9172
9173   // x86 address has 4 operands: base, index, scale, and displacement
9174   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9175   int valArgIndx = lastAddrIndx + 1;
9176
9177   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9178   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9179   for (int i=0; i <= lastAddrIndx; ++i)
9180     (*MIB).addOperand(*argOpers[i]);
9181
9182   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9183   if (invSrc) {
9184     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9185   }
9186   else
9187     tt = t1;
9188
9189   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9190   assert((argOpers[valArgIndx]->isReg() ||
9191           argOpers[valArgIndx]->isImm()) &&
9192          "invalid operand");
9193   if (argOpers[valArgIndx]->isReg())
9194     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9195   else
9196     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9197   MIB.addReg(tt);
9198   (*MIB).addOperand(*argOpers[valArgIndx]);
9199
9200   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9201   MIB.addReg(t1);
9202
9203   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9204   for (int i=0; i <= lastAddrIndx; ++i)
9205     (*MIB).addOperand(*argOpers[i]);
9206   MIB.addReg(t2);
9207   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9208   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9209                     bInstr->memoperands_end());
9210
9211   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9212   MIB.addReg(EAXreg);
9213
9214   // insert branch
9215   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9216
9217   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9218   return nextMBB;
9219 }
9220
9221 // private utility function:  64 bit atomics on 32 bit host.
9222 MachineBasicBlock *
9223 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9224                                                        MachineBasicBlock *MBB,
9225                                                        unsigned regOpcL,
9226                                                        unsigned regOpcH,
9227                                                        unsigned immOpcL,
9228                                                        unsigned immOpcH,
9229                                                        bool invSrc) const {
9230   // For the atomic bitwise operator, we generate
9231   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9232   //     ld t1,t2 = [bitinstr.addr]
9233   //   newMBB:
9234   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9235   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9236   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9237   //     mov ECX, EBX <- t5, t6
9238   //     mov EAX, EDX <- t1, t2
9239   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9240   //     mov t3, t4 <- EAX, EDX
9241   //     bz  newMBB
9242   //     result in out1, out2
9243   //     fallthrough -->nextMBB
9244
9245   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9246   const unsigned LoadOpc = X86::MOV32rm;
9247   const unsigned NotOpc = X86::NOT32r;
9248   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9249   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9250   MachineFunction::iterator MBBIter = MBB;
9251   ++MBBIter;
9252
9253   /// First build the CFG
9254   MachineFunction *F = MBB->getParent();
9255   MachineBasicBlock *thisMBB = MBB;
9256   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9257   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9258   F->insert(MBBIter, newMBB);
9259   F->insert(MBBIter, nextMBB);
9260
9261   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9262   nextMBB->splice(nextMBB->begin(), thisMBB,
9263                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9264                   thisMBB->end());
9265   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9266
9267   // Update thisMBB to fall through to newMBB
9268   thisMBB->addSuccessor(newMBB);
9269
9270   // newMBB jumps to itself and fall through to nextMBB
9271   newMBB->addSuccessor(nextMBB);
9272   newMBB->addSuccessor(newMBB);
9273
9274   DebugLoc dl = bInstr->getDebugLoc();
9275   // Insert instructions into newMBB based on incoming instruction
9276   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9277   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9278          "unexpected number of operands");
9279   MachineOperand& dest1Oper = bInstr->getOperand(0);
9280   MachineOperand& dest2Oper = bInstr->getOperand(1);
9281   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9282   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9283     argOpers[i] = &bInstr->getOperand(i+2);
9284
9285     // We use some of the operands multiple times, so conservatively just
9286     // clear any kill flags that might be present.
9287     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9288       argOpers[i]->setIsKill(false);
9289   }
9290
9291   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9292   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9293
9294   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9295   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9296   for (int i=0; i <= lastAddrIndx; ++i)
9297     (*MIB).addOperand(*argOpers[i]);
9298   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9299   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9300   // add 4 to displacement.
9301   for (int i=0; i <= lastAddrIndx-2; ++i)
9302     (*MIB).addOperand(*argOpers[i]);
9303   MachineOperand newOp3 = *(argOpers[3]);
9304   if (newOp3.isImm())
9305     newOp3.setImm(newOp3.getImm()+4);
9306   else
9307     newOp3.setOffset(newOp3.getOffset()+4);
9308   (*MIB).addOperand(newOp3);
9309   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9310
9311   // t3/4 are defined later, at the bottom of the loop
9312   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9313   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9314   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9315     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9316   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9317     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9318
9319   // The subsequent operations should be using the destination registers of
9320   //the PHI instructions.
9321   if (invSrc) {
9322     t1 = F->getRegInfo().createVirtualRegister(RC);
9323     t2 = F->getRegInfo().createVirtualRegister(RC);
9324     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9325     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9326   } else {
9327     t1 = dest1Oper.getReg();
9328     t2 = dest2Oper.getReg();
9329   }
9330
9331   int valArgIndx = lastAddrIndx + 1;
9332   assert((argOpers[valArgIndx]->isReg() ||
9333           argOpers[valArgIndx]->isImm()) &&
9334          "invalid operand");
9335   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9336   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9337   if (argOpers[valArgIndx]->isReg())
9338     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9339   else
9340     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9341   if (regOpcL != X86::MOV32rr)
9342     MIB.addReg(t1);
9343   (*MIB).addOperand(*argOpers[valArgIndx]);
9344   assert(argOpers[valArgIndx + 1]->isReg() ==
9345          argOpers[valArgIndx]->isReg());
9346   assert(argOpers[valArgIndx + 1]->isImm() ==
9347          argOpers[valArgIndx]->isImm());
9348   if (argOpers[valArgIndx + 1]->isReg())
9349     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9350   else
9351     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9352   if (regOpcH != X86::MOV32rr)
9353     MIB.addReg(t2);
9354   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9355
9356   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9357   MIB.addReg(t1);
9358   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9359   MIB.addReg(t2);
9360
9361   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9362   MIB.addReg(t5);
9363   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9364   MIB.addReg(t6);
9365
9366   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9367   for (int i=0; i <= lastAddrIndx; ++i)
9368     (*MIB).addOperand(*argOpers[i]);
9369
9370   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9371   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9372                     bInstr->memoperands_end());
9373
9374   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9375   MIB.addReg(X86::EAX);
9376   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9377   MIB.addReg(X86::EDX);
9378
9379   // insert branch
9380   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9381
9382   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9383   return nextMBB;
9384 }
9385
9386 // private utility function
9387 MachineBasicBlock *
9388 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9389                                                       MachineBasicBlock *MBB,
9390                                                       unsigned cmovOpc) const {
9391   // For the atomic min/max operator, we generate
9392   //   thisMBB:
9393   //   newMBB:
9394   //     ld t1 = [min/max.addr]
9395   //     mov t2 = [min/max.val]
9396   //     cmp  t1, t2
9397   //     cmov[cond] t2 = t1
9398   //     mov EAX = t1
9399   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9400   //     bz   newMBB
9401   //     fallthrough -->nextMBB
9402   //
9403   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9404   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9405   MachineFunction::iterator MBBIter = MBB;
9406   ++MBBIter;
9407
9408   /// First build the CFG
9409   MachineFunction *F = MBB->getParent();
9410   MachineBasicBlock *thisMBB = MBB;
9411   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9412   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9413   F->insert(MBBIter, newMBB);
9414   F->insert(MBBIter, nextMBB);
9415
9416   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9417   nextMBB->splice(nextMBB->begin(), thisMBB,
9418                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9419                   thisMBB->end());
9420   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9421
9422   // Update thisMBB to fall through to newMBB
9423   thisMBB->addSuccessor(newMBB);
9424
9425   // newMBB jumps to newMBB and fall through to nextMBB
9426   newMBB->addSuccessor(nextMBB);
9427   newMBB->addSuccessor(newMBB);
9428
9429   DebugLoc dl = mInstr->getDebugLoc();
9430   // Insert instructions into newMBB based on incoming instruction
9431   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9432          "unexpected number of operands");
9433   MachineOperand& destOper = mInstr->getOperand(0);
9434   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9435   int numArgs = mInstr->getNumOperands() - 1;
9436   for (int i=0; i < numArgs; ++i)
9437     argOpers[i] = &mInstr->getOperand(i+1);
9438
9439   // x86 address has 4 operands: base, index, scale, and displacement
9440   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9441   int valArgIndx = lastAddrIndx + 1;
9442
9443   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9444   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9445   for (int i=0; i <= lastAddrIndx; ++i)
9446     (*MIB).addOperand(*argOpers[i]);
9447
9448   // We only support register and immediate values
9449   assert((argOpers[valArgIndx]->isReg() ||
9450           argOpers[valArgIndx]->isImm()) &&
9451          "invalid operand");
9452
9453   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9454   if (argOpers[valArgIndx]->isReg())
9455     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9456   else
9457     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9458   (*MIB).addOperand(*argOpers[valArgIndx]);
9459
9460   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9461   MIB.addReg(t1);
9462
9463   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9464   MIB.addReg(t1);
9465   MIB.addReg(t2);
9466
9467   // Generate movc
9468   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9469   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9470   MIB.addReg(t2);
9471   MIB.addReg(t1);
9472
9473   // Cmp and exchange if none has modified the memory location
9474   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9475   for (int i=0; i <= lastAddrIndx; ++i)
9476     (*MIB).addOperand(*argOpers[i]);
9477   MIB.addReg(t3);
9478   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9479   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9480                     mInstr->memoperands_end());
9481
9482   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9483   MIB.addReg(X86::EAX);
9484
9485   // insert branch
9486   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9487
9488   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9489   return nextMBB;
9490 }
9491
9492 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9493 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9494 // in the .td file.
9495 MachineBasicBlock *
9496 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9497                             unsigned numArgs, bool memArg) const {
9498   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9499          "Target must have SSE4.2 or AVX features enabled");
9500
9501   DebugLoc dl = MI->getDebugLoc();
9502   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9503   unsigned Opc;
9504   if (!Subtarget->hasAVX()) {
9505     if (memArg)
9506       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9507     else
9508       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9509   } else {
9510     if (memArg)
9511       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9512     else
9513       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9514   }
9515
9516   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9517   for (unsigned i = 0; i < numArgs; ++i) {
9518     MachineOperand &Op = MI->getOperand(i+1);
9519     if (!(Op.isReg() && Op.isImplicit()))
9520       MIB.addOperand(Op);
9521   }
9522   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9523     .addReg(X86::XMM0);
9524
9525   MI->eraseFromParent();
9526   return BB;
9527 }
9528
9529 MachineBasicBlock *
9530 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9531   DebugLoc dl = MI->getDebugLoc();
9532   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9533   
9534   // Address into RAX/EAX, other two args into ECX, EDX.
9535   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9536   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9537   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9538   for (int i = 0; i < X86::AddrNumOperands; ++i)
9539     MIB.addOperand(MI->getOperand(i));
9540   
9541   unsigned ValOps = X86::AddrNumOperands;
9542   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9543     .addReg(MI->getOperand(ValOps).getReg());
9544   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9545     .addReg(MI->getOperand(ValOps+1).getReg());
9546
9547   // The instruction doesn't actually take any operands though.
9548   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9549   
9550   MI->eraseFromParent(); // The pseudo is gone now.
9551   return BB;
9552 }
9553
9554 MachineBasicBlock *
9555 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9556   DebugLoc dl = MI->getDebugLoc();
9557   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9558   
9559   // First arg in ECX, the second in EAX.
9560   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9561     .addReg(MI->getOperand(0).getReg());
9562   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9563     .addReg(MI->getOperand(1).getReg());
9564     
9565   // The instruction doesn't actually take any operands though.
9566   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9567   
9568   MI->eraseFromParent(); // The pseudo is gone now.
9569   return BB;
9570 }
9571
9572 MachineBasicBlock *
9573 X86TargetLowering::EmitVAARG64WithCustomInserter(
9574                    MachineInstr *MI,
9575                    MachineBasicBlock *MBB) const {
9576   // Emit va_arg instruction on X86-64.
9577
9578   // Operands to this pseudo-instruction:
9579   // 0  ) Output        : destination address (reg)
9580   // 1-5) Input         : va_list address (addr, i64mem)
9581   // 6  ) ArgSize       : Size (in bytes) of vararg type
9582   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9583   // 8  ) Align         : Alignment of type
9584   // 9  ) EFLAGS (implicit-def)
9585
9586   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9587   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9588
9589   unsigned DestReg = MI->getOperand(0).getReg();
9590   MachineOperand &Base = MI->getOperand(1);
9591   MachineOperand &Scale = MI->getOperand(2);
9592   MachineOperand &Index = MI->getOperand(3);
9593   MachineOperand &Disp = MI->getOperand(4);
9594   MachineOperand &Segment = MI->getOperand(5);
9595   unsigned ArgSize = MI->getOperand(6).getImm();
9596   unsigned ArgMode = MI->getOperand(7).getImm();
9597   unsigned Align = MI->getOperand(8).getImm();
9598
9599   // Memory Reference
9600   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9601   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9602   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9603
9604   // Machine Information
9605   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9606   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9607   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9608   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9609   DebugLoc DL = MI->getDebugLoc();
9610
9611   // struct va_list {
9612   //   i32   gp_offset
9613   //   i32   fp_offset
9614   //   i64   overflow_area (address)
9615   //   i64   reg_save_area (address)
9616   // }
9617   // sizeof(va_list) = 24
9618   // alignment(va_list) = 8
9619
9620   unsigned TotalNumIntRegs = 6;
9621   unsigned TotalNumXMMRegs = 8;
9622   bool UseGPOffset = (ArgMode == 1);
9623   bool UseFPOffset = (ArgMode == 2);
9624   unsigned MaxOffset = TotalNumIntRegs * 8 +
9625                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9626
9627   /* Align ArgSize to a multiple of 8 */
9628   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9629   bool NeedsAlign = (Align > 8);
9630
9631   MachineBasicBlock *thisMBB = MBB;
9632   MachineBasicBlock *overflowMBB;
9633   MachineBasicBlock *offsetMBB;
9634   MachineBasicBlock *endMBB;
9635
9636   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9637   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9638   unsigned OffsetReg = 0;
9639
9640   if (!UseGPOffset && !UseFPOffset) {
9641     // If we only pull from the overflow region, we don't create a branch.
9642     // We don't need to alter control flow.
9643     OffsetDestReg = 0; // unused
9644     OverflowDestReg = DestReg;
9645
9646     offsetMBB = NULL;
9647     overflowMBB = thisMBB;
9648     endMBB = thisMBB;
9649   } else {
9650     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9651     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9652     // If not, pull from overflow_area. (branch to overflowMBB)
9653     //
9654     //       thisMBB
9655     //         |     .
9656     //         |        .
9657     //     offsetMBB   overflowMBB
9658     //         |        .
9659     //         |     .
9660     //        endMBB
9661
9662     // Registers for the PHI in endMBB
9663     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9664     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9665
9666     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9667     MachineFunction *MF = MBB->getParent();
9668     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9669     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9670     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9671
9672     MachineFunction::iterator MBBIter = MBB;
9673     ++MBBIter;
9674
9675     // Insert the new basic blocks
9676     MF->insert(MBBIter, offsetMBB);
9677     MF->insert(MBBIter, overflowMBB);
9678     MF->insert(MBBIter, endMBB);
9679
9680     // Transfer the remainder of MBB and its successor edges to endMBB.
9681     endMBB->splice(endMBB->begin(), thisMBB,
9682                     llvm::next(MachineBasicBlock::iterator(MI)),
9683                     thisMBB->end());
9684     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9685
9686     // Make offsetMBB and overflowMBB successors of thisMBB
9687     thisMBB->addSuccessor(offsetMBB);
9688     thisMBB->addSuccessor(overflowMBB);
9689
9690     // endMBB is a successor of both offsetMBB and overflowMBB
9691     offsetMBB->addSuccessor(endMBB);
9692     overflowMBB->addSuccessor(endMBB);
9693
9694     // Load the offset value into a register
9695     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9696     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9697       .addOperand(Base)
9698       .addOperand(Scale)
9699       .addOperand(Index)
9700       .addDisp(Disp, UseFPOffset ? 4 : 0)
9701       .addOperand(Segment)
9702       .setMemRefs(MMOBegin, MMOEnd);
9703
9704     // Check if there is enough room left to pull this argument.
9705     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9706       .addReg(OffsetReg)
9707       .addImm(MaxOffset + 8 - ArgSizeA8);
9708
9709     // Branch to "overflowMBB" if offset >= max
9710     // Fall through to "offsetMBB" otherwise
9711     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9712       .addMBB(overflowMBB);
9713   }
9714
9715   // In offsetMBB, emit code to use the reg_save_area.
9716   if (offsetMBB) {
9717     assert(OffsetReg != 0);
9718
9719     // Read the reg_save_area address.
9720     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9721     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9722       .addOperand(Base)
9723       .addOperand(Scale)
9724       .addOperand(Index)
9725       .addDisp(Disp, 16)
9726       .addOperand(Segment)
9727       .setMemRefs(MMOBegin, MMOEnd);
9728
9729     // Zero-extend the offset
9730     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9731       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9732         .addImm(0)
9733         .addReg(OffsetReg)
9734         .addImm(X86::sub_32bit);
9735
9736     // Add the offset to the reg_save_area to get the final address.
9737     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9738       .addReg(OffsetReg64)
9739       .addReg(RegSaveReg);
9740
9741     // Compute the offset for the next argument
9742     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9743     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9744       .addReg(OffsetReg)
9745       .addImm(UseFPOffset ? 16 : 8);
9746
9747     // Store it back into the va_list.
9748     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9749       .addOperand(Base)
9750       .addOperand(Scale)
9751       .addOperand(Index)
9752       .addDisp(Disp, UseFPOffset ? 4 : 0)
9753       .addOperand(Segment)
9754       .addReg(NextOffsetReg)
9755       .setMemRefs(MMOBegin, MMOEnd);
9756
9757     // Jump to endMBB
9758     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9759       .addMBB(endMBB);
9760   }
9761
9762   //
9763   // Emit code to use overflow area
9764   //
9765
9766   // Load the overflow_area address into a register.
9767   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9768   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9769     .addOperand(Base)
9770     .addOperand(Scale)
9771     .addOperand(Index)
9772     .addDisp(Disp, 8)
9773     .addOperand(Segment)
9774     .setMemRefs(MMOBegin, MMOEnd);
9775
9776   // If we need to align it, do so. Otherwise, just copy the address
9777   // to OverflowDestReg.
9778   if (NeedsAlign) {
9779     // Align the overflow address
9780     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9781     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9782
9783     // aligned_addr = (addr + (align-1)) & ~(align-1)
9784     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9785       .addReg(OverflowAddrReg)
9786       .addImm(Align-1);
9787
9788     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9789       .addReg(TmpReg)
9790       .addImm(~(uint64_t)(Align-1));
9791   } else {
9792     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9793       .addReg(OverflowAddrReg);
9794   }
9795
9796   // Compute the next overflow address after this argument.
9797   // (the overflow address should be kept 8-byte aligned)
9798   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9799   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9800     .addReg(OverflowDestReg)
9801     .addImm(ArgSizeA8);
9802
9803   // Store the new overflow address.
9804   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9805     .addOperand(Base)
9806     .addOperand(Scale)
9807     .addOperand(Index)
9808     .addDisp(Disp, 8)
9809     .addOperand(Segment)
9810     .addReg(NextAddrReg)
9811     .setMemRefs(MMOBegin, MMOEnd);
9812
9813   // If we branched, emit the PHI to the front of endMBB.
9814   if (offsetMBB) {
9815     BuildMI(*endMBB, endMBB->begin(), DL,
9816             TII->get(X86::PHI), DestReg)
9817       .addReg(OffsetDestReg).addMBB(offsetMBB)
9818       .addReg(OverflowDestReg).addMBB(overflowMBB);
9819   }
9820
9821   // Erase the pseudo instruction
9822   MI->eraseFromParent();
9823
9824   return endMBB;
9825 }
9826
9827 MachineBasicBlock *
9828 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9829                                                  MachineInstr *MI,
9830                                                  MachineBasicBlock *MBB) const {
9831   // Emit code to save XMM registers to the stack. The ABI says that the
9832   // number of registers to save is given in %al, so it's theoretically
9833   // possible to do an indirect jump trick to avoid saving all of them,
9834   // however this code takes a simpler approach and just executes all
9835   // of the stores if %al is non-zero. It's less code, and it's probably
9836   // easier on the hardware branch predictor, and stores aren't all that
9837   // expensive anyway.
9838
9839   // Create the new basic blocks. One block contains all the XMM stores,
9840   // and one block is the final destination regardless of whether any
9841   // stores were performed.
9842   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9843   MachineFunction *F = MBB->getParent();
9844   MachineFunction::iterator MBBIter = MBB;
9845   ++MBBIter;
9846   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9847   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9848   F->insert(MBBIter, XMMSaveMBB);
9849   F->insert(MBBIter, EndMBB);
9850
9851   // Transfer the remainder of MBB and its successor edges to EndMBB.
9852   EndMBB->splice(EndMBB->begin(), MBB,
9853                  llvm::next(MachineBasicBlock::iterator(MI)),
9854                  MBB->end());
9855   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9856
9857   // The original block will now fall through to the XMM save block.
9858   MBB->addSuccessor(XMMSaveMBB);
9859   // The XMMSaveMBB will fall through to the end block.
9860   XMMSaveMBB->addSuccessor(EndMBB);
9861
9862   // Now add the instructions.
9863   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9864   DebugLoc DL = MI->getDebugLoc();
9865
9866   unsigned CountReg = MI->getOperand(0).getReg();
9867   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9868   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9869
9870   if (!Subtarget->isTargetWin64()) {
9871     // If %al is 0, branch around the XMM save block.
9872     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9873     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9874     MBB->addSuccessor(EndMBB);
9875   }
9876
9877   // In the XMM save block, save all the XMM argument registers.
9878   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9879     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9880     MachineMemOperand *MMO =
9881       F->getMachineMemOperand(
9882           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9883         MachineMemOperand::MOStore,
9884         /*Size=*/16, /*Align=*/16);
9885     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9886       .addFrameIndex(RegSaveFrameIndex)
9887       .addImm(/*Scale=*/1)
9888       .addReg(/*IndexReg=*/0)
9889       .addImm(/*Disp=*/Offset)
9890       .addReg(/*Segment=*/0)
9891       .addReg(MI->getOperand(i).getReg())
9892       .addMemOperand(MMO);
9893   }
9894
9895   MI->eraseFromParent();   // The pseudo instruction is gone now.
9896
9897   return EndMBB;
9898 }
9899
9900 MachineBasicBlock *
9901 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9902                                      MachineBasicBlock *BB) const {
9903   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9904   DebugLoc DL = MI->getDebugLoc();
9905
9906   // To "insert" a SELECT_CC instruction, we actually have to insert the
9907   // diamond control-flow pattern.  The incoming instruction knows the
9908   // destination vreg to set, the condition code register to branch on, the
9909   // true/false values to select between, and a branch opcode to use.
9910   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9911   MachineFunction::iterator It = BB;
9912   ++It;
9913
9914   //  thisMBB:
9915   //  ...
9916   //   TrueVal = ...
9917   //   cmpTY ccX, r1, r2
9918   //   bCC copy1MBB
9919   //   fallthrough --> copy0MBB
9920   MachineBasicBlock *thisMBB = BB;
9921   MachineFunction *F = BB->getParent();
9922   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9923   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9924   F->insert(It, copy0MBB);
9925   F->insert(It, sinkMBB);
9926
9927   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9928   // live into the sink and copy blocks.
9929   const MachineFunction *MF = BB->getParent();
9930   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9931   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9932
9933   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9934     const MachineOperand &MO = MI->getOperand(I);
9935     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9936     unsigned Reg = MO.getReg();
9937     if (Reg != X86::EFLAGS) continue;
9938     copy0MBB->addLiveIn(Reg);
9939     sinkMBB->addLiveIn(Reg);
9940   }
9941
9942   // Transfer the remainder of BB and its successor edges to sinkMBB.
9943   sinkMBB->splice(sinkMBB->begin(), BB,
9944                   llvm::next(MachineBasicBlock::iterator(MI)),
9945                   BB->end());
9946   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9947
9948   // Add the true and fallthrough blocks as its successors.
9949   BB->addSuccessor(copy0MBB);
9950   BB->addSuccessor(sinkMBB);
9951
9952   // Create the conditional branch instruction.
9953   unsigned Opc =
9954     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9955   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9956
9957   //  copy0MBB:
9958   //   %FalseValue = ...
9959   //   # fallthrough to sinkMBB
9960   copy0MBB->addSuccessor(sinkMBB);
9961
9962   //  sinkMBB:
9963   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9964   //  ...
9965   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9966           TII->get(X86::PHI), MI->getOperand(0).getReg())
9967     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9968     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9969
9970   MI->eraseFromParent();   // The pseudo instruction is gone now.
9971   return sinkMBB;
9972 }
9973
9974 MachineBasicBlock *
9975 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9976                                           MachineBasicBlock *BB) const {
9977   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9978   DebugLoc DL = MI->getDebugLoc();
9979
9980   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9981   // non-trivial part is impdef of ESP.
9982   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9983   // mingw-w64.
9984
9985   const char *StackProbeSymbol =
9986       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9987
9988   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9989     .addExternalSymbol(StackProbeSymbol)
9990     .addReg(X86::EAX, RegState::Implicit)
9991     .addReg(X86::ESP, RegState::Implicit)
9992     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9993     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9994     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9995
9996   MI->eraseFromParent();   // The pseudo instruction is gone now.
9997   return BB;
9998 }
9999
10000 MachineBasicBlock *
10001 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10002                                       MachineBasicBlock *BB) const {
10003   // This is pretty easy.  We're taking the value that we received from
10004   // our load from the relocation, sticking it in either RDI (x86-64)
10005   // or EAX and doing an indirect call.  The return value will then
10006   // be in the normal return register.
10007   const X86InstrInfo *TII
10008     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10009   DebugLoc DL = MI->getDebugLoc();
10010   MachineFunction *F = BB->getParent();
10011
10012   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10013   assert(MI->getOperand(3).isGlobal() && "This should be a global");
10014
10015   if (Subtarget->is64Bit()) {
10016     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10017                                       TII->get(X86::MOV64rm), X86::RDI)
10018     .addReg(X86::RIP)
10019     .addImm(0).addReg(0)
10020     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10021                       MI->getOperand(3).getTargetFlags())
10022     .addReg(0);
10023     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10024     addDirectMem(MIB, X86::RDI);
10025   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10026     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10027                                       TII->get(X86::MOV32rm), X86::EAX)
10028     .addReg(0)
10029     .addImm(0).addReg(0)
10030     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10031                       MI->getOperand(3).getTargetFlags())
10032     .addReg(0);
10033     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10034     addDirectMem(MIB, X86::EAX);
10035   } else {
10036     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10037                                       TII->get(X86::MOV32rm), X86::EAX)
10038     .addReg(TII->getGlobalBaseReg(F))
10039     .addImm(0).addReg(0)
10040     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10041                       MI->getOperand(3).getTargetFlags())
10042     .addReg(0);
10043     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10044     addDirectMem(MIB, X86::EAX);
10045   }
10046
10047   MI->eraseFromParent(); // The pseudo instruction is gone now.
10048   return BB;
10049 }
10050
10051 MachineBasicBlock *
10052 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10053                                                MachineBasicBlock *BB) const {
10054   switch (MI->getOpcode()) {
10055   default: assert(false && "Unexpected instr type to insert");
10056   case X86::WIN_ALLOCA:
10057     return EmitLoweredWinAlloca(MI, BB);
10058   case X86::TLSCall_32:
10059   case X86::TLSCall_64:
10060     return EmitLoweredTLSCall(MI, BB);
10061   case X86::CMOV_GR8:
10062   case X86::CMOV_FR32:
10063   case X86::CMOV_FR64:
10064   case X86::CMOV_V4F32:
10065   case X86::CMOV_V2F64:
10066   case X86::CMOV_V2I64:
10067   case X86::CMOV_GR16:
10068   case X86::CMOV_GR32:
10069   case X86::CMOV_RFP32:
10070   case X86::CMOV_RFP64:
10071   case X86::CMOV_RFP80:
10072     return EmitLoweredSelect(MI, BB);
10073
10074   case X86::FP32_TO_INT16_IN_MEM:
10075   case X86::FP32_TO_INT32_IN_MEM:
10076   case X86::FP32_TO_INT64_IN_MEM:
10077   case X86::FP64_TO_INT16_IN_MEM:
10078   case X86::FP64_TO_INT32_IN_MEM:
10079   case X86::FP64_TO_INT64_IN_MEM:
10080   case X86::FP80_TO_INT16_IN_MEM:
10081   case X86::FP80_TO_INT32_IN_MEM:
10082   case X86::FP80_TO_INT64_IN_MEM: {
10083     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10084     DebugLoc DL = MI->getDebugLoc();
10085
10086     // Change the floating point control register to use "round towards zero"
10087     // mode when truncating to an integer value.
10088     MachineFunction *F = BB->getParent();
10089     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10090     addFrameReference(BuildMI(*BB, MI, DL,
10091                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10092
10093     // Load the old value of the high byte of the control word...
10094     unsigned OldCW =
10095       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10096     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10097                       CWFrameIdx);
10098
10099     // Set the high part to be round to zero...
10100     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10101       .addImm(0xC7F);
10102
10103     // Reload the modified control word now...
10104     addFrameReference(BuildMI(*BB, MI, DL,
10105                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10106
10107     // Restore the memory image of control word to original value
10108     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10109       .addReg(OldCW);
10110
10111     // Get the X86 opcode to use.
10112     unsigned Opc;
10113     switch (MI->getOpcode()) {
10114     default: llvm_unreachable("illegal opcode!");
10115     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10116     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10117     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10118     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10119     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10120     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10121     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10122     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10123     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10124     }
10125
10126     X86AddressMode AM;
10127     MachineOperand &Op = MI->getOperand(0);
10128     if (Op.isReg()) {
10129       AM.BaseType = X86AddressMode::RegBase;
10130       AM.Base.Reg = Op.getReg();
10131     } else {
10132       AM.BaseType = X86AddressMode::FrameIndexBase;
10133       AM.Base.FrameIndex = Op.getIndex();
10134     }
10135     Op = MI->getOperand(1);
10136     if (Op.isImm())
10137       AM.Scale = Op.getImm();
10138     Op = MI->getOperand(2);
10139     if (Op.isImm())
10140       AM.IndexReg = Op.getImm();
10141     Op = MI->getOperand(3);
10142     if (Op.isGlobal()) {
10143       AM.GV = Op.getGlobal();
10144     } else {
10145       AM.Disp = Op.getImm();
10146     }
10147     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10148                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10149
10150     // Reload the original control word now.
10151     addFrameReference(BuildMI(*BB, MI, DL,
10152                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10153
10154     MI->eraseFromParent();   // The pseudo instruction is gone now.
10155     return BB;
10156   }
10157     // String/text processing lowering.
10158   case X86::PCMPISTRM128REG:
10159   case X86::VPCMPISTRM128REG:
10160     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10161   case X86::PCMPISTRM128MEM:
10162   case X86::VPCMPISTRM128MEM:
10163     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10164   case X86::PCMPESTRM128REG:
10165   case X86::VPCMPESTRM128REG:
10166     return EmitPCMP(MI, BB, 5, false /* in mem */);
10167   case X86::PCMPESTRM128MEM:
10168   case X86::VPCMPESTRM128MEM:
10169     return EmitPCMP(MI, BB, 5, true /* in mem */);
10170
10171     // Thread synchronization.
10172   case X86::MONITOR:
10173     return EmitMonitor(MI, BB);  
10174   case X86::MWAIT:
10175     return EmitMwait(MI, BB);
10176
10177     // Atomic Lowering.
10178   case X86::ATOMAND32:
10179     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10180                                                X86::AND32ri, X86::MOV32rm,
10181                                                X86::LCMPXCHG32,
10182                                                X86::NOT32r, X86::EAX,
10183                                                X86::GR32RegisterClass);
10184   case X86::ATOMOR32:
10185     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10186                                                X86::OR32ri, X86::MOV32rm,
10187                                                X86::LCMPXCHG32,
10188                                                X86::NOT32r, X86::EAX,
10189                                                X86::GR32RegisterClass);
10190   case X86::ATOMXOR32:
10191     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10192                                                X86::XOR32ri, X86::MOV32rm,
10193                                                X86::LCMPXCHG32,
10194                                                X86::NOT32r, X86::EAX,
10195                                                X86::GR32RegisterClass);
10196   case X86::ATOMNAND32:
10197     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10198                                                X86::AND32ri, X86::MOV32rm,
10199                                                X86::LCMPXCHG32,
10200                                                X86::NOT32r, X86::EAX,
10201                                                X86::GR32RegisterClass, true);
10202   case X86::ATOMMIN32:
10203     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10204   case X86::ATOMMAX32:
10205     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10206   case X86::ATOMUMIN32:
10207     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10208   case X86::ATOMUMAX32:
10209     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10210
10211   case X86::ATOMAND16:
10212     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10213                                                X86::AND16ri, X86::MOV16rm,
10214                                                X86::LCMPXCHG16,
10215                                                X86::NOT16r, X86::AX,
10216                                                X86::GR16RegisterClass);
10217   case X86::ATOMOR16:
10218     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10219                                                X86::OR16ri, X86::MOV16rm,
10220                                                X86::LCMPXCHG16,
10221                                                X86::NOT16r, X86::AX,
10222                                                X86::GR16RegisterClass);
10223   case X86::ATOMXOR16:
10224     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10225                                                X86::XOR16ri, X86::MOV16rm,
10226                                                X86::LCMPXCHG16,
10227                                                X86::NOT16r, X86::AX,
10228                                                X86::GR16RegisterClass);
10229   case X86::ATOMNAND16:
10230     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10231                                                X86::AND16ri, X86::MOV16rm,
10232                                                X86::LCMPXCHG16,
10233                                                X86::NOT16r, X86::AX,
10234                                                X86::GR16RegisterClass, true);
10235   case X86::ATOMMIN16:
10236     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10237   case X86::ATOMMAX16:
10238     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10239   case X86::ATOMUMIN16:
10240     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10241   case X86::ATOMUMAX16:
10242     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10243
10244   case X86::ATOMAND8:
10245     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10246                                                X86::AND8ri, X86::MOV8rm,
10247                                                X86::LCMPXCHG8,
10248                                                X86::NOT8r, X86::AL,
10249                                                X86::GR8RegisterClass);
10250   case X86::ATOMOR8:
10251     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10252                                                X86::OR8ri, X86::MOV8rm,
10253                                                X86::LCMPXCHG8,
10254                                                X86::NOT8r, X86::AL,
10255                                                X86::GR8RegisterClass);
10256   case X86::ATOMXOR8:
10257     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10258                                                X86::XOR8ri, X86::MOV8rm,
10259                                                X86::LCMPXCHG8,
10260                                                X86::NOT8r, X86::AL,
10261                                                X86::GR8RegisterClass);
10262   case X86::ATOMNAND8:
10263     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10264                                                X86::AND8ri, X86::MOV8rm,
10265                                                X86::LCMPXCHG8,
10266                                                X86::NOT8r, X86::AL,
10267                                                X86::GR8RegisterClass, true);
10268   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10269   // This group is for 64-bit host.
10270   case X86::ATOMAND64:
10271     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10272                                                X86::AND64ri32, X86::MOV64rm,
10273                                                X86::LCMPXCHG64,
10274                                                X86::NOT64r, X86::RAX,
10275                                                X86::GR64RegisterClass);
10276   case X86::ATOMOR64:
10277     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10278                                                X86::OR64ri32, X86::MOV64rm,
10279                                                X86::LCMPXCHG64,
10280                                                X86::NOT64r, X86::RAX,
10281                                                X86::GR64RegisterClass);
10282   case X86::ATOMXOR64:
10283     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10284                                                X86::XOR64ri32, X86::MOV64rm,
10285                                                X86::LCMPXCHG64,
10286                                                X86::NOT64r, X86::RAX,
10287                                                X86::GR64RegisterClass);
10288   case X86::ATOMNAND64:
10289     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10290                                                X86::AND64ri32, X86::MOV64rm,
10291                                                X86::LCMPXCHG64,
10292                                                X86::NOT64r, X86::RAX,
10293                                                X86::GR64RegisterClass, true);
10294   case X86::ATOMMIN64:
10295     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10296   case X86::ATOMMAX64:
10297     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10298   case X86::ATOMUMIN64:
10299     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10300   case X86::ATOMUMAX64:
10301     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10302
10303   // This group does 64-bit operations on a 32-bit host.
10304   case X86::ATOMAND6432:
10305     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10306                                                X86::AND32rr, X86::AND32rr,
10307                                                X86::AND32ri, X86::AND32ri,
10308                                                false);
10309   case X86::ATOMOR6432:
10310     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10311                                                X86::OR32rr, X86::OR32rr,
10312                                                X86::OR32ri, X86::OR32ri,
10313                                                false);
10314   case X86::ATOMXOR6432:
10315     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10316                                                X86::XOR32rr, X86::XOR32rr,
10317                                                X86::XOR32ri, X86::XOR32ri,
10318                                                false);
10319   case X86::ATOMNAND6432:
10320     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10321                                                X86::AND32rr, X86::AND32rr,
10322                                                X86::AND32ri, X86::AND32ri,
10323                                                true);
10324   case X86::ATOMADD6432:
10325     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10326                                                X86::ADD32rr, X86::ADC32rr,
10327                                                X86::ADD32ri, X86::ADC32ri,
10328                                                false);
10329   case X86::ATOMSUB6432:
10330     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10331                                                X86::SUB32rr, X86::SBB32rr,
10332                                                X86::SUB32ri, X86::SBB32ri,
10333                                                false);
10334   case X86::ATOMSWAP6432:
10335     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10336                                                X86::MOV32rr, X86::MOV32rr,
10337                                                X86::MOV32ri, X86::MOV32ri,
10338                                                false);
10339   case X86::VASTART_SAVE_XMM_REGS:
10340     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10341
10342   case X86::VAARG_64:
10343     return EmitVAARG64WithCustomInserter(MI, BB);
10344   }
10345 }
10346
10347 //===----------------------------------------------------------------------===//
10348 //                           X86 Optimization Hooks
10349 //===----------------------------------------------------------------------===//
10350
10351 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10352                                                        const APInt &Mask,
10353                                                        APInt &KnownZero,
10354                                                        APInt &KnownOne,
10355                                                        const SelectionDAG &DAG,
10356                                                        unsigned Depth) const {
10357   unsigned Opc = Op.getOpcode();
10358   assert((Opc >= ISD::BUILTIN_OP_END ||
10359           Opc == ISD::INTRINSIC_WO_CHAIN ||
10360           Opc == ISD::INTRINSIC_W_CHAIN ||
10361           Opc == ISD::INTRINSIC_VOID) &&
10362          "Should use MaskedValueIsZero if you don't know whether Op"
10363          " is a target node!");
10364
10365   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10366   switch (Opc) {
10367   default: break;
10368   case X86ISD::ADD:
10369   case X86ISD::SUB:
10370   case X86ISD::ADC:
10371   case X86ISD::SBB:
10372   case X86ISD::SMUL:
10373   case X86ISD::UMUL:
10374   case X86ISD::INC:
10375   case X86ISD::DEC:
10376   case X86ISD::OR:
10377   case X86ISD::XOR:
10378   case X86ISD::AND:
10379     // These nodes' second result is a boolean.
10380     if (Op.getResNo() == 0)
10381       break;
10382     // Fallthrough
10383   case X86ISD::SETCC:
10384     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10385                                        Mask.getBitWidth() - 1);
10386     break;
10387   }
10388 }
10389
10390 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10391                                                          unsigned Depth) const {
10392   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10393   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10394     return Op.getValueType().getScalarType().getSizeInBits();
10395
10396   // Fallback case.
10397   return 1;
10398 }
10399
10400 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10401 /// node is a GlobalAddress + offset.
10402 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10403                                        const GlobalValue* &GA,
10404                                        int64_t &Offset) const {
10405   if (N->getOpcode() == X86ISD::Wrapper) {
10406     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10407       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10408       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10409       return true;
10410     }
10411   }
10412   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10413 }
10414
10415 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10416 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10417 /// if the load addresses are consecutive, non-overlapping, and in the right
10418 /// order.
10419 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10420                                      TargetLowering::DAGCombinerInfo &DCI) {
10421   DebugLoc dl = N->getDebugLoc();
10422   EVT VT = N->getValueType(0);
10423
10424   if (VT.getSizeInBits() != 128)
10425     return SDValue();
10426
10427   // Don't create instructions with illegal types after legalize types has run.
10428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10429   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10430     return SDValue();
10431
10432   SmallVector<SDValue, 16> Elts;
10433   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10434     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10435
10436   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10437 }
10438
10439 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10440 /// generation and convert it from being a bunch of shuffles and extracts
10441 /// to a simple store and scalar loads to extract the elements.
10442 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10443                                                 const TargetLowering &TLI) {
10444   SDValue InputVector = N->getOperand(0);
10445
10446   // Only operate on vectors of 4 elements, where the alternative shuffling
10447   // gets to be more expensive.
10448   if (InputVector.getValueType() != MVT::v4i32)
10449     return SDValue();
10450
10451   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10452   // single use which is a sign-extend or zero-extend, and all elements are
10453   // used.
10454   SmallVector<SDNode *, 4> Uses;
10455   unsigned ExtractedElements = 0;
10456   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10457        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10458     if (UI.getUse().getResNo() != InputVector.getResNo())
10459       return SDValue();
10460
10461     SDNode *Extract = *UI;
10462     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10463       return SDValue();
10464
10465     if (Extract->getValueType(0) != MVT::i32)
10466       return SDValue();
10467     if (!Extract->hasOneUse())
10468       return SDValue();
10469     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10470         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10471       return SDValue();
10472     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10473       return SDValue();
10474
10475     // Record which element was extracted.
10476     ExtractedElements |=
10477       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10478
10479     Uses.push_back(Extract);
10480   }
10481
10482   // If not all the elements were used, this may not be worthwhile.
10483   if (ExtractedElements != 15)
10484     return SDValue();
10485
10486   // Ok, we've now decided to do the transformation.
10487   DebugLoc dl = InputVector.getDebugLoc();
10488
10489   // Store the value to a temporary stack slot.
10490   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10491   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10492                             MachinePointerInfo(), false, false, 0);
10493
10494   // Replace each use (extract) with a load of the appropriate element.
10495   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10496        UE = Uses.end(); UI != UE; ++UI) {
10497     SDNode *Extract = *UI;
10498
10499     // Compute the element's address.
10500     SDValue Idx = Extract->getOperand(1);
10501     unsigned EltSize =
10502         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10503     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10504     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10505
10506     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10507                                      StackPtr, OffsetVal);
10508
10509     // Load the scalar.
10510     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10511                                      ScalarAddr, MachinePointerInfo(),
10512                                      false, false, 0);
10513
10514     // Replace the exact with the load.
10515     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10516   }
10517
10518   // The replacement was made in place; don't return anything.
10519   return SDValue();
10520 }
10521
10522 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10523 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10524                                     const X86Subtarget *Subtarget) {
10525   DebugLoc DL = N->getDebugLoc();
10526   SDValue Cond = N->getOperand(0);
10527   // Get the LHS/RHS of the select.
10528   SDValue LHS = N->getOperand(1);
10529   SDValue RHS = N->getOperand(2);
10530
10531   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10532   // instructions match the semantics of the common C idiom x<y?x:y but not
10533   // x<=y?x:y, because of how they handle negative zero (which can be
10534   // ignored in unsafe-math mode).
10535   if (Subtarget->hasSSE2() &&
10536       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10537       Cond.getOpcode() == ISD::SETCC) {
10538     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10539
10540     unsigned Opcode = 0;
10541     // Check for x CC y ? x : y.
10542     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10543         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10544       switch (CC) {
10545       default: break;
10546       case ISD::SETULT:
10547         // Converting this to a min would handle NaNs incorrectly, and swapping
10548         // the operands would cause it to handle comparisons between positive
10549         // and negative zero incorrectly.
10550         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10551           if (!UnsafeFPMath &&
10552               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10553             break;
10554           std::swap(LHS, RHS);
10555         }
10556         Opcode = X86ISD::FMIN;
10557         break;
10558       case ISD::SETOLE:
10559         // Converting this to a min would handle comparisons between positive
10560         // and negative zero incorrectly.
10561         if (!UnsafeFPMath &&
10562             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10563           break;
10564         Opcode = X86ISD::FMIN;
10565         break;
10566       case ISD::SETULE:
10567         // Converting this to a min would handle both negative zeros and NaNs
10568         // incorrectly, but we can swap the operands to fix both.
10569         std::swap(LHS, RHS);
10570       case ISD::SETOLT:
10571       case ISD::SETLT:
10572       case ISD::SETLE:
10573         Opcode = X86ISD::FMIN;
10574         break;
10575
10576       case ISD::SETOGE:
10577         // Converting this to a max would handle comparisons between positive
10578         // and negative zero incorrectly.
10579         if (!UnsafeFPMath &&
10580             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10581           break;
10582         Opcode = X86ISD::FMAX;
10583         break;
10584       case ISD::SETUGT:
10585         // Converting this to a max would handle NaNs incorrectly, and swapping
10586         // the operands would cause it to handle comparisons between positive
10587         // and negative zero incorrectly.
10588         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10589           if (!UnsafeFPMath &&
10590               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10591             break;
10592           std::swap(LHS, RHS);
10593         }
10594         Opcode = X86ISD::FMAX;
10595         break;
10596       case ISD::SETUGE:
10597         // Converting this to a max would handle both negative zeros and NaNs
10598         // incorrectly, but we can swap the operands to fix both.
10599         std::swap(LHS, RHS);
10600       case ISD::SETOGT:
10601       case ISD::SETGT:
10602       case ISD::SETGE:
10603         Opcode = X86ISD::FMAX;
10604         break;
10605       }
10606     // Check for x CC y ? y : x -- a min/max with reversed arms.
10607     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10608                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10609       switch (CC) {
10610       default: break;
10611       case ISD::SETOGE:
10612         // Converting this to a min would handle comparisons between positive
10613         // and negative zero incorrectly, and swapping the operands would
10614         // cause it to handle NaNs incorrectly.
10615         if (!UnsafeFPMath &&
10616             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10617           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10618             break;
10619           std::swap(LHS, RHS);
10620         }
10621         Opcode = X86ISD::FMIN;
10622         break;
10623       case ISD::SETUGT:
10624         // Converting this to a min would handle NaNs incorrectly.
10625         if (!UnsafeFPMath &&
10626             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10627           break;
10628         Opcode = X86ISD::FMIN;
10629         break;
10630       case ISD::SETUGE:
10631         // Converting this to a min would handle both negative zeros and NaNs
10632         // incorrectly, but we can swap the operands to fix both.
10633         std::swap(LHS, RHS);
10634       case ISD::SETOGT:
10635       case ISD::SETGT:
10636       case ISD::SETGE:
10637         Opcode = X86ISD::FMIN;
10638         break;
10639
10640       case ISD::SETULT:
10641         // Converting this to a max would handle NaNs incorrectly.
10642         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10643           break;
10644         Opcode = X86ISD::FMAX;
10645         break;
10646       case ISD::SETOLE:
10647         // Converting this to a max would handle comparisons between positive
10648         // and negative zero incorrectly, and swapping the operands would
10649         // cause it to handle NaNs incorrectly.
10650         if (!UnsafeFPMath &&
10651             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10652           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10653             break;
10654           std::swap(LHS, RHS);
10655         }
10656         Opcode = X86ISD::FMAX;
10657         break;
10658       case ISD::SETULE:
10659         // Converting this to a max would handle both negative zeros and NaNs
10660         // incorrectly, but we can swap the operands to fix both.
10661         std::swap(LHS, RHS);
10662       case ISD::SETOLT:
10663       case ISD::SETLT:
10664       case ISD::SETLE:
10665         Opcode = X86ISD::FMAX;
10666         break;
10667       }
10668     }
10669
10670     if (Opcode)
10671       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10672   }
10673
10674   // If this is a select between two integer constants, try to do some
10675   // optimizations.
10676   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10677     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10678       // Don't do this for crazy integer types.
10679       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10680         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10681         // so that TrueC (the true value) is larger than FalseC.
10682         bool NeedsCondInvert = false;
10683
10684         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10685             // Efficiently invertible.
10686             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10687              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10688               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10689           NeedsCondInvert = true;
10690           std::swap(TrueC, FalseC);
10691         }
10692
10693         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10694         if (FalseC->getAPIntValue() == 0 &&
10695             TrueC->getAPIntValue().isPowerOf2()) {
10696           if (NeedsCondInvert) // Invert the condition if needed.
10697             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10698                                DAG.getConstant(1, Cond.getValueType()));
10699
10700           // Zero extend the condition if needed.
10701           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10702
10703           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10704           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10705                              DAG.getConstant(ShAmt, MVT::i8));
10706         }
10707
10708         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10709         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10710           if (NeedsCondInvert) // Invert the condition if needed.
10711             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10712                                DAG.getConstant(1, Cond.getValueType()));
10713
10714           // Zero extend the condition if needed.
10715           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10716                              FalseC->getValueType(0), Cond);
10717           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10718                              SDValue(FalseC, 0));
10719         }
10720
10721         // Optimize cases that will turn into an LEA instruction.  This requires
10722         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10723         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10724           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10725           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10726
10727           bool isFastMultiplier = false;
10728           if (Diff < 10) {
10729             switch ((unsigned char)Diff) {
10730               default: break;
10731               case 1:  // result = add base, cond
10732               case 2:  // result = lea base(    , cond*2)
10733               case 3:  // result = lea base(cond, cond*2)
10734               case 4:  // result = lea base(    , cond*4)
10735               case 5:  // result = lea base(cond, cond*4)
10736               case 8:  // result = lea base(    , cond*8)
10737               case 9:  // result = lea base(cond, cond*8)
10738                 isFastMultiplier = true;
10739                 break;
10740             }
10741           }
10742
10743           if (isFastMultiplier) {
10744             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10745             if (NeedsCondInvert) // Invert the condition if needed.
10746               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10747                                  DAG.getConstant(1, Cond.getValueType()));
10748
10749             // Zero extend the condition if needed.
10750             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10751                                Cond);
10752             // Scale the condition by the difference.
10753             if (Diff != 1)
10754               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10755                                  DAG.getConstant(Diff, Cond.getValueType()));
10756
10757             // Add the base if non-zero.
10758             if (FalseC->getAPIntValue() != 0)
10759               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10760                                  SDValue(FalseC, 0));
10761             return Cond;
10762           }
10763         }
10764       }
10765   }
10766
10767   return SDValue();
10768 }
10769
10770 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10771 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10772                                   TargetLowering::DAGCombinerInfo &DCI) {
10773   DebugLoc DL = N->getDebugLoc();
10774
10775   // If the flag operand isn't dead, don't touch this CMOV.
10776   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10777     return SDValue();
10778
10779   // If this is a select between two integer constants, try to do some
10780   // optimizations.  Note that the operands are ordered the opposite of SELECT
10781   // operands.
10782   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10783     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10784       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10785       // larger than FalseC (the false value).
10786       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10787
10788       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10789         CC = X86::GetOppositeBranchCondition(CC);
10790         std::swap(TrueC, FalseC);
10791       }
10792
10793       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10794       // This is efficient for any integer data type (including i8/i16) and
10795       // shift amount.
10796       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10797         SDValue Cond = N->getOperand(3);
10798         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10799                            DAG.getConstant(CC, MVT::i8), Cond);
10800
10801         // Zero extend the condition if needed.
10802         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10803
10804         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10805         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10806                            DAG.getConstant(ShAmt, MVT::i8));
10807         if (N->getNumValues() == 2)  // Dead flag value?
10808           return DCI.CombineTo(N, Cond, SDValue());
10809         return Cond;
10810       }
10811
10812       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10813       // for any integer data type, including i8/i16.
10814       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
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,
10821                            FalseC->getValueType(0), Cond);
10822         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10823                            SDValue(FalseC, 0));
10824
10825         if (N->getNumValues() == 2)  // Dead flag value?
10826           return DCI.CombineTo(N, Cond, SDValue());
10827         return Cond;
10828       }
10829
10830       // Optimize cases that will turn into an LEA instruction.  This requires
10831       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10832       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10833         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10834         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10835
10836         bool isFastMultiplier = false;
10837         if (Diff < 10) {
10838           switch ((unsigned char)Diff) {
10839           default: break;
10840           case 1:  // result = add base, cond
10841           case 2:  // result = lea base(    , cond*2)
10842           case 3:  // result = lea base(cond, cond*2)
10843           case 4:  // result = lea base(    , cond*4)
10844           case 5:  // result = lea base(cond, cond*4)
10845           case 8:  // result = lea base(    , cond*8)
10846           case 9:  // result = lea base(cond, cond*8)
10847             isFastMultiplier = true;
10848             break;
10849           }
10850         }
10851
10852         if (isFastMultiplier) {
10853           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10854           SDValue Cond = N->getOperand(3);
10855           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10856                              DAG.getConstant(CC, MVT::i8), Cond);
10857           // Zero extend the condition if needed.
10858           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10859                              Cond);
10860           // Scale the condition by the difference.
10861           if (Diff != 1)
10862             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10863                                DAG.getConstant(Diff, Cond.getValueType()));
10864
10865           // Add the base if non-zero.
10866           if (FalseC->getAPIntValue() != 0)
10867             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10868                                SDValue(FalseC, 0));
10869           if (N->getNumValues() == 2)  // Dead flag value?
10870             return DCI.CombineTo(N, Cond, SDValue());
10871           return Cond;
10872         }
10873       }
10874     }
10875   }
10876   return SDValue();
10877 }
10878
10879
10880 /// PerformMulCombine - Optimize a single multiply with constant into two
10881 /// in order to implement it with two cheaper instructions, e.g.
10882 /// LEA + SHL, LEA + LEA.
10883 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10884                                  TargetLowering::DAGCombinerInfo &DCI) {
10885   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10886     return SDValue();
10887
10888   EVT VT = N->getValueType(0);
10889   if (VT != MVT::i64)
10890     return SDValue();
10891
10892   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10893   if (!C)
10894     return SDValue();
10895   uint64_t MulAmt = C->getZExtValue();
10896   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10897     return SDValue();
10898
10899   uint64_t MulAmt1 = 0;
10900   uint64_t MulAmt2 = 0;
10901   if ((MulAmt % 9) == 0) {
10902     MulAmt1 = 9;
10903     MulAmt2 = MulAmt / 9;
10904   } else if ((MulAmt % 5) == 0) {
10905     MulAmt1 = 5;
10906     MulAmt2 = MulAmt / 5;
10907   } else if ((MulAmt % 3) == 0) {
10908     MulAmt1 = 3;
10909     MulAmt2 = MulAmt / 3;
10910   }
10911   if (MulAmt2 &&
10912       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10913     DebugLoc DL = N->getDebugLoc();
10914
10915     if (isPowerOf2_64(MulAmt2) &&
10916         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10917       // If second multiplifer is pow2, issue it first. We want the multiply by
10918       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10919       // is an add.
10920       std::swap(MulAmt1, MulAmt2);
10921
10922     SDValue NewMul;
10923     if (isPowerOf2_64(MulAmt1))
10924       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10925                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10926     else
10927       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10928                            DAG.getConstant(MulAmt1, VT));
10929
10930     if (isPowerOf2_64(MulAmt2))
10931       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10932                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10933     else
10934       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10935                            DAG.getConstant(MulAmt2, VT));
10936
10937     // Do not add new nodes to DAG combiner worklist.
10938     DCI.CombineTo(N, NewMul, false);
10939   }
10940   return SDValue();
10941 }
10942
10943 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10944   SDValue N0 = N->getOperand(0);
10945   SDValue N1 = N->getOperand(1);
10946   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10947   EVT VT = N0.getValueType();
10948
10949   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10950   // since the result of setcc_c is all zero's or all ones.
10951   if (N1C && N0.getOpcode() == ISD::AND &&
10952       N0.getOperand(1).getOpcode() == ISD::Constant) {
10953     SDValue N00 = N0.getOperand(0);
10954     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10955         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10956           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10957          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10958       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10959       APInt ShAmt = N1C->getAPIntValue();
10960       Mask = Mask.shl(ShAmt);
10961       if (Mask != 0)
10962         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10963                            N00, DAG.getConstant(Mask, VT));
10964     }
10965   }
10966
10967   return SDValue();
10968 }
10969
10970 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10971 ///                       when possible.
10972 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10973                                    const X86Subtarget *Subtarget) {
10974   EVT VT = N->getValueType(0);
10975   if (!VT.isVector() && VT.isInteger() &&
10976       N->getOpcode() == ISD::SHL)
10977     return PerformSHLCombine(N, DAG);
10978
10979   // On X86 with SSE2 support, we can transform this to a vector shift if
10980   // all elements are shifted by the same amount.  We can't do this in legalize
10981   // because the a constant vector is typically transformed to a constant pool
10982   // so we have no knowledge of the shift amount.
10983   if (!Subtarget->hasSSE2())
10984     return SDValue();
10985
10986   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10987     return SDValue();
10988
10989   SDValue ShAmtOp = N->getOperand(1);
10990   EVT EltVT = VT.getVectorElementType();
10991   DebugLoc DL = N->getDebugLoc();
10992   SDValue BaseShAmt = SDValue();
10993   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10994     unsigned NumElts = VT.getVectorNumElements();
10995     unsigned i = 0;
10996     for (; i != NumElts; ++i) {
10997       SDValue Arg = ShAmtOp.getOperand(i);
10998       if (Arg.getOpcode() == ISD::UNDEF) continue;
10999       BaseShAmt = Arg;
11000       break;
11001     }
11002     for (; i != NumElts; ++i) {
11003       SDValue Arg = ShAmtOp.getOperand(i);
11004       if (Arg.getOpcode() == ISD::UNDEF) continue;
11005       if (Arg != BaseShAmt) {
11006         return SDValue();
11007       }
11008     }
11009   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11010              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11011     SDValue InVec = ShAmtOp.getOperand(0);
11012     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11013       unsigned NumElts = InVec.getValueType().getVectorNumElements();
11014       unsigned i = 0;
11015       for (; i != NumElts; ++i) {
11016         SDValue Arg = InVec.getOperand(i);
11017         if (Arg.getOpcode() == ISD::UNDEF) continue;
11018         BaseShAmt = Arg;
11019         break;
11020       }
11021     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11022        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11023          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11024          if (C->getZExtValue() == SplatIdx)
11025            BaseShAmt = InVec.getOperand(1);
11026        }
11027     }
11028     if (BaseShAmt.getNode() == 0)
11029       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11030                               DAG.getIntPtrConstant(0));
11031   } else
11032     return SDValue();
11033
11034   // The shift amount is an i32.
11035   if (EltVT.bitsGT(MVT::i32))
11036     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11037   else if (EltVT.bitsLT(MVT::i32))
11038     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11039
11040   // The shift amount is identical so we can do a vector shift.
11041   SDValue  ValOp = N->getOperand(0);
11042   switch (N->getOpcode()) {
11043   default:
11044     llvm_unreachable("Unknown shift opcode!");
11045     break;
11046   case ISD::SHL:
11047     if (VT == MVT::v2i64)
11048       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11049                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11050                          ValOp, BaseShAmt);
11051     if (VT == MVT::v4i32)
11052       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11053                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11054                          ValOp, BaseShAmt);
11055     if (VT == MVT::v8i16)
11056       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11057                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11058                          ValOp, BaseShAmt);
11059     break;
11060   case ISD::SRA:
11061     if (VT == MVT::v4i32)
11062       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11063                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11064                          ValOp, BaseShAmt);
11065     if (VT == MVT::v8i16)
11066       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11067                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11068                          ValOp, BaseShAmt);
11069     break;
11070   case ISD::SRL:
11071     if (VT == MVT::v2i64)
11072       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11073                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11074                          ValOp, BaseShAmt);
11075     if (VT == MVT::v4i32)
11076       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11077                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11078                          ValOp, BaseShAmt);
11079     if (VT ==  MVT::v8i16)
11080       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11081                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11082                          ValOp, BaseShAmt);
11083     break;
11084   }
11085   return SDValue();
11086 }
11087
11088
11089 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11090                                  TargetLowering::DAGCombinerInfo &DCI,
11091                                  const X86Subtarget *Subtarget) {
11092   if (DCI.isBeforeLegalizeOps())
11093     return SDValue();
11094   
11095   // Want to form PANDN nodes, in the hopes of then easily combining them with
11096   // OR and AND nodes to form PBLEND/PSIGN.
11097   EVT VT = N->getValueType(0);
11098   if (VT != MVT::v2i64)
11099     return SDValue();
11100   
11101   SDValue N0 = N->getOperand(0);
11102   SDValue N1 = N->getOperand(1);
11103   DebugLoc DL = N->getDebugLoc();
11104   
11105   // Check LHS for vnot
11106   if (N0.getOpcode() == ISD::XOR && 
11107       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11108     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11109
11110   // Check RHS for vnot
11111   if (N1.getOpcode() == ISD::XOR &&
11112       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11113     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11114   
11115   return SDValue();
11116 }
11117
11118 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11119                                 TargetLowering::DAGCombinerInfo &DCI,
11120                                 const X86Subtarget *Subtarget) {
11121   if (DCI.isBeforeLegalizeOps())
11122     return SDValue();
11123
11124   EVT VT = N->getValueType(0);
11125   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11126     return SDValue();
11127
11128   SDValue N0 = N->getOperand(0);
11129   SDValue N1 = N->getOperand(1);
11130   
11131   // look for psign/blend
11132   if (Subtarget->hasSSSE3()) {
11133     if (VT == MVT::v2i64) {
11134       // Canonicalize pandn to RHS
11135       if (N0.getOpcode() == X86ISD::PANDN)
11136         std::swap(N0, N1);
11137       // or (and (m, x), (pandn m, y))
11138       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11139         SDValue Mask = N1.getOperand(0);
11140         SDValue X    = N1.getOperand(1);
11141         SDValue Y;
11142         if (N0.getOperand(0) == Mask)
11143           Y = N0.getOperand(1);
11144         if (N0.getOperand(1) == Mask)
11145           Y = N0.getOperand(0);
11146         
11147         // Check to see if the mask appeared in both the AND and PANDN and
11148         if (!Y.getNode())
11149           return SDValue();
11150         
11151         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11152         if (Mask.getOpcode() != ISD::BITCAST ||
11153             X.getOpcode() != ISD::BITCAST ||
11154             Y.getOpcode() != ISD::BITCAST)
11155           return SDValue();
11156         
11157         // Look through mask bitcast.
11158         Mask = Mask.getOperand(0);
11159         EVT MaskVT = Mask.getValueType();
11160
11161         // Validate that the Mask operand is a vector sra node.  The sra node
11162         // will be an intrinsic.
11163         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11164           return SDValue();
11165         
11166         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11167         // there is no psrai.b
11168         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11169         case Intrinsic::x86_sse2_psrai_w:
11170         case Intrinsic::x86_sse2_psrai_d:
11171           break;
11172         default: return SDValue();
11173         }
11174         
11175         // Check that the SRA is all signbits.
11176         SDValue SraC = Mask.getOperand(2);
11177         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11178         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11179         if ((SraAmt + 1) != EltBits)
11180           return SDValue();
11181         
11182         DebugLoc DL = N->getDebugLoc();
11183
11184         // Now we know we at least have a plendvb with the mask val.  See if
11185         // we can form a psignb/w/d.
11186         // psign = x.type == y.type == mask.type && y = sub(0, x);
11187         X = X.getOperand(0);
11188         Y = Y.getOperand(0);
11189         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11190             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11191             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11192           unsigned Opc = 0;
11193           switch (EltBits) {
11194           case 8: Opc = X86ISD::PSIGNB; break;
11195           case 16: Opc = X86ISD::PSIGNW; break;
11196           case 32: Opc = X86ISD::PSIGND; break;
11197           default: break;
11198           }
11199           if (Opc) {
11200             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11201             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11202           }
11203         }
11204         // PBLENDVB only available on SSE 4.1
11205         if (!Subtarget->hasSSE41())
11206           return SDValue();
11207         
11208         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11209         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11210         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11211         Mask = DAG.getNode(X86ISD::PBLENDVB, DL, MVT::v16i8, X, Y, Mask);
11212         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11213       }
11214     }
11215   }
11216   
11217   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11218   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11219     std::swap(N0, N1);
11220   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11221     return SDValue();
11222   if (!N0.hasOneUse() || !N1.hasOneUse())
11223     return SDValue();
11224
11225   SDValue ShAmt0 = N0.getOperand(1);
11226   if (ShAmt0.getValueType() != MVT::i8)
11227     return SDValue();
11228   SDValue ShAmt1 = N1.getOperand(1);
11229   if (ShAmt1.getValueType() != MVT::i8)
11230     return SDValue();
11231   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11232     ShAmt0 = ShAmt0.getOperand(0);
11233   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11234     ShAmt1 = ShAmt1.getOperand(0);
11235
11236   DebugLoc DL = N->getDebugLoc();
11237   unsigned Opc = X86ISD::SHLD;
11238   SDValue Op0 = N0.getOperand(0);
11239   SDValue Op1 = N1.getOperand(0);
11240   if (ShAmt0.getOpcode() == ISD::SUB) {
11241     Opc = X86ISD::SHRD;
11242     std::swap(Op0, Op1);
11243     std::swap(ShAmt0, ShAmt1);
11244   }
11245
11246   unsigned Bits = VT.getSizeInBits();
11247   if (ShAmt1.getOpcode() == ISD::SUB) {
11248     SDValue Sum = ShAmt1.getOperand(0);
11249     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11250       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11251       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11252         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11253       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11254         return DAG.getNode(Opc, DL, VT,
11255                            Op0, Op1,
11256                            DAG.getNode(ISD::TRUNCATE, DL,
11257                                        MVT::i8, ShAmt0));
11258     }
11259   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11260     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11261     if (ShAmt0C &&
11262         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11263       return DAG.getNode(Opc, DL, VT,
11264                          N0.getOperand(0), N1.getOperand(0),
11265                          DAG.getNode(ISD::TRUNCATE, DL,
11266                                        MVT::i8, ShAmt0));
11267   }
11268   
11269   return SDValue();
11270 }
11271
11272 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11273 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11274                                    const X86Subtarget *Subtarget) {
11275   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11276   // the FP state in cases where an emms may be missing.
11277   // A preferable solution to the general problem is to figure out the right
11278   // places to insert EMMS.  This qualifies as a quick hack.
11279
11280   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11281   StoreSDNode *St = cast<StoreSDNode>(N);
11282   EVT VT = St->getValue().getValueType();
11283   if (VT.getSizeInBits() != 64)
11284     return SDValue();
11285
11286   const Function *F = DAG.getMachineFunction().getFunction();
11287   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11288   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11289     && Subtarget->hasSSE2();
11290   if ((VT.isVector() ||
11291        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11292       isa<LoadSDNode>(St->getValue()) &&
11293       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11294       St->getChain().hasOneUse() && !St->isVolatile()) {
11295     SDNode* LdVal = St->getValue().getNode();
11296     LoadSDNode *Ld = 0;
11297     int TokenFactorIndex = -1;
11298     SmallVector<SDValue, 8> Ops;
11299     SDNode* ChainVal = St->getChain().getNode();
11300     // Must be a store of a load.  We currently handle two cases:  the load
11301     // is a direct child, and it's under an intervening TokenFactor.  It is
11302     // possible to dig deeper under nested TokenFactors.
11303     if (ChainVal == LdVal)
11304       Ld = cast<LoadSDNode>(St->getChain());
11305     else if (St->getValue().hasOneUse() &&
11306              ChainVal->getOpcode() == ISD::TokenFactor) {
11307       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11308         if (ChainVal->getOperand(i).getNode() == LdVal) {
11309           TokenFactorIndex = i;
11310           Ld = cast<LoadSDNode>(St->getValue());
11311         } else
11312           Ops.push_back(ChainVal->getOperand(i));
11313       }
11314     }
11315
11316     if (!Ld || !ISD::isNormalLoad(Ld))
11317       return SDValue();
11318
11319     // If this is not the MMX case, i.e. we are just turning i64 load/store
11320     // into f64 load/store, avoid the transformation if there are multiple
11321     // uses of the loaded value.
11322     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11323       return SDValue();
11324
11325     DebugLoc LdDL = Ld->getDebugLoc();
11326     DebugLoc StDL = N->getDebugLoc();
11327     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11328     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11329     // pair instead.
11330     if (Subtarget->is64Bit() || F64IsLegal) {
11331       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11332       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11333                                   Ld->getPointerInfo(), Ld->isVolatile(),
11334                                   Ld->isNonTemporal(), Ld->getAlignment());
11335       SDValue NewChain = NewLd.getValue(1);
11336       if (TokenFactorIndex != -1) {
11337         Ops.push_back(NewChain);
11338         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11339                                Ops.size());
11340       }
11341       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11342                           St->getPointerInfo(),
11343                           St->isVolatile(), St->isNonTemporal(),
11344                           St->getAlignment());
11345     }
11346
11347     // Otherwise, lower to two pairs of 32-bit loads / stores.
11348     SDValue LoAddr = Ld->getBasePtr();
11349     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11350                                  DAG.getConstant(4, MVT::i32));
11351
11352     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11353                                Ld->getPointerInfo(),
11354                                Ld->isVolatile(), Ld->isNonTemporal(),
11355                                Ld->getAlignment());
11356     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11357                                Ld->getPointerInfo().getWithOffset(4),
11358                                Ld->isVolatile(), Ld->isNonTemporal(),
11359                                MinAlign(Ld->getAlignment(), 4));
11360
11361     SDValue NewChain = LoLd.getValue(1);
11362     if (TokenFactorIndex != -1) {
11363       Ops.push_back(LoLd);
11364       Ops.push_back(HiLd);
11365       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11366                              Ops.size());
11367     }
11368
11369     LoAddr = St->getBasePtr();
11370     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11371                          DAG.getConstant(4, MVT::i32));
11372
11373     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11374                                 St->getPointerInfo(),
11375                                 St->isVolatile(), St->isNonTemporal(),
11376                                 St->getAlignment());
11377     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11378                                 St->getPointerInfo().getWithOffset(4),
11379                                 St->isVolatile(),
11380                                 St->isNonTemporal(),
11381                                 MinAlign(St->getAlignment(), 4));
11382     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11383   }
11384   return SDValue();
11385 }
11386
11387 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11388 /// X86ISD::FXOR nodes.
11389 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11390   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11391   // F[X]OR(0.0, x) -> x
11392   // F[X]OR(x, 0.0) -> x
11393   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11394     if (C->getValueAPF().isPosZero())
11395       return N->getOperand(1);
11396   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11397     if (C->getValueAPF().isPosZero())
11398       return N->getOperand(0);
11399   return SDValue();
11400 }
11401
11402 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11403 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11404   // FAND(0.0, x) -> 0.0
11405   // FAND(x, 0.0) -> 0.0
11406   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11407     if (C->getValueAPF().isPosZero())
11408       return N->getOperand(0);
11409   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11410     if (C->getValueAPF().isPosZero())
11411       return N->getOperand(1);
11412   return SDValue();
11413 }
11414
11415 static SDValue PerformBTCombine(SDNode *N,
11416                                 SelectionDAG &DAG,
11417                                 TargetLowering::DAGCombinerInfo &DCI) {
11418   // BT ignores high bits in the bit index operand.
11419   SDValue Op1 = N->getOperand(1);
11420   if (Op1.hasOneUse()) {
11421     unsigned BitWidth = Op1.getValueSizeInBits();
11422     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11423     APInt KnownZero, KnownOne;
11424     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11425                                           !DCI.isBeforeLegalizeOps());
11426     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11427     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11428         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11429       DCI.CommitTargetLoweringOpt(TLO);
11430   }
11431   return SDValue();
11432 }
11433
11434 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11435   SDValue Op = N->getOperand(0);
11436   if (Op.getOpcode() == ISD::BITCAST)
11437     Op = Op.getOperand(0);
11438   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11439   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11440       VT.getVectorElementType().getSizeInBits() ==
11441       OpVT.getVectorElementType().getSizeInBits()) {
11442     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11443   }
11444   return SDValue();
11445 }
11446
11447 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11448   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11449   //           (and (i32 x86isd::setcc_carry), 1)
11450   // This eliminates the zext. This transformation is necessary because
11451   // ISD::SETCC is always legalized to i8.
11452   DebugLoc dl = N->getDebugLoc();
11453   SDValue N0 = N->getOperand(0);
11454   EVT VT = N->getValueType(0);
11455   if (N0.getOpcode() == ISD::AND &&
11456       N0.hasOneUse() &&
11457       N0.getOperand(0).hasOneUse()) {
11458     SDValue N00 = N0.getOperand(0);
11459     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11460       return SDValue();
11461     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11462     if (!C || C->getZExtValue() != 1)
11463       return SDValue();
11464     return DAG.getNode(ISD::AND, dl, VT,
11465                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11466                                    N00.getOperand(0), N00.getOperand(1)),
11467                        DAG.getConstant(1, VT));
11468   }
11469
11470   return SDValue();
11471 }
11472
11473 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11474 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11475   unsigned X86CC = N->getConstantOperandVal(0);
11476   SDValue EFLAG = N->getOperand(1);
11477   DebugLoc DL = N->getDebugLoc();
11478   
11479   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11480   // a zext and produces an all-ones bit which is more useful than 0/1 in some
11481   // cases.
11482   if (X86CC == X86::COND_B)
11483     return DAG.getNode(ISD::AND, DL, MVT::i8,
11484                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11485                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
11486                        DAG.getConstant(1, MVT::i8));
11487   
11488   return SDValue();
11489 }
11490           
11491 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11492 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11493                                  X86TargetLowering::DAGCombinerInfo &DCI) {
11494   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11495   // the result is either zero or one (depending on the input carry bit).
11496   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11497   if (X86::isZeroNode(N->getOperand(0)) &&
11498       X86::isZeroNode(N->getOperand(1)) &&
11499       // We don't have a good way to replace an EFLAGS use, so only do this when
11500       // dead right now.
11501       SDValue(N, 1).use_empty()) {
11502     DebugLoc DL = N->getDebugLoc();
11503     EVT VT = N->getValueType(0);
11504     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11505     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11506                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11507                                            DAG.getConstant(X86::COND_B,MVT::i8),
11508                                            N->getOperand(2)),
11509                                DAG.getConstant(1, VT));
11510     return DCI.CombineTo(N, Res1, CarryOut);
11511   }
11512
11513   return SDValue();
11514 }
11515
11516
11517 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11518                                              DAGCombinerInfo &DCI) const {
11519   SelectionDAG &DAG = DCI.DAG;
11520   switch (N->getOpcode()) {
11521   default: break;
11522   case ISD::EXTRACT_VECTOR_ELT:
11523     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11524   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11525   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11526   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
11527   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11528   case ISD::SHL:
11529   case ISD::SRA:
11530   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11531   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11532   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11533   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11534   case X86ISD::FXOR:
11535   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11536   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11537   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11538   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11539   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11540   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
11541   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11542   case X86ISD::SHUFPD:
11543   case X86ISD::PALIGN:
11544   case X86ISD::PUNPCKHBW:
11545   case X86ISD::PUNPCKHWD:
11546   case X86ISD::PUNPCKHDQ:
11547   case X86ISD::PUNPCKHQDQ:
11548   case X86ISD::UNPCKHPS:
11549   case X86ISD::UNPCKHPD:
11550   case X86ISD::PUNPCKLBW:
11551   case X86ISD::PUNPCKLWD:
11552   case X86ISD::PUNPCKLDQ:
11553   case X86ISD::PUNPCKLQDQ:
11554   case X86ISD::UNPCKLPS:
11555   case X86ISD::UNPCKLPD:
11556   case X86ISD::MOVHLPS:
11557   case X86ISD::MOVLHPS:
11558   case X86ISD::PSHUFD:
11559   case X86ISD::PSHUFHW:
11560   case X86ISD::PSHUFLW:
11561   case X86ISD::MOVSS:
11562   case X86ISD::MOVSD:
11563   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11564   }
11565
11566   return SDValue();
11567 }
11568
11569 /// isTypeDesirableForOp - Return true if the target has native support for
11570 /// the specified value type and it is 'desirable' to use the type for the
11571 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11572 /// instruction encodings are longer and some i16 instructions are slow.
11573 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11574   if (!isTypeLegal(VT))
11575     return false;
11576   if (VT != MVT::i16)
11577     return true;
11578
11579   switch (Opc) {
11580   default:
11581     return true;
11582   case ISD::LOAD:
11583   case ISD::SIGN_EXTEND:
11584   case ISD::ZERO_EXTEND:
11585   case ISD::ANY_EXTEND:
11586   case ISD::SHL:
11587   case ISD::SRL:
11588   case ISD::SUB:
11589   case ISD::ADD:
11590   case ISD::MUL:
11591   case ISD::AND:
11592   case ISD::OR:
11593   case ISD::XOR:
11594     return false;
11595   }
11596 }
11597
11598 /// IsDesirableToPromoteOp - This method query the target whether it is
11599 /// beneficial for dag combiner to promote the specified node. If true, it
11600 /// should return the desired promotion type by reference.
11601 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11602   EVT VT = Op.getValueType();
11603   if (VT != MVT::i16)
11604     return false;
11605
11606   bool Promote = false;
11607   bool Commute = false;
11608   switch (Op.getOpcode()) {
11609   default: break;
11610   case ISD::LOAD: {
11611     LoadSDNode *LD = cast<LoadSDNode>(Op);
11612     // If the non-extending load has a single use and it's not live out, then it
11613     // might be folded.
11614     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11615                                                      Op.hasOneUse()*/) {
11616       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11617              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11618         // The only case where we'd want to promote LOAD (rather then it being
11619         // promoted as an operand is when it's only use is liveout.
11620         if (UI->getOpcode() != ISD::CopyToReg)
11621           return false;
11622       }
11623     }
11624     Promote = true;
11625     break;
11626   }
11627   case ISD::SIGN_EXTEND:
11628   case ISD::ZERO_EXTEND:
11629   case ISD::ANY_EXTEND:
11630     Promote = true;
11631     break;
11632   case ISD::SHL:
11633   case ISD::SRL: {
11634     SDValue N0 = Op.getOperand(0);
11635     // Look out for (store (shl (load), x)).
11636     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11637       return false;
11638     Promote = true;
11639     break;
11640   }
11641   case ISD::ADD:
11642   case ISD::MUL:
11643   case ISD::AND:
11644   case ISD::OR:
11645   case ISD::XOR:
11646     Commute = true;
11647     // fallthrough
11648   case ISD::SUB: {
11649     SDValue N0 = Op.getOperand(0);
11650     SDValue N1 = Op.getOperand(1);
11651     if (!Commute && MayFoldLoad(N1))
11652       return false;
11653     // Avoid disabling potential load folding opportunities.
11654     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11655       return false;
11656     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11657       return false;
11658     Promote = true;
11659   }
11660   }
11661
11662   PVT = MVT::i32;
11663   return Promote;
11664 }
11665
11666 //===----------------------------------------------------------------------===//
11667 //                           X86 Inline Assembly Support
11668 //===----------------------------------------------------------------------===//
11669
11670 static bool LowerToBSwap(CallInst *CI) {
11671   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11672   // we will turn this bswap into something that will be lowered to logical ops
11673   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11674   // so don't worry about this.
11675
11676   // Verify this is a simple bswap.
11677   if (CI->getNumArgOperands() != 1 ||
11678       CI->getType() != CI->getArgOperand(0)->getType() ||
11679       !CI->getType()->isIntegerTy())
11680     return false;
11681
11682   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11683   if (!Ty || Ty->getBitWidth() % 16 != 0)
11684     return false;
11685
11686   // Okay, we can do this xform, do so now.
11687   const Type *Tys[] = { Ty };
11688   Module *M = CI->getParent()->getParent()->getParent();
11689   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11690
11691   Value *Op = CI->getArgOperand(0);
11692   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11693
11694   CI->replaceAllUsesWith(Op);
11695   CI->eraseFromParent();
11696   return true;
11697 }
11698
11699 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11700   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11701   InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11702
11703   std::string AsmStr = IA->getAsmString();
11704
11705   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11706   SmallVector<StringRef, 4> AsmPieces;
11707   SplitString(AsmStr, AsmPieces, ";\n");
11708
11709   switch (AsmPieces.size()) {
11710   default: return false;
11711   case 1:
11712     AsmStr = AsmPieces[0];
11713     AsmPieces.clear();
11714     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11715
11716     // bswap $0
11717     if (AsmPieces.size() == 2 &&
11718         (AsmPieces[0] == "bswap" ||
11719          AsmPieces[0] == "bswapq" ||
11720          AsmPieces[0] == "bswapl") &&
11721         (AsmPieces[1] == "$0" ||
11722          AsmPieces[1] == "${0:q}")) {
11723       // No need to check constraints, nothing other than the equivalent of
11724       // "=r,0" would be valid here.
11725       return LowerToBSwap(CI);
11726     }
11727     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11728     if (CI->getType()->isIntegerTy(16) &&
11729         AsmPieces.size() == 3 &&
11730         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11731         AsmPieces[1] == "$$8," &&
11732         AsmPieces[2] == "${0:w}" &&
11733         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11734       AsmPieces.clear();
11735       const std::string &Constraints = IA->getConstraintString();
11736       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11737       std::sort(AsmPieces.begin(), AsmPieces.end());
11738       if (AsmPieces.size() == 4 &&
11739           AsmPieces[0] == "~{cc}" &&
11740           AsmPieces[1] == "~{dirflag}" &&
11741           AsmPieces[2] == "~{flags}" &&
11742           AsmPieces[3] == "~{fpsr}") {
11743         return LowerToBSwap(CI);
11744       }
11745     }
11746     break;
11747   case 3:
11748     if (CI->getType()->isIntegerTy(32) &&
11749         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11750       SmallVector<StringRef, 4> Words;
11751       SplitString(AsmPieces[0], Words, " \t,");
11752       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11753           Words[2] == "${0:w}") {
11754         Words.clear();
11755         SplitString(AsmPieces[1], Words, " \t,");
11756         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11757             Words[2] == "$0") {
11758           Words.clear();
11759           SplitString(AsmPieces[2], Words, " \t,");
11760           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11761               Words[2] == "${0:w}") {
11762             AsmPieces.clear();
11763             const std::string &Constraints = IA->getConstraintString();
11764             SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11765             std::sort(AsmPieces.begin(), AsmPieces.end());
11766             if (AsmPieces.size() == 4 &&
11767                 AsmPieces[0] == "~{cc}" &&
11768                 AsmPieces[1] == "~{dirflag}" &&
11769                 AsmPieces[2] == "~{flags}" &&
11770                 AsmPieces[3] == "~{fpsr}") {
11771               return LowerToBSwap(CI);
11772             }
11773           }
11774         }
11775       }
11776     }
11777     if (CI->getType()->isIntegerTy(64) &&
11778         Constraints.size() >= 2 &&
11779         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11780         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11781       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11782       SmallVector<StringRef, 4> Words;
11783       SplitString(AsmPieces[0], Words, " \t");
11784       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11785         Words.clear();
11786         SplitString(AsmPieces[1], Words, " \t");
11787         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11788           Words.clear();
11789           SplitString(AsmPieces[2], Words, " \t,");
11790           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11791               Words[2] == "%edx") {
11792             return LowerToBSwap(CI);
11793           }
11794         }
11795       }
11796     }
11797     break;
11798   }
11799   return false;
11800 }
11801
11802
11803
11804 /// getConstraintType - Given a constraint letter, return the type of
11805 /// constraint it is for this target.
11806 X86TargetLowering::ConstraintType
11807 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11808   if (Constraint.size() == 1) {
11809     switch (Constraint[0]) {
11810     case 'R':
11811     case 'q':
11812     case 'Q':
11813     case 'f':
11814     case 't':
11815     case 'u':
11816     case 'y':
11817     case 'x':
11818     case 'Y':
11819       return C_RegisterClass;
11820     case 'a':
11821     case 'b':
11822     case 'c':
11823     case 'd':
11824     case 'S':
11825     case 'D':
11826     case 'A':
11827       return C_Register;
11828     case 'I':
11829     case 'J':
11830     case 'K':
11831     case 'L':
11832     case 'M':
11833     case 'N':
11834     case 'G':
11835     case 'C':
11836     case 'e':
11837     case 'Z':
11838       return C_Other;
11839     default:
11840       break;
11841     }
11842   }
11843   return TargetLowering::getConstraintType(Constraint);
11844 }
11845
11846 /// Examine constraint type and operand type and determine a weight value.
11847 /// This object must already have been set up with the operand type
11848 /// and the current alternative constraint selected.
11849 TargetLowering::ConstraintWeight
11850   X86TargetLowering::getSingleConstraintMatchWeight(
11851     AsmOperandInfo &info, const char *constraint) const {
11852   ConstraintWeight weight = CW_Invalid;
11853   Value *CallOperandVal = info.CallOperandVal;
11854     // If we don't have a value, we can't do a match,
11855     // but allow it at the lowest weight.
11856   if (CallOperandVal == NULL)
11857     return CW_Default;
11858   const Type *type = CallOperandVal->getType();
11859   // Look at the constraint type.
11860   switch (*constraint) {
11861   default:
11862     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11863   case 'R':
11864   case 'q':
11865   case 'Q':
11866   case 'a':
11867   case 'b':
11868   case 'c':
11869   case 'd':
11870   case 'S':
11871   case 'D':
11872   case 'A':
11873     if (CallOperandVal->getType()->isIntegerTy())
11874       weight = CW_SpecificReg;
11875     break;
11876   case 'f':
11877   case 't':
11878   case 'u':
11879       if (type->isFloatingPointTy())
11880         weight = CW_SpecificReg;
11881       break;
11882   case 'y':
11883       if (type->isX86_MMXTy() && Subtarget->hasMMX())
11884         weight = CW_SpecificReg;
11885       break;
11886   case 'x':
11887   case 'Y':
11888     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11889       weight = CW_Register;
11890     break;
11891   case 'I':
11892     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11893       if (C->getZExtValue() <= 31)
11894         weight = CW_Constant;
11895     }
11896     break;
11897   case 'J':
11898     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11899       if (C->getZExtValue() <= 63)
11900         weight = CW_Constant;
11901     }
11902     break;
11903   case 'K':
11904     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11905       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11906         weight = CW_Constant;
11907     }
11908     break;
11909   case 'L':
11910     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11911       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11912         weight = CW_Constant;
11913     }
11914     break;
11915   case 'M':
11916     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11917       if (C->getZExtValue() <= 3)
11918         weight = CW_Constant;
11919     }
11920     break;
11921   case 'N':
11922     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11923       if (C->getZExtValue() <= 0xff)
11924         weight = CW_Constant;
11925     }
11926     break;
11927   case 'G':
11928   case 'C':
11929     if (dyn_cast<ConstantFP>(CallOperandVal)) {
11930       weight = CW_Constant;
11931     }
11932     break;
11933   case 'e':
11934     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11935       if ((C->getSExtValue() >= -0x80000000LL) &&
11936           (C->getSExtValue() <= 0x7fffffffLL))
11937         weight = CW_Constant;
11938     }
11939     break;
11940   case 'Z':
11941     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11942       if (C->getZExtValue() <= 0xffffffff)
11943         weight = CW_Constant;
11944     }
11945     break;
11946   }
11947   return weight;
11948 }
11949
11950 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11951 /// with another that has more specific requirements based on the type of the
11952 /// corresponding operand.
11953 const char *X86TargetLowering::
11954 LowerXConstraint(EVT ConstraintVT) const {
11955   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11956   // 'f' like normal targets.
11957   if (ConstraintVT.isFloatingPoint()) {
11958     if (Subtarget->hasXMMInt())
11959       return "Y";
11960     if (Subtarget->hasXMM())
11961       return "x";
11962   }
11963
11964   return TargetLowering::LowerXConstraint(ConstraintVT);
11965 }
11966
11967 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11968 /// vector.  If it is invalid, don't add anything to Ops.
11969 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11970                                                      char Constraint,
11971                                                      std::vector<SDValue>&Ops,
11972                                                      SelectionDAG &DAG) const {
11973   SDValue Result(0, 0);
11974
11975   switch (Constraint) {
11976   default: break;
11977   case 'I':
11978     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11979       if (C->getZExtValue() <= 31) {
11980         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11981         break;
11982       }
11983     }
11984     return;
11985   case 'J':
11986     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11987       if (C->getZExtValue() <= 63) {
11988         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11989         break;
11990       }
11991     }
11992     return;
11993   case 'K':
11994     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11995       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11996         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11997         break;
11998       }
11999     }
12000     return;
12001   case 'N':
12002     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12003       if (C->getZExtValue() <= 255) {
12004         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12005         break;
12006       }
12007     }
12008     return;
12009   case 'e': {
12010     // 32-bit signed value
12011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12012       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12013                                            C->getSExtValue())) {
12014         // Widen to 64 bits here to get it sign extended.
12015         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12016         break;
12017       }
12018     // FIXME gcc accepts some relocatable values here too, but only in certain
12019     // memory models; it's complicated.
12020     }
12021     return;
12022   }
12023   case 'Z': {
12024     // 32-bit unsigned value
12025     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12026       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12027                                            C->getZExtValue())) {
12028         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12029         break;
12030       }
12031     }
12032     // FIXME gcc accepts some relocatable values here too, but only in certain
12033     // memory models; it's complicated.
12034     return;
12035   }
12036   case 'i': {
12037     // Literal immediates are always ok.
12038     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12039       // Widen to 64 bits here to get it sign extended.
12040       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12041       break;
12042     }
12043
12044     // In any sort of PIC mode addresses need to be computed at runtime by
12045     // adding in a register or some sort of table lookup.  These can't
12046     // be used as immediates.
12047     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12048       return;
12049
12050     // If we are in non-pic codegen mode, we allow the address of a global (with
12051     // an optional displacement) to be used with 'i'.
12052     GlobalAddressSDNode *GA = 0;
12053     int64_t Offset = 0;
12054
12055     // Match either (GA), (GA+C), (GA+C1+C2), etc.
12056     while (1) {
12057       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12058         Offset += GA->getOffset();
12059         break;
12060       } else if (Op.getOpcode() == ISD::ADD) {
12061         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12062           Offset += C->getZExtValue();
12063           Op = Op.getOperand(0);
12064           continue;
12065         }
12066       } else if (Op.getOpcode() == ISD::SUB) {
12067         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12068           Offset += -C->getZExtValue();
12069           Op = Op.getOperand(0);
12070           continue;
12071         }
12072       }
12073
12074       // Otherwise, this isn't something we can handle, reject it.
12075       return;
12076     }
12077
12078     const GlobalValue *GV = GA->getGlobal();
12079     // If we require an extra load to get this address, as in PIC mode, we
12080     // can't accept it.
12081     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12082                                                         getTargetMachine())))
12083       return;
12084
12085     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12086                                         GA->getValueType(0), Offset);
12087     break;
12088   }
12089   }
12090
12091   if (Result.getNode()) {
12092     Ops.push_back(Result);
12093     return;
12094   }
12095   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12096 }
12097
12098 std::vector<unsigned> X86TargetLowering::
12099 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12100                                   EVT VT) const {
12101   if (Constraint.size() == 1) {
12102     // FIXME: not handling fp-stack yet!
12103     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12104     default: break;  // Unknown constraint letter
12105     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12106       if (Subtarget->is64Bit()) {
12107         if (VT == MVT::i32)
12108           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12109                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12110                                        X86::R10D,X86::R11D,X86::R12D,
12111                                        X86::R13D,X86::R14D,X86::R15D,
12112                                        X86::EBP, X86::ESP, 0);
12113         else if (VT == MVT::i16)
12114           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12115                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12116                                        X86::R10W,X86::R11W,X86::R12W,
12117                                        X86::R13W,X86::R14W,X86::R15W,
12118                                        X86::BP,  X86::SP, 0);
12119         else if (VT == MVT::i8)
12120           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12121                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12122                                        X86::R10B,X86::R11B,X86::R12B,
12123                                        X86::R13B,X86::R14B,X86::R15B,
12124                                        X86::BPL, X86::SPL, 0);
12125
12126         else if (VT == MVT::i64)
12127           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12128                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12129                                        X86::R10, X86::R11, X86::R12,
12130                                        X86::R13, X86::R14, X86::R15,
12131                                        X86::RBP, X86::RSP, 0);
12132
12133         break;
12134       }
12135       // 32-bit fallthrough
12136     case 'Q':   // Q_REGS
12137       if (VT == MVT::i32)
12138         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12139       else if (VT == MVT::i16)
12140         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12141       else if (VT == MVT::i8)
12142         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12143       else if (VT == MVT::i64)
12144         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12145       break;
12146     }
12147   }
12148
12149   return std::vector<unsigned>();
12150 }
12151
12152 std::pair<unsigned, const TargetRegisterClass*>
12153 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12154                                                 EVT VT) const {
12155   // First, see if this is a constraint that directly corresponds to an LLVM
12156   // register class.
12157   if (Constraint.size() == 1) {
12158     // GCC Constraint Letters
12159     switch (Constraint[0]) {
12160     default: break;
12161     case 'r':   // GENERAL_REGS
12162     case 'l':   // INDEX_REGS
12163       if (VT == MVT::i8)
12164         return std::make_pair(0U, X86::GR8RegisterClass);
12165       if (VT == MVT::i16)
12166         return std::make_pair(0U, X86::GR16RegisterClass);
12167       if (VT == MVT::i32 || !Subtarget->is64Bit())
12168         return std::make_pair(0U, X86::GR32RegisterClass);
12169       return std::make_pair(0U, X86::GR64RegisterClass);
12170     case 'R':   // LEGACY_REGS
12171       if (VT == MVT::i8)
12172         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12173       if (VT == MVT::i16)
12174         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12175       if (VT == MVT::i32 || !Subtarget->is64Bit())
12176         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12177       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12178     case 'f':  // FP Stack registers.
12179       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12180       // value to the correct fpstack register class.
12181       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12182         return std::make_pair(0U, X86::RFP32RegisterClass);
12183       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12184         return std::make_pair(0U, X86::RFP64RegisterClass);
12185       return std::make_pair(0U, X86::RFP80RegisterClass);
12186     case 'y':   // MMX_REGS if MMX allowed.
12187       if (!Subtarget->hasMMX()) break;
12188       return std::make_pair(0U, X86::VR64RegisterClass);
12189     case 'Y':   // SSE_REGS if SSE2 allowed
12190       if (!Subtarget->hasXMMInt()) break;
12191       // FALL THROUGH.
12192     case 'x':   // SSE_REGS if SSE1 allowed
12193       if (!Subtarget->hasXMM()) break;
12194
12195       switch (VT.getSimpleVT().SimpleTy) {
12196       default: break;
12197       // Scalar SSE types.
12198       case MVT::f32:
12199       case MVT::i32:
12200         return std::make_pair(0U, X86::FR32RegisterClass);
12201       case MVT::f64:
12202       case MVT::i64:
12203         return std::make_pair(0U, X86::FR64RegisterClass);
12204       // Vector types.
12205       case MVT::v16i8:
12206       case MVT::v8i16:
12207       case MVT::v4i32:
12208       case MVT::v2i64:
12209       case MVT::v4f32:
12210       case MVT::v2f64:
12211         return std::make_pair(0U, X86::VR128RegisterClass);
12212       }
12213       break;
12214     }
12215   }
12216
12217   // Use the default implementation in TargetLowering to convert the register
12218   // constraint into a member of a register class.
12219   std::pair<unsigned, const TargetRegisterClass*> Res;
12220   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12221
12222   // Not found as a standard register?
12223   if (Res.second == 0) {
12224     // Map st(0) -> st(7) -> ST0
12225     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12226         tolower(Constraint[1]) == 's' &&
12227         tolower(Constraint[2]) == 't' &&
12228         Constraint[3] == '(' &&
12229         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12230         Constraint[5] == ')' &&
12231         Constraint[6] == '}') {
12232
12233       Res.first = X86::ST0+Constraint[4]-'0';
12234       Res.second = X86::RFP80RegisterClass;
12235       return Res;
12236     }
12237
12238     // GCC allows "st(0)" to be called just plain "st".
12239     if (StringRef("{st}").equals_lower(Constraint)) {
12240       Res.first = X86::ST0;
12241       Res.second = X86::RFP80RegisterClass;
12242       return Res;
12243     }
12244
12245     // flags -> EFLAGS
12246     if (StringRef("{flags}").equals_lower(Constraint)) {
12247       Res.first = X86::EFLAGS;
12248       Res.second = X86::CCRRegisterClass;
12249       return Res;
12250     }
12251
12252     // 'A' means EAX + EDX.
12253     if (Constraint == "A") {
12254       Res.first = X86::EAX;
12255       Res.second = X86::GR32_ADRegisterClass;
12256       return Res;
12257     }
12258     return Res;
12259   }
12260
12261   // Otherwise, check to see if this is a register class of the wrong value
12262   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12263   // turn into {ax},{dx}.
12264   if (Res.second->hasType(VT))
12265     return Res;   // Correct type already, nothing to do.
12266
12267   // All of the single-register GCC register classes map their values onto
12268   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12269   // really want an 8-bit or 32-bit register, map to the appropriate register
12270   // class and return the appropriate register.
12271   if (Res.second == X86::GR16RegisterClass) {
12272     if (VT == MVT::i8) {
12273       unsigned DestReg = 0;
12274       switch (Res.first) {
12275       default: break;
12276       case X86::AX: DestReg = X86::AL; break;
12277       case X86::DX: DestReg = X86::DL; break;
12278       case X86::CX: DestReg = X86::CL; break;
12279       case X86::BX: DestReg = X86::BL; break;
12280       }
12281       if (DestReg) {
12282         Res.first = DestReg;
12283         Res.second = X86::GR8RegisterClass;
12284       }
12285     } else if (VT == MVT::i32) {
12286       unsigned DestReg = 0;
12287       switch (Res.first) {
12288       default: break;
12289       case X86::AX: DestReg = X86::EAX; break;
12290       case X86::DX: DestReg = X86::EDX; break;
12291       case X86::CX: DestReg = X86::ECX; break;
12292       case X86::BX: DestReg = X86::EBX; break;
12293       case X86::SI: DestReg = X86::ESI; break;
12294       case X86::DI: DestReg = X86::EDI; break;
12295       case X86::BP: DestReg = X86::EBP; break;
12296       case X86::SP: DestReg = X86::ESP; break;
12297       }
12298       if (DestReg) {
12299         Res.first = DestReg;
12300         Res.second = X86::GR32RegisterClass;
12301       }
12302     } else if (VT == MVT::i64) {
12303       unsigned DestReg = 0;
12304       switch (Res.first) {
12305       default: break;
12306       case X86::AX: DestReg = X86::RAX; break;
12307       case X86::DX: DestReg = X86::RDX; break;
12308       case X86::CX: DestReg = X86::RCX; break;
12309       case X86::BX: DestReg = X86::RBX; break;
12310       case X86::SI: DestReg = X86::RSI; break;
12311       case X86::DI: DestReg = X86::RDI; break;
12312       case X86::BP: DestReg = X86::RBP; break;
12313       case X86::SP: DestReg = X86::RSP; break;
12314       }
12315       if (DestReg) {
12316         Res.first = DestReg;
12317         Res.second = X86::GR64RegisterClass;
12318       }
12319     }
12320   } else if (Res.second == X86::FR32RegisterClass ||
12321              Res.second == X86::FR64RegisterClass ||
12322              Res.second == X86::VR128RegisterClass) {
12323     // Handle references to XMM physical registers that got mapped into the
12324     // wrong class.  This can happen with constraints like {xmm0} where the
12325     // target independent register mapper will just pick the first match it can
12326     // find, ignoring the required type.
12327     if (VT == MVT::f32)
12328       Res.second = X86::FR32RegisterClass;
12329     else if (VT == MVT::f64)
12330       Res.second = X86::FR64RegisterClass;
12331     else if (X86::VR128RegisterClass->hasType(VT))
12332       Res.second = X86::VR128RegisterClass;
12333   }
12334
12335   return Res;
12336 }