8f7f4ab11a35ad5c14778c2c0bda47df3b4e2512
[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 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 using namespace llvm;
42
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
45
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47   : TargetLowering(TM) {
48   Subtarget = &TM.getSubtarget<X86Subtarget>();
49   X86ScalarSSEf64 = Subtarget->hasSSE2();
50   X86ScalarSSEf32 = Subtarget->hasSSE1();
51   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
52
53   bool Fast = false;
54
55   RegInfo = TM.getRegisterInfo();
56   TD = getTargetData();
57
58   // Set up the TargetLowering object.
59
60   // X86 is weird, it always uses i8 for shift amounts and setcc results.
61   setShiftAmountType(MVT::i8);
62   setSetCCResultContents(ZeroOrOneSetCCResult);
63   setSchedulingPreference(SchedulingForRegPressure);
64   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
65   setStackPointerRegisterToSaveRestore(X86StackPtr);
66
67   if (Subtarget->isTargetDarwin()) {
68     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69     setUseUnderscoreSetJmp(false);
70     setUseUnderscoreLongJmp(false);
71   } else if (Subtarget->isTargetMingw()) {
72     // MS runtime is weird: it exports _setjmp, but longjmp!
73     setUseUnderscoreSetJmp(true);
74     setUseUnderscoreLongJmp(false);
75   } else {
76     setUseUnderscoreSetJmp(true);
77     setUseUnderscoreLongJmp(true);
78   }
79   
80   // Set up the register classes.
81   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84   if (Subtarget->is64Bit())
85     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
86
87   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
88
89   // We don't accept any truncstore of integer registers.  
90   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95   setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96
97   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
98   // operation.
99   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
100   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
101   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
102
103   if (Subtarget->is64Bit()) {
104     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
105     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
106   } else {
107     if (X86ScalarSSEf64)
108       // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
109       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Expand);
110     else
111       setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Promote);
112   }
113
114   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
115   // this operation.
116   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
117   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
118   // SSE has no i16 to fp conversion, only i32
119   if (X86ScalarSSEf32) {
120     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
121     // f32 and f64 cases are Legal, f80 case is not
122     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
123   } else {
124     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
125     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
126   }
127
128   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
129   // are Legal, f80 is custom lowered.
130   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
131   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
132
133   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
134   // this operation.
135   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
136   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
137
138   if (X86ScalarSSEf32) {
139     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
140     // f32 and f64 cases are Legal, f80 case is not
141     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
142   } else {
143     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
144     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
145   }
146
147   // Handle FP_TO_UINT by promoting the destination to a larger signed
148   // conversion.
149   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
150   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
151   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
152
153   if (Subtarget->is64Bit()) {
154     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
155     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
156   } else {
157     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
158       // Expand FP_TO_UINT into a select.
159       // FIXME: We would like to use a Custom expander here eventually to do
160       // the optimal thing for SSE vs. the default expansion in the legalizer.
161       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
162     else
163       // With SSE3 we can use fisttpll to convert to a signed i64.
164       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Promote);
165   }
166
167   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
168   if (!X86ScalarSSEf64) {
169     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
170     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
171   }
172
173   // Scalar integer divide and remainder are lowered to use operations that
174   // produce two results, to match the available instructions. This exposes
175   // the two-result form to trivial CSE, which is able to combine x/y and x%y
176   // into a single instruction.
177   //
178   // Scalar integer multiply-high is also lowered to use two-result
179   // operations, to match the available instructions. However, plain multiply
180   // (low) operations are left as Legal, as there are single-result
181   // instructions for this in x86. Using the two-result multiply instructions
182   // when both high and low results are needed must be arranged by dagcombine.
183   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
184   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
185   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
186   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
187   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
188   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
189   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
190   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
191   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
192   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
193   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
194   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
195   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
196   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
197   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
198   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
199   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
200   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
201   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
202   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
203   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
204   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
205   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
206   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
207
208   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
209   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
210   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
211   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
212   if (Subtarget->is64Bit())
213     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
217   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
218   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
219   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
220   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
221   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
222   
223   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
224   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
225   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
226   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
227   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
228   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
229   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
230   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
231   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
232   if (Subtarget->is64Bit()) {
233     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
234     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
235     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
236   }
237
238   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
239   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
240
241   // These should be promoted to a larger select which is supported.
242   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
243   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
244   // X86 wants to expand cmov itself.
245   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
246   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
247   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
248   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
249   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
250   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
251   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
252   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
253   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
254   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
255   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
258     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
259   }
260   // X86 ret instruction may pop stack.
261   setOperationAction(ISD::RET             , MVT::Other, Custom);
262   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
263
264   // Darwin ABI issue.
265   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
266   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
267   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
268   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
269   if (Subtarget->is64Bit())
270     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271   setOperationAction(ISD::Symbol          , MVT::i32  , Custom);
272   if (Subtarget->is64Bit()) {
273     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
274     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
275     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
276     setOperationAction(ISD::Symbol        , MVT::i64  , Custom);
277   }
278   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
279   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
280   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
281   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
282   if (Subtarget->is64Bit()) {
283     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
284     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
285     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
286   }
287
288   if (Subtarget->hasSSE1())
289     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
290
291   if (!Subtarget->hasSSE2())
292     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
293
294   // Expand certain atomics
295   setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
296   setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
297   setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
298   setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
299
300   setOperationAction(ISD::ATOMIC_LOAD_SUB_8, MVT::i8, Expand);
301   setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Expand);
302   setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Expand);
303   setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Expand);
304
305   // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
306   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
307   // FIXME - use subtarget debug flags
308   if (!Subtarget->isTargetDarwin() &&
309       !Subtarget->isTargetELF() &&
310       !Subtarget->isTargetCygMing()) {
311     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
312     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
313   }
314
315   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
316   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
317   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
318   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
319   if (Subtarget->is64Bit()) {
320     setExceptionPointerRegister(X86::RAX);
321     setExceptionSelectorRegister(X86::RDX);
322   } else {
323     setExceptionPointerRegister(X86::EAX);
324     setExceptionSelectorRegister(X86::EDX);
325   }
326   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
327   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
328
329   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
330
331   setOperationAction(ISD::TRAP, MVT::Other, Legal);
332
333   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
334   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
335   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
338     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
339   } else {
340     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
341     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
342   }
343
344   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
345   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
346   if (Subtarget->is64Bit())
347     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
348   if (Subtarget->isTargetCygMing())
349     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
350   else
351     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
352
353   if (X86ScalarSSEf64) {
354     // f32 and f64 use SSE.
355     // Set up the FP register classes.
356     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
357     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
358
359     // Use ANDPD to simulate FABS.
360     setOperationAction(ISD::FABS , MVT::f64, Custom);
361     setOperationAction(ISD::FABS , MVT::f32, Custom);
362
363     // Use XORP to simulate FNEG.
364     setOperationAction(ISD::FNEG , MVT::f64, Custom);
365     setOperationAction(ISD::FNEG , MVT::f32, Custom);
366
367     // Use ANDPD and ORPD to simulate FCOPYSIGN.
368     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
369     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
370
371     // We don't support sin/cos/fmod
372     setOperationAction(ISD::FSIN , MVT::f64, Expand);
373     setOperationAction(ISD::FCOS , MVT::f64, Expand);
374     setOperationAction(ISD::FSIN , MVT::f32, Expand);
375     setOperationAction(ISD::FCOS , MVT::f32, Expand);
376
377     // Expand FP immediates into loads from the stack, except for the special
378     // cases we handle.
379     addLegalFPImmediate(APFloat(+0.0)); // xorpd
380     addLegalFPImmediate(APFloat(+0.0f)); // xorps
381
382     // Floating truncations from f80 and extensions to f80 go through memory.
383     // If optimizing, we lie about this though and handle it in
384     // InstructionSelectPreprocess so that dagcombine2 can hack on these.
385     if (Fast) {
386       setConvertAction(MVT::f32, MVT::f80, Expand);
387       setConvertAction(MVT::f64, MVT::f80, Expand);
388       setConvertAction(MVT::f80, MVT::f32, Expand);
389       setConvertAction(MVT::f80, MVT::f64, Expand);
390     }
391   } else if (X86ScalarSSEf32) {
392     // Use SSE for f32, x87 for f64.
393     // Set up the FP register classes.
394     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
395     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
396
397     // Use ANDPS to simulate FABS.
398     setOperationAction(ISD::FABS , MVT::f32, Custom);
399
400     // Use XORP to simulate FNEG.
401     setOperationAction(ISD::FNEG , MVT::f32, Custom);
402
403     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
404
405     // Use ANDPS and ORPS to simulate FCOPYSIGN.
406     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
407     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
408
409     // We don't support sin/cos/fmod
410     setOperationAction(ISD::FSIN , MVT::f32, Expand);
411     setOperationAction(ISD::FCOS , MVT::f32, Expand);
412
413     // Special cases we handle for FP constants.
414     addLegalFPImmediate(APFloat(+0.0f)); // xorps
415     addLegalFPImmediate(APFloat(+0.0)); // FLD0
416     addLegalFPImmediate(APFloat(+1.0)); // FLD1
417     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
418     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
419
420     // SSE <-> X87 conversions go through memory.  If optimizing, we lie about
421     // this though and handle it in InstructionSelectPreprocess so that
422     // dagcombine2 can hack on these.
423     if (Fast) {
424       setConvertAction(MVT::f32, MVT::f64, Expand);
425       setConvertAction(MVT::f32, MVT::f80, Expand);
426       setConvertAction(MVT::f80, MVT::f32, Expand);    
427       setConvertAction(MVT::f64, MVT::f32, Expand);
428       // And x87->x87 truncations also.
429       setConvertAction(MVT::f80, MVT::f64, Expand);
430     }
431
432     if (!UnsafeFPMath) {
433       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
434       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
435     }
436   } else {
437     // f32 and f64 in x87.
438     // Set up the FP register classes.
439     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
440     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
441
442     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
443     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
444     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
445     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
446
447     // Floating truncations go through memory.  If optimizing, we lie about
448     // this though and handle it in InstructionSelectPreprocess so that
449     // dagcombine2 can hack on these.
450     if (Fast) {
451       setConvertAction(MVT::f80, MVT::f32, Expand);    
452       setConvertAction(MVT::f64, MVT::f32, Expand);
453       setConvertAction(MVT::f80, MVT::f64, Expand);
454     }
455
456     if (!UnsafeFPMath) {
457       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
458       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
459     }
460     addLegalFPImmediate(APFloat(+0.0)); // FLD0
461     addLegalFPImmediate(APFloat(+1.0)); // FLD1
462     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
463     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
464     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
465     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
466     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
467     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
468   }
469
470   // Long double always uses X87.
471   addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
472   setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
473   setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
474   {
475     APFloat TmpFlt(+0.0);
476     TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
477     addLegalFPImmediate(TmpFlt);  // FLD0
478     TmpFlt.changeSign();
479     addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
480     APFloat TmpFlt2(+1.0);
481     TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
482     addLegalFPImmediate(TmpFlt2);  // FLD1
483     TmpFlt2.changeSign();
484     addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
485   }
486     
487   if (!UnsafeFPMath) {
488     setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
489     setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
490   }
491
492   // Always use a library call for pow.
493   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
494   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
495   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
496
497   setOperationAction(ISD::FLOG, MVT::f32, Expand);
498   setOperationAction(ISD::FLOG, MVT::f64, Expand);
499   setOperationAction(ISD::FLOG, MVT::f80, Expand);
500   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
501   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
502   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
503   setOperationAction(ISD::FLOG10, MVT::f32, Expand);
504   setOperationAction(ISD::FLOG10, MVT::f64, Expand);
505   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
506   setOperationAction(ISD::FEXP, MVT::f32, Expand);
507   setOperationAction(ISD::FEXP, MVT::f64, Expand);
508   setOperationAction(ISD::FEXP, MVT::f80, Expand);
509   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
510   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
511   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
512
513   // First set operation action for all vector types to expand. Then we
514   // will selectively turn on ones that can be effectively codegen'd.
515   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
516        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
517     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
518     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
519     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
520     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
521     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
522     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
523     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
524     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
525     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
526     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
527     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
528     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
529     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
532     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
534     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
535     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
536     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
537     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
538     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
539     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
560   }
561
562   if (Subtarget->hasMMX()) {
563     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
564     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
565     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
566     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
567     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
568
569     // FIXME: add MMX packed arithmetics
570
571     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
572     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
573     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
574     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
575
576     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
577     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
578     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
579     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
580
581     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
582     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
583
584     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
585     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
586     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
587     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
588     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
589     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
590     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
591
592     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
593     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
594     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
595     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
596     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
597     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
598     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
599
600     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
601     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
602     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
603     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
604     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
605     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
606     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
607
608     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
609     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
610     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
611     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
612     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
613     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
614     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
615     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
616     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
617
618     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
619     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
620     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
621     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
622     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
623
624     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
625     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
626     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
627     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
628
629     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
630     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
631     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
632     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
633
634     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
635   }
636
637   if (Subtarget->hasSSE1()) {
638     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
639
640     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
641     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
642     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
643     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
644     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
645     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
646     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
647     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
648     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
649     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
650     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
651     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
652   }
653
654   if (Subtarget->hasSSE2()) {
655     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
656     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
657     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
658     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
659     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
660
661     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
662     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
663     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
664     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
665     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
666     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
667     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
668     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
669     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
670     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
671     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
672     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
673     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
674     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
675     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
676
677     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
678     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
679     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
680     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
681
682     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
683     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
684     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
685     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
686     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
687
688     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
689     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
690       MVT VT = (MVT::SimpleValueType)i;
691       // Do not attempt to custom lower non-power-of-2 vectors
692       if (!isPowerOf2_32(VT.getVectorNumElements()))
693         continue;
694       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
695       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
696       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
697     }
698     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
699     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
700     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
701     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
702     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
703     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
704     if (Subtarget->is64Bit()) {
705       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
706       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
707     }
708
709     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
710     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
711       setOperationAction(ISD::AND,    (MVT::SimpleValueType)VT, Promote);
712       AddPromotedToType (ISD::AND,    (MVT::SimpleValueType)VT, MVT::v2i64);
713       setOperationAction(ISD::OR,     (MVT::SimpleValueType)VT, Promote);
714       AddPromotedToType (ISD::OR,     (MVT::SimpleValueType)VT, MVT::v2i64);
715       setOperationAction(ISD::XOR,    (MVT::SimpleValueType)VT, Promote);
716       AddPromotedToType (ISD::XOR,    (MVT::SimpleValueType)VT, MVT::v2i64);
717       setOperationAction(ISD::LOAD,   (MVT::SimpleValueType)VT, Promote);
718       AddPromotedToType (ISD::LOAD,   (MVT::SimpleValueType)VT, MVT::v2i64);
719       setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
720       AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
721     }
722
723     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
724
725     // Custom lower v2i64 and v2f64 selects.
726     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
727     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
728     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
729     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
730     
731   }
732   
733   if (Subtarget->hasSSE41()) {
734     // FIXME: Do we need to handle scalar-to-vector here?
735     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
736     setOperationAction(ISD::MUL,                MVT::v2i64, Legal);
737
738     // i8 and i16 vectors are custom , because the source register and source
739     // source memory operand types are not the same width.  f32 vectors are
740     // custom since the immediate controlling the insert encodes additional
741     // information.
742     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
743     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
744     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Legal);
745     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
746
747     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
748     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
749     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
750     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
751
752     if (Subtarget->is64Bit()) {
753       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
754       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
755     }
756   }
757
758   if (Subtarget->hasSSE42()) {
759     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
760   }
761   
762   // We want to custom lower some of our intrinsics.
763   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
764
765   // We have target-specific dag combine patterns for the following nodes:
766   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
767   setTargetDAGCombine(ISD::BUILD_VECTOR);
768   setTargetDAGCombine(ISD::SELECT);
769   setTargetDAGCombine(ISD::STORE);
770
771   computeRegisterProperties();
772
773   // FIXME: These should be based on subtarget info. Plus, the values should
774   // be smaller when we are in optimizing for size mode.
775   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
776   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
777   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
778   allowUnalignedMemoryAccesses = true; // x86 supports it!
779   setPrefLoopAlignment(16);
780 }
781
782
783 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
784   return MVT::i8;
785 }
786
787
788 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
789 /// the desired ByVal argument alignment.
790 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
791   if (MaxAlign == 16)
792     return;
793   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
794     if (VTy->getBitWidth() == 128)
795       MaxAlign = 16;
796   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
797     unsigned EltAlign = 0;
798     getMaxByValAlign(ATy->getElementType(), EltAlign);
799     if (EltAlign > MaxAlign)
800       MaxAlign = EltAlign;
801   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
802     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
803       unsigned EltAlign = 0;
804       getMaxByValAlign(STy->getElementType(i), EltAlign);
805       if (EltAlign > MaxAlign)
806         MaxAlign = EltAlign;
807       if (MaxAlign == 16)
808         break;
809     }
810   }
811   return;
812 }
813
814 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
815 /// function arguments in the caller parameter area. For X86, aggregates
816 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
817 /// are at 4-byte boundaries.
818 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
819   if (Subtarget->is64Bit()) {
820     // Max of 8 and alignment of type.
821     unsigned TyAlign = TD->getABITypeAlignment(Ty);
822     if (TyAlign > 8)
823       return TyAlign;
824     return 8;
825   }
826
827   unsigned Align = 4;
828   if (Subtarget->hasSSE1())
829     getMaxByValAlign(Ty, Align);
830   return Align;
831 }
832
833 /// getOptimalMemOpType - Returns the target specific optimal type for load
834 /// and store operations as a result of memset, memcpy, and memmove
835 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
836 /// determining it.
837 MVT
838 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
839                                        bool isSrcConst, bool isSrcStr) const {
840   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
841     return MVT::v4i32;
842   if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
843     return MVT::v4f32;
844   if (Subtarget->is64Bit() && Size >= 8)
845     return MVT::i64;
846   return MVT::i32;
847 }
848
849
850 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
851 /// jumptable.
852 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
853                                                       SelectionDAG &DAG) const {
854   if (usesGlobalOffsetTable())
855     return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
856   if (!Subtarget->isPICStyleRIPRel())
857     return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
858   return Table;
859 }
860
861 //===----------------------------------------------------------------------===//
862 //               Return Value Calling Convention Implementation
863 //===----------------------------------------------------------------------===//
864
865 #include "X86GenCallingConv.inc"
866
867 /// LowerRET - Lower an ISD::RET node.
868 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
869   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
870   
871   SmallVector<CCValAssign, 16> RVLocs;
872   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
873   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
874   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
875   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
876     
877   // If this is the first return lowered for this function, add the regs to the
878   // liveout set for the function.
879   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
880     for (unsigned i = 0; i != RVLocs.size(); ++i)
881       if (RVLocs[i].isRegLoc())
882         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
883   }
884   SDValue Chain = Op.getOperand(0);
885   
886   // Handle tail call return.
887   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
888   if (Chain.getOpcode() == X86ISD::TAILCALL) {
889     SDValue TailCall = Chain;
890     SDValue TargetAddress = TailCall.getOperand(1);
891     SDValue StackAdjustment = TailCall.getOperand(2);
892     assert(((TargetAddress.getOpcode() == ISD::Register &&
893                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
894                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
895               TargetAddress.getOpcode() == ISD::TargetSymbol ||
896               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) && 
897              "Expecting an global address, external symbol, or register");
898     assert(StackAdjustment.getOpcode() == ISD::Constant &&
899            "Expecting a const value");
900
901     SmallVector<SDValue,8> Operands;
902     Operands.push_back(Chain.getOperand(0));
903     Operands.push_back(TargetAddress);
904     Operands.push_back(StackAdjustment);
905     // Copy registers used by the call. Last operand is a flag so it is not
906     // copied.
907     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
908       Operands.push_back(Chain.getOperand(i));
909     }
910     return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0], 
911                        Operands.size());
912   }
913   
914   // Regular return.
915   SDValue Flag;
916
917   SmallVector<SDValue, 6> RetOps;
918   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
919   // Operand #1 = Bytes To Pop
920   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
921   
922   // Copy the result values into the output registers.
923   for (unsigned i = 0; i != RVLocs.size(); ++i) {
924     CCValAssign &VA = RVLocs[i];
925     assert(VA.isRegLoc() && "Can only return in registers!");
926     SDValue ValToCopy = Op.getOperand(i*2+1);
927     
928     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
929     // the RET instruction and handled by the FP Stackifier.
930     if (RVLocs[i].getLocReg() == X86::ST0 ||
931         RVLocs[i].getLocReg() == X86::ST1) {
932       // If this is a copy from an xmm register to ST(0), use an FPExtend to
933       // change the value to the FP stack register class.
934       if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
935         ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
936       RetOps.push_back(ValToCopy);
937       // Don't emit a copytoreg.
938       continue;
939     }
940
941     Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
942     Flag = Chain.getValue(1);
943   }
944
945   // The x86-64 ABI for returning structs by value requires that we copy
946   // the sret argument into %rax for the return. We saved the argument into
947   // a virtual register in the entry block, so now we copy the value out
948   // and into %rax.
949   if (Subtarget->is64Bit() &&
950       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
951     MachineFunction &MF = DAG.getMachineFunction();
952     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
953     unsigned Reg = FuncInfo->getSRetReturnReg();
954     if (!Reg) {
955       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
956       FuncInfo->setSRetReturnReg(Reg);
957     }
958     SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
959
960     Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
961     Flag = Chain.getValue(1);
962   }
963   
964   RetOps[0] = Chain;  // Update chain.
965
966   // Add the flag if we have it.
967   if (Flag.getNode())
968     RetOps.push_back(Flag);
969   
970   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
971 }
972
973
974 /// LowerCallResult - Lower the result values of an ISD::CALL into the
975 /// appropriate copies out of appropriate physical registers.  This assumes that
976 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
977 /// being lowered.  The returns a SDNode with the same number of values as the
978 /// ISD::CALL.
979 SDNode *X86TargetLowering::
980 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall, 
981                 unsigned CallingConv, SelectionDAG &DAG) {
982   
983   // Assign locations to each value returned by this call.
984   SmallVector<CCValAssign, 16> RVLocs;
985   bool isVarArg = TheCall->isVarArg();
986   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
987   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
988
989   SmallVector<SDValue, 8> ResultVals;
990   
991   // Copy all of the result registers out of their specified physreg.
992   for (unsigned i = 0; i != RVLocs.size(); ++i) {
993     MVT CopyVT = RVLocs[i].getValVT();
994     
995     // If this is a call to a function that returns an fp value on the floating
996     // point stack, but where we prefer to use the value in xmm registers, copy
997     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
998     if ((RVLocs[i].getLocReg() == X86::ST0 ||
999          RVLocs[i].getLocReg() == X86::ST1) &&
1000         isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1001       CopyVT = MVT::f80;
1002     }
1003     
1004     Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1005                                CopyVT, InFlag).getValue(1);
1006     SDValue Val = Chain.getValue(0);
1007     InFlag = Chain.getValue(2);
1008
1009     if (CopyVT != RVLocs[i].getValVT()) {
1010       // Round the F80 the right size, which also moves to the appropriate xmm
1011       // register.
1012       Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1013                         // This truncation won't change the value.
1014                         DAG.getIntPtrConstant(1));
1015     }
1016     
1017     ResultVals.push_back(Val);
1018   }
1019
1020   // Merge everything together with a MERGE_VALUES node.
1021   ResultVals.push_back(Chain);
1022   return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1023                             ResultVals.size()).getNode();
1024 }
1025
1026
1027 //===----------------------------------------------------------------------===//
1028 //                C & StdCall & Fast Calling Convention implementation
1029 //===----------------------------------------------------------------------===//
1030 //  StdCall calling convention seems to be standard for many Windows' API
1031 //  routines and around. It differs from C calling convention just a little:
1032 //  callee should clean up the stack, not caller. Symbols should be also
1033 //  decorated in some fancy way :) It doesn't support any vector arguments.
1034 //  For info on fast calling convention see Fast Calling Convention (tail call)
1035 //  implementation LowerX86_32FastCCCallTo.
1036
1037 /// AddLiveIn - This helper function adds the specified physical register to the
1038 /// MachineFunction as a live in value.  It also creates a corresponding virtual
1039 /// register for it.
1040 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1041                           const TargetRegisterClass *RC) {
1042   assert(RC->contains(PReg) && "Not the correct regclass!");
1043   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1044   MF.getRegInfo().addLiveIn(PReg, VReg);
1045   return VReg;
1046 }
1047
1048 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1049 /// semantics.
1050 static bool CallIsStructReturn(CallSDNode *TheCall) {
1051   unsigned NumOps = TheCall->getNumArgs();
1052   if (!NumOps)
1053     return false;
1054
1055   return TheCall->getArgFlags(0).isSRet();
1056 }
1057
1058 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1059 /// return semantics.
1060 static bool ArgsAreStructReturn(SDValue Op) {
1061   unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1062   if (!NumArgs)
1063     return false;
1064
1065   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1066 }
1067
1068 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1069 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1070 /// calls.
1071 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1072   if (IsVarArg)
1073     return false;
1074
1075   switch (CallingConv) {
1076   default:
1077     return false;
1078   case CallingConv::X86_StdCall:
1079     return !Subtarget->is64Bit();
1080   case CallingConv::X86_FastCall:
1081     return !Subtarget->is64Bit();
1082   case CallingConv::Fast:
1083     return PerformTailCallOpt;
1084   }
1085 }
1086
1087 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1088 /// given CallingConvention value.
1089 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1090   if (Subtarget->is64Bit()) {
1091     if (Subtarget->isTargetWin64())
1092       return CC_X86_Win64_C;
1093     else if (CC == CallingConv::Fast && PerformTailCallOpt)
1094       return CC_X86_64_TailCall;
1095     else
1096       return CC_X86_64_C;
1097   }
1098
1099   if (CC == CallingConv::X86_FastCall)
1100     return CC_X86_32_FastCall;
1101   else if (CC == CallingConv::Fast && PerformTailCallOpt)
1102     return CC_X86_32_TailCall;
1103   else if (CC == CallingConv::Fast)
1104     return CC_X86_32_FastCC;
1105   else
1106     return CC_X86_32_C;
1107 }
1108
1109 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1110 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1111 NameDecorationStyle
1112 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1113   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1114   if (CC == CallingConv::X86_FastCall)
1115     return FastCall;
1116   else if (CC == CallingConv::X86_StdCall)
1117     return StdCall;
1118   return None;
1119 }
1120
1121
1122 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1123 /// in a register before calling.
1124 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1125   return !IsTailCall && !Is64Bit &&
1126     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1127     Subtarget->isPICStyleGOT();
1128 }
1129
1130 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1131 /// address to be loaded in a register.
1132 bool 
1133 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1134   return !Is64Bit && IsTailCall &&  
1135     getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1136     Subtarget->isPICStyleGOT();
1137 }
1138
1139 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1140 /// by "Src" to address "Dst" with size and alignment information specified by
1141 /// the specific parameter attribute. The copy will be passed as a byval
1142 /// function parameter.
1143 static SDValue 
1144 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1145                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1146   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1147   return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1148                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1149 }
1150
1151 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1152                                               const CCValAssign &VA,
1153                                               MachineFrameInfo *MFI,
1154                                               unsigned CC,
1155                                               SDValue Root, unsigned i) {
1156   // Create the nodes corresponding to a load from this parameter slot.
1157   ISD::ArgFlagsTy Flags =
1158     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1159   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1160   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1161
1162   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1163   // changed with more analysis.  
1164   // In case of tail call optimization mark all arguments mutable. Since they
1165   // could be overwritten by lowering of arguments in case of a tail call.
1166   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1167                                   VA.getLocMemOffset(), isImmutable);
1168   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1169   if (Flags.isByVal())
1170     return FIN;
1171   return DAG.getLoad(VA.getValVT(), Root, FIN,
1172                      PseudoSourceValue::getFixedStack(FI), 0);
1173 }
1174
1175 SDValue
1176 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1177   MachineFunction &MF = DAG.getMachineFunction();
1178   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1179   
1180   const Function* Fn = MF.getFunction();
1181   if (Fn->hasExternalLinkage() &&
1182       Subtarget->isTargetCygMing() &&
1183       Fn->getName() == "main")
1184     FuncInfo->setForceFramePointer(true);
1185
1186   // Decorate the function name.
1187   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1188   
1189   MachineFrameInfo *MFI = MF.getFrameInfo();
1190   SDValue Root = Op.getOperand(0);
1191   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1192   unsigned CC = MF.getFunction()->getCallingConv();
1193   bool Is64Bit = Subtarget->is64Bit();
1194   bool IsWin64 = Subtarget->isTargetWin64();
1195
1196   assert(!(isVarArg && CC == CallingConv::Fast) &&
1197          "Var args not supported with calling convention fastcc");
1198
1199   // Assign locations to all of the incoming arguments.
1200   SmallVector<CCValAssign, 16> ArgLocs;
1201   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1202   CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1203   
1204   SmallVector<SDValue, 8> ArgValues;
1205   unsigned LastVal = ~0U;
1206   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1207     CCValAssign &VA = ArgLocs[i];
1208     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1209     // places.
1210     assert(VA.getValNo() != LastVal &&
1211            "Don't support value assigned to multiple locs yet");
1212     LastVal = VA.getValNo();
1213     
1214     if (VA.isRegLoc()) {
1215       MVT RegVT = VA.getLocVT();
1216       TargetRegisterClass *RC;
1217       if (RegVT == MVT::i32)
1218         RC = X86::GR32RegisterClass;
1219       else if (Is64Bit && RegVT == MVT::i64)
1220         RC = X86::GR64RegisterClass;
1221       else if (RegVT == MVT::f32)
1222         RC = X86::FR32RegisterClass;
1223       else if (RegVT == MVT::f64)
1224         RC = X86::FR64RegisterClass;
1225       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1226         RC = X86::VR128RegisterClass;
1227       else if (RegVT.isVector()) {
1228         assert(RegVT.getSizeInBits() == 64);
1229         if (!Is64Bit)
1230           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1231         else {
1232           // Darwin calling convention passes MMX values in either GPRs or
1233           // XMMs in x86-64. Other targets pass them in memory.
1234           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1235             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1236             RegVT = MVT::v2i64;
1237           } else {
1238             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1239             RegVT = MVT::i64;
1240           }
1241         }
1242       } else {
1243         assert(0 && "Unknown argument type!");
1244       }
1245
1246       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1247       SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1248       
1249       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1250       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1251       // right size.
1252       if (VA.getLocInfo() == CCValAssign::SExt)
1253         ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1254                                DAG.getValueType(VA.getValVT()));
1255       else if (VA.getLocInfo() == CCValAssign::ZExt)
1256         ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1257                                DAG.getValueType(VA.getValVT()));
1258       
1259       if (VA.getLocInfo() != CCValAssign::Full)
1260         ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1261       
1262       // Handle MMX values passed in GPRs.
1263       if (Is64Bit && RegVT != VA.getLocVT()) {
1264         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1265           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1266         else if (RC == X86::VR128RegisterClass) {
1267           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1268                                  DAG.getConstant(0, MVT::i64));
1269           ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1270         }
1271       }
1272       
1273       ArgValues.push_back(ArgValue);
1274     } else {
1275       assert(VA.isMemLoc());
1276       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1277     }
1278   }
1279
1280   // The x86-64 ABI for returning structs by value requires that we copy
1281   // the sret argument into %rax for the return. Save the argument into
1282   // a virtual register so that we can access it from the return points.
1283   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1284     MachineFunction &MF = DAG.getMachineFunction();
1285     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286     unsigned Reg = FuncInfo->getSRetReturnReg();
1287     if (!Reg) {
1288       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1289       FuncInfo->setSRetReturnReg(Reg);
1290     }
1291     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1292     Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1293   }
1294
1295   unsigned StackSize = CCInfo.getNextStackOffset();
1296   // align stack specially for tail calls
1297   if (PerformTailCallOpt && CC == CallingConv::Fast)
1298     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1299
1300   // If the function takes variable number of arguments, make a frame index for
1301   // the start of the first vararg value... for expansion of llvm.va_start.
1302   if (isVarArg) {
1303     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1304       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1305     }
1306     if (Is64Bit) {
1307       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1308
1309       // FIXME: We should really autogenerate these arrays
1310       static const unsigned GPR64ArgRegsWin64[] = {
1311         X86::RCX, X86::RDX, X86::R8,  X86::R9
1312       };
1313       static const unsigned XMMArgRegsWin64[] = {
1314         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1315       };
1316       static const unsigned GPR64ArgRegs64Bit[] = {
1317         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1318       };
1319       static const unsigned XMMArgRegs64Bit[] = {
1320         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1321         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1322       };
1323       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1324
1325       if (IsWin64) {
1326         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1327         GPR64ArgRegs = GPR64ArgRegsWin64;
1328         XMMArgRegs = XMMArgRegsWin64;
1329       } else {
1330         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1331         GPR64ArgRegs = GPR64ArgRegs64Bit;
1332         XMMArgRegs = XMMArgRegs64Bit;
1333       }
1334       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1335                                                        TotalNumIntRegs);
1336       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1337                                                        TotalNumXMMRegs);
1338
1339       // For X86-64, if there are vararg parameters that are passed via
1340       // registers, then we must store them to their spots on the stack so they
1341       // may be loaded by deferencing the result of va_next.
1342       VarArgsGPOffset = NumIntRegs * 8;
1343       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1344       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1345                                                  TotalNumXMMRegs * 16, 16);
1346
1347       // Store the integer parameter registers.
1348       SmallVector<SDValue, 8> MemOps;
1349       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1350       SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1351                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1352       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1353         unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1354                                   X86::GR64RegisterClass);
1355         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1356         SDValue Store =
1357           DAG.getStore(Val.getValue(1), Val, FIN,
1358                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1359         MemOps.push_back(Store);
1360         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1361                           DAG.getIntPtrConstant(8));
1362       }
1363
1364       // Now store the XMM (fp + vector) parameter registers.
1365       FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1366                         DAG.getIntPtrConstant(VarArgsFPOffset));
1367       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1368         unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1369                                   X86::VR128RegisterClass);
1370         SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1371         SDValue Store =
1372           DAG.getStore(Val.getValue(1), Val, FIN,
1373                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1374         MemOps.push_back(Store);
1375         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1376                           DAG.getIntPtrConstant(16));
1377       }
1378       if (!MemOps.empty())
1379           Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1380                              &MemOps[0], MemOps.size());
1381     }
1382   }
1383   
1384   ArgValues.push_back(Root);
1385
1386   // Some CCs need callee pop.
1387   if (IsCalleePop(isVarArg, CC)) {
1388     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1389     BytesCallerReserves = 0;
1390   } else {
1391     BytesToPopOnReturn  = 0; // Callee pops nothing.
1392     // If this is an sret function, the return should pop the hidden pointer.
1393     if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1394       BytesToPopOnReturn = 4;  
1395     BytesCallerReserves = StackSize;
1396   }
1397
1398   if (!Is64Bit) {
1399     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1400     if (CC == CallingConv::X86_FastCall)
1401       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1402   }
1403
1404   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1405
1406   // Return the new list of results.
1407   return DAG.getMergeValues(Op.getNode()->getVTList(), &ArgValues[0],
1408                             ArgValues.size()).getValue(Op.getResNo());
1409 }
1410
1411 SDValue
1412 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1413                                     const SDValue &StackPtr,
1414                                     const CCValAssign &VA,
1415                                     SDValue Chain,
1416                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
1417   unsigned LocMemOffset = VA.getLocMemOffset();
1418   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1419   PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1420   if (Flags.isByVal()) {
1421     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1422   }
1423   return DAG.getStore(Chain, Arg, PtrOff,
1424                       PseudoSourceValue::getStack(), LocMemOffset);
1425 }
1426
1427 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1428 /// optimization is performed and it is required.
1429 SDValue 
1430 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG, 
1431                                            SDValue &OutRetAddr,
1432                                            SDValue Chain, 
1433                                            bool IsTailCall, 
1434                                            bool Is64Bit, 
1435                                            int FPDiff) {
1436   if (!IsTailCall || FPDiff==0) return Chain;
1437
1438   // Adjust the Return address stack slot.
1439   MVT VT = getPointerTy();
1440   OutRetAddr = getReturnAddressFrameIndex(DAG);
1441   // Load the "old" Return address.
1442   OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1443   return SDValue(OutRetAddr.getNode(), 1);
1444 }
1445
1446 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1447 /// optimization is performed and it is required (FPDiff!=0).
1448 static SDValue 
1449 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF, 
1450                          SDValue Chain, SDValue RetAddrFrIdx,
1451                          bool Is64Bit, int FPDiff) {
1452   // Store the return address to the appropriate stack slot.
1453   if (!FPDiff) return Chain;
1454   // Calculate the new stack slot for the return address.
1455   int SlotSize = Is64Bit ? 8 : 4;
1456   int NewReturnAddrFI = 
1457     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1458   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1459   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1460   Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx, 
1461                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1462   return Chain;
1463 }
1464
1465 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1466   MachineFunction &MF = DAG.getMachineFunction();
1467   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1468   SDValue Chain       = TheCall->getChain();
1469   unsigned CC         = TheCall->getCallingConv();
1470   bool isVarArg       = TheCall->isVarArg();
1471   bool IsTailCall     = TheCall->isTailCall() &&
1472                         CC == CallingConv::Fast && PerformTailCallOpt;
1473   SDValue Callee      = TheCall->getCallee();
1474   bool Is64Bit        = Subtarget->is64Bit();
1475   bool IsStructRet    = CallIsStructReturn(TheCall);
1476
1477   assert(!(isVarArg && CC == CallingConv::Fast) &&
1478          "Var args not supported with calling convention fastcc");
1479
1480   // Analyze operands of the call, assigning locations to each operand.
1481   SmallVector<CCValAssign, 16> ArgLocs;
1482   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1483   CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1484   
1485   // Get a count of how many bytes are to be pushed on the stack.
1486   unsigned NumBytes = CCInfo.getNextStackOffset();
1487   if (PerformTailCallOpt && CC == CallingConv::Fast)
1488     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1489
1490   int FPDiff = 0;
1491   if (IsTailCall) {
1492     // Lower arguments at fp - stackoffset + fpdiff.
1493     unsigned NumBytesCallerPushed = 
1494       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1495     FPDiff = NumBytesCallerPushed - NumBytes;
1496
1497     // Set the delta of movement of the returnaddr stackslot.
1498     // But only set if delta is greater than previous delta.
1499     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1500       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1501   }
1502
1503   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1504
1505   SDValue RetAddrFrIdx;
1506   // Load return adress for tail calls.
1507   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1508                                   FPDiff);
1509
1510   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1511   SmallVector<SDValue, 8> MemOpChains;
1512   SDValue StackPtr;
1513
1514   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1515   // of tail call optimization arguments are handle later.
1516   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1517     CCValAssign &VA = ArgLocs[i];
1518     SDValue Arg = TheCall->getArg(i);
1519     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1520     bool isByVal = Flags.isByVal();
1521   
1522     // Promote the value if needed.
1523     switch (VA.getLocInfo()) {
1524     default: assert(0 && "Unknown loc info!");
1525     case CCValAssign::Full: break;
1526     case CCValAssign::SExt:
1527       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1528       break;
1529     case CCValAssign::ZExt:
1530       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1531       break;
1532     case CCValAssign::AExt:
1533       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1534       break;
1535     }
1536     
1537     if (VA.isRegLoc()) {
1538       if (Is64Bit) {
1539         MVT RegVT = VA.getLocVT();
1540         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1541           switch (VA.getLocReg()) {
1542           default:
1543             break;
1544           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1545           case X86::R8: {
1546             // Special case: passing MMX values in GPR registers.
1547             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1548             break;
1549           }
1550           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1551           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1552             // Special case: passing MMX values in XMM registers.
1553             Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1554             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1555             Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1556                               DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1557                               getMOVLMask(2, DAG));
1558             break;
1559           }
1560           }
1561       }
1562       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1563     } else {
1564       if (!IsTailCall || (IsTailCall && isByVal)) {
1565         assert(VA.isMemLoc());
1566         if (StackPtr.getNode() == 0)
1567           StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1568         
1569         MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1570                                                Chain, Arg, Flags));
1571       }
1572     }
1573   }
1574   
1575   if (!MemOpChains.empty())
1576     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1577                         &MemOpChains[0], MemOpChains.size());
1578
1579   // Build a sequence of copy-to-reg nodes chained together with token chain
1580   // and flag operands which copy the outgoing args into registers.
1581   SDValue InFlag;
1582   // Tail call byval lowering might overwrite argument registers so in case of
1583   // tail call optimization the copies to registers are lowered later.
1584   if (!IsTailCall)
1585     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1586       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1587                                InFlag);
1588       InFlag = Chain.getValue(1);
1589     }
1590
1591   // ELF / PIC requires GOT in the EBX register before function calls via PLT
1592   // GOT pointer.  
1593   if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1594     Chain = DAG.getCopyToReg(Chain, X86::EBX,
1595                              DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1596                              InFlag);
1597     InFlag = Chain.getValue(1);
1598   }
1599   // If we are tail calling and generating PIC/GOT style code load the address
1600   // of the callee into ecx. The value in ecx is used as target of the tail
1601   // jump. This is done to circumvent the ebx/callee-saved problem for tail
1602   // calls on PIC/GOT architectures. Normally we would just put the address of
1603   // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1604   // restored (since ebx is callee saved) before jumping to the target@PLT.
1605   if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1606     // Note: The actual moving to ecx is done further down.
1607     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1608     if (G &&  !G->getGlobal()->hasHiddenVisibility() &&
1609         !G->getGlobal()->hasProtectedVisibility())
1610       Callee =  LowerGlobalAddress(Callee, DAG);
1611     else if (isa<SymbolSDNode>(Callee))
1612       Callee = LowerExternalSymbol(Callee, DAG);
1613   }
1614
1615   if (Is64Bit && isVarArg) {
1616     // From AMD64 ABI document:
1617     // For calls that may call functions that use varargs or stdargs
1618     // (prototype-less calls or calls to functions containing ellipsis (...) in
1619     // the declaration) %al is used as hidden argument to specify the number
1620     // of SSE registers used. The contents of %al do not need to match exactly
1621     // the number of registers, but must be an ubound on the number of SSE
1622     // registers used and is in the range 0 - 8 inclusive.
1623
1624     // FIXME: Verify this on Win64
1625     // Count the number of XMM registers allocated.
1626     static const unsigned XMMArgRegs[] = {
1627       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1628       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1629     };
1630     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1631     
1632     Chain = DAG.getCopyToReg(Chain, X86::AL,
1633                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1634     InFlag = Chain.getValue(1);
1635   }
1636
1637
1638   // For tail calls lower the arguments to the 'real' stack slot.
1639   if (IsTailCall) {
1640     SmallVector<SDValue, 8> MemOpChains2;
1641     SDValue FIN;
1642     int FI = 0;
1643     // Do not flag preceeding copytoreg stuff together with the following stuff.
1644     InFlag = SDValue();
1645     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1646       CCValAssign &VA = ArgLocs[i];
1647       if (!VA.isRegLoc()) {
1648         assert(VA.isMemLoc());
1649         SDValue Arg = TheCall->getArg(i);
1650         ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1651         // Create frame index.
1652         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1653         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1654         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1655         FIN = DAG.getFrameIndex(FI, getPointerTy());
1656
1657         if (Flags.isByVal()) {
1658           // Copy relative to framepointer.
1659           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1660           if (StackPtr.getNode() == 0)
1661             StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1662           Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1663
1664           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1665                                                            Flags, DAG));
1666         } else {
1667           // Store relative to framepointer.
1668           MemOpChains2.push_back(
1669             DAG.getStore(Chain, Arg, FIN,
1670                          PseudoSourceValue::getFixedStack(FI), 0));
1671         }            
1672       }
1673     }
1674
1675     if (!MemOpChains2.empty())
1676       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1677                           &MemOpChains2[0], MemOpChains2.size());
1678
1679     // Copy arguments to their registers.
1680     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1681       Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1682                                InFlag);
1683       InFlag = Chain.getValue(1);
1684     }
1685     InFlag =SDValue();
1686
1687     // Store the return address to the appropriate stack slot.
1688     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1689                                      FPDiff);
1690   }
1691
1692   // If the callee is a GlobalAddress node (quite common, every direct call is)
1693   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1694   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1695     // We should use extra load for direct calls to dllimported functions in
1696     // non-JIT mode.
1697     if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1698                                         getTargetMachine(), true))
1699       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1700   } else if (SymbolSDNode *S = dyn_cast<SymbolSDNode>(Callee)) {
1701     Callee = DAG.getTargetSymbol(S->getSymbol(), getPointerTy(),
1702                                  S->getLinkage());
1703   } else if (IsTailCall) {
1704     unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1705
1706     Chain = DAG.getCopyToReg(Chain, 
1707                              DAG.getRegister(Opc, getPointerTy()), 
1708                              Callee,InFlag);
1709     Callee = DAG.getRegister(Opc, getPointerTy());
1710     // Add register as live out.
1711     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1712   }
1713  
1714   // Returns a chain & a flag for retval copy to use.
1715   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1716   SmallVector<SDValue, 8> Ops;
1717
1718   if (IsTailCall) {
1719     Ops.push_back(Chain);
1720     Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1721     Ops.push_back(DAG.getIntPtrConstant(0));
1722     if (InFlag.getNode())
1723       Ops.push_back(InFlag);
1724     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1725     InFlag = Chain.getValue(1);
1726  
1727     // Returns a chain & a flag for retval copy to use.
1728     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1729     Ops.clear();
1730   }
1731   
1732   Ops.push_back(Chain);
1733   Ops.push_back(Callee);
1734
1735   if (IsTailCall)
1736     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1737
1738   // Add argument registers to the end of the list so that they are known live
1739   // into the call.
1740   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1741     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1742                                   RegsToPass[i].second.getValueType()));
1743   
1744   // Add an implicit use GOT pointer in EBX.
1745   if (!IsTailCall && !Is64Bit &&
1746       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1747       Subtarget->isPICStyleGOT())
1748     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1749
1750   // Add an implicit use of AL for x86 vararg functions.
1751   if (Is64Bit && isVarArg)
1752     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1753
1754   if (InFlag.getNode())
1755     Ops.push_back(InFlag);
1756
1757   if (IsTailCall) {
1758     assert(InFlag.getNode() && 
1759            "Flag must be set. Depend on flag being set in LowerRET");
1760     Chain = DAG.getNode(X86ISD::TAILCALL,
1761                         TheCall->getVTList(), &Ops[0], Ops.size());
1762       
1763     return SDValue(Chain.getNode(), Op.getResNo());
1764   }
1765
1766   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1767   InFlag = Chain.getValue(1);
1768
1769   // Create the CALLSEQ_END node.
1770   unsigned NumBytesForCalleeToPush;
1771   if (IsCalleePop(isVarArg, CC))
1772     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1773   else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1774     // If this is is a call to a struct-return function, the callee
1775     // pops the hidden struct pointer, so we have to push it back.
1776     // This is common for Darwin/X86, Linux & Mingw32 targets.
1777     NumBytesForCalleeToPush = 4;
1778   else
1779     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1780   
1781   // Returns a flag for retval copy to use.
1782   Chain = DAG.getCALLSEQ_END(Chain,
1783                              DAG.getIntPtrConstant(NumBytes),
1784                              DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1785                              InFlag);
1786   InFlag = Chain.getValue(1);
1787
1788   // Handle result values, copying them out of physregs into vregs that we
1789   // return.
1790   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1791                  Op.getResNo());
1792 }
1793
1794
1795 //===----------------------------------------------------------------------===//
1796 //                Fast Calling Convention (tail call) implementation
1797 //===----------------------------------------------------------------------===//
1798
1799 //  Like std call, callee cleans arguments, convention except that ECX is
1800 //  reserved for storing the tail called function address. Only 2 registers are
1801 //  free for argument passing (inreg). Tail call optimization is performed
1802 //  provided:
1803 //                * tailcallopt is enabled
1804 //                * caller/callee are fastcc
1805 //  On X86_64 architecture with GOT-style position independent code only local
1806 //  (within module) calls are supported at the moment.
1807 //  To keep the stack aligned according to platform abi the function
1808 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1809 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1810 //  If a tail called function callee has more arguments than the caller the
1811 //  caller needs to make sure that there is room to move the RETADDR to. This is
1812 //  achieved by reserving an area the size of the argument delta right after the
1813 //  original REtADDR, but before the saved framepointer or the spilled registers
1814 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1815 //  stack layout:
1816 //    arg1
1817 //    arg2
1818 //    RETADDR
1819 //    [ new RETADDR 
1820 //      move area ]
1821 //    (possible EBP)
1822 //    ESI
1823 //    EDI
1824 //    local1 ..
1825
1826 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1827 /// for a 16 byte align requirement.
1828 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1829                                                         SelectionDAG& DAG) {
1830   MachineFunction &MF = DAG.getMachineFunction();
1831   const TargetMachine &TM = MF.getTarget();
1832   const TargetFrameInfo &TFI = *TM.getFrameInfo();
1833   unsigned StackAlignment = TFI.getStackAlignment();
1834   uint64_t AlignMask = StackAlignment - 1; 
1835   int64_t Offset = StackSize;
1836   uint64_t SlotSize = TD->getPointerSize();
1837   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1838     // Number smaller than 12 so just add the difference.
1839     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1840   } else {
1841     // Mask out lower bits, add stackalignment once plus the 12 bytes.
1842     Offset = ((~AlignMask) & Offset) + StackAlignment + 
1843       (StackAlignment-SlotSize);
1844   }
1845   return Offset;
1846 }
1847
1848 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1849 /// following the call is a return. A function is eligible if caller/callee
1850 /// calling conventions match, currently only fastcc supports tail calls, and
1851 /// the function CALL is immediatly followed by a RET.
1852 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1853                                                       SDValue Ret,
1854                                                       SelectionDAG& DAG) const {
1855   if (!PerformTailCallOpt)
1856     return false;
1857
1858   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1859     MachineFunction &MF = DAG.getMachineFunction();
1860     unsigned CallerCC = MF.getFunction()->getCallingConv();
1861     unsigned CalleeCC= TheCall->getCallingConv();
1862     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1863       SDValue Callee = TheCall->getCallee();
1864       // On x86/32Bit PIC/GOT  tail calls are supported.
1865       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1866           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1867         return true;
1868
1869       // Can only do local tail calls (in same module, hidden or protected) on
1870       // x86_64 PIC/GOT at the moment.
1871       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1872         return G->getGlobal()->hasHiddenVisibility()
1873             || G->getGlobal()->hasProtectedVisibility();
1874     }
1875   }
1876
1877   return false;
1878 }
1879
1880 FastISel *
1881 X86TargetLowering::createFastISel(MachineFunction &mf,
1882                                   DenseMap<const Value *, unsigned> &vm,
1883                                   DenseMap<const BasicBlock *,
1884                                            MachineBasicBlock *> &bm,
1885                                   DenseMap<const AllocaInst *, int> &am) {
1886                                          
1887   return X86::createFastISel(mf, vm, bm, am);
1888 }
1889
1890
1891 //===----------------------------------------------------------------------===//
1892 //                           Other Lowering Hooks
1893 //===----------------------------------------------------------------------===//
1894
1895
1896 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1897   MachineFunction &MF = DAG.getMachineFunction();
1898   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1899   int ReturnAddrIndex = FuncInfo->getRAIndex();
1900   uint64_t SlotSize = TD->getPointerSize();
1901
1902   if (ReturnAddrIndex == 0) {
1903     // Set up a frame object for the return address.
1904     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1905     FuncInfo->setRAIndex(ReturnAddrIndex);
1906   }
1907
1908   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1909 }
1910
1911
1912 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1913 /// specific condition code. It returns a false if it cannot do a direct
1914 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1915 /// needed.
1916 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1917                            unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1918                            SelectionDAG &DAG) {
1919   X86CC = X86::COND_INVALID;
1920   if (!isFP) {
1921     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1922       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1923         // X > -1   -> X == 0, jump !sign.
1924         RHS = DAG.getConstant(0, RHS.getValueType());
1925         X86CC = X86::COND_NS;
1926         return true;
1927       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1928         // X < 0   -> X == 0, jump on sign.
1929         X86CC = X86::COND_S;
1930         return true;
1931       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1932         // X < 1   -> X <= 0
1933         RHS = DAG.getConstant(0, RHS.getValueType());
1934         X86CC = X86::COND_LE;
1935         return true;
1936       }
1937     }
1938
1939     switch (SetCCOpcode) {
1940     default: break;
1941     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1942     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1943     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1944     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1945     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1946     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1947     case ISD::SETULT: X86CC = X86::COND_B;  break;
1948     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1949     case ISD::SETULE: X86CC = X86::COND_BE; break;
1950     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1951     }
1952   } else {
1953     // First determine if it requires or is profitable to flip the operands.
1954     bool Flip = false;
1955     switch (SetCCOpcode) {
1956     default: break;
1957     case ISD::SETOLT:
1958     case ISD::SETOLE:
1959     case ISD::SETUGT:
1960     case ISD::SETUGE:
1961       Flip = true;
1962       break;
1963     }
1964
1965     // If LHS is a foldable load, but RHS is not, flip the condition.
1966     if (!Flip &&
1967         (ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1968         !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1969       SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1970       Flip = true;
1971     }
1972     if (Flip)
1973       std::swap(LHS, RHS);
1974
1975     // On a floating point condition, the flags are set as follows:
1976     // ZF  PF  CF   op
1977     //  0 | 0 | 0 | X > Y
1978     //  0 | 0 | 1 | X < Y
1979     //  1 | 0 | 0 | X == Y
1980     //  1 | 1 | 1 | unordered
1981     switch (SetCCOpcode) {
1982     default: break;
1983     case ISD::SETUEQ:
1984     case ISD::SETEQ:
1985       X86CC = X86::COND_E;
1986       break;
1987     case ISD::SETOLT:              // flipped
1988     case ISD::SETOGT:
1989     case ISD::SETGT:
1990       X86CC = X86::COND_A;
1991       break;
1992     case ISD::SETOLE:              // flipped
1993     case ISD::SETOGE:
1994     case ISD::SETGE:
1995       X86CC = X86::COND_AE;
1996       break;
1997     case ISD::SETUGT:              // flipped
1998     case ISD::SETULT:
1999     case ISD::SETLT:
2000       X86CC = X86::COND_B;
2001       break;
2002     case ISD::SETUGE:              // flipped
2003     case ISD::SETULE:
2004     case ISD::SETLE:
2005       X86CC = X86::COND_BE;
2006       break;
2007     case ISD::SETONE:
2008     case ISD::SETNE:
2009       X86CC = X86::COND_NE;
2010       break;
2011     case ISD::SETUO:
2012       X86CC = X86::COND_P;
2013       break;
2014     case ISD::SETO:
2015       X86CC = X86::COND_NP;
2016       break;
2017     }
2018   }
2019
2020   return X86CC != X86::COND_INVALID;
2021 }
2022
2023 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2024 /// code. Current x86 isa includes the following FP cmov instructions:
2025 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2026 static bool hasFPCMov(unsigned X86CC) {
2027   switch (X86CC) {
2028   default:
2029     return false;
2030   case X86::COND_B:
2031   case X86::COND_BE:
2032   case X86::COND_E:
2033   case X86::COND_P:
2034   case X86::COND_A:
2035   case X86::COND_AE:
2036   case X86::COND_NE:
2037   case X86::COND_NP:
2038     return true;
2039   }
2040 }
2041
2042 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
2043 /// true if Op is undef or if its value falls within the specified range (L, H].
2044 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2045   if (Op.getOpcode() == ISD::UNDEF)
2046     return true;
2047
2048   unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2049   return (Val >= Low && Val < Hi);
2050 }
2051
2052 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2053 /// true if Op is undef or if its value equal to the specified value.
2054 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2055   if (Op.getOpcode() == ISD::UNDEF)
2056     return true;
2057   return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2058 }
2059
2060 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2061 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2062 bool X86::isPSHUFDMask(SDNode *N) {
2063   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2064
2065   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2066     return false;
2067
2068   // Check if the value doesn't reference the second vector.
2069   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2070     SDValue Arg = N->getOperand(i);
2071     if (Arg.getOpcode() == ISD::UNDEF) continue;
2072     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2073     if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2074       return false;
2075   }
2076
2077   return true;
2078 }
2079
2080 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2081 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2082 bool X86::isPSHUFHWMask(SDNode *N) {
2083   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2084
2085   if (N->getNumOperands() != 8)
2086     return false;
2087
2088   // Lower quadword copied in order.
2089   for (unsigned i = 0; i != 4; ++i) {
2090     SDValue Arg = N->getOperand(i);
2091     if (Arg.getOpcode() == ISD::UNDEF) continue;
2092     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2093     if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2094       return false;
2095   }
2096
2097   // Upper quadword shuffled.
2098   for (unsigned i = 4; i != 8; ++i) {
2099     SDValue Arg = N->getOperand(i);
2100     if (Arg.getOpcode() == ISD::UNDEF) continue;
2101     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2102     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2103     if (Val < 4 || Val > 7)
2104       return false;
2105   }
2106
2107   return true;
2108 }
2109
2110 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2111 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2112 bool X86::isPSHUFLWMask(SDNode *N) {
2113   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2114
2115   if (N->getNumOperands() != 8)
2116     return false;
2117
2118   // Upper quadword copied in order.
2119   for (unsigned i = 4; i != 8; ++i)
2120     if (!isUndefOrEqual(N->getOperand(i), i))
2121       return false;
2122
2123   // Lower quadword shuffled.
2124   for (unsigned i = 0; i != 4; ++i)
2125     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2126       return false;
2127
2128   return true;
2129 }
2130
2131 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2132 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2133 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2134   if (NumElems != 2 && NumElems != 4) return false;
2135
2136   unsigned Half = NumElems / 2;
2137   for (unsigned i = 0; i < Half; ++i)
2138     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2139       return false;
2140   for (unsigned i = Half; i < NumElems; ++i)
2141     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2142       return false;
2143
2144   return true;
2145 }
2146
2147 bool X86::isSHUFPMask(SDNode *N) {
2148   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2149   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2150 }
2151
2152 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2153 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2154 /// half elements to come from vector 1 (which would equal the dest.) and
2155 /// the upper half to come from vector 2.
2156 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2157   if (NumOps != 2 && NumOps != 4) return false;
2158
2159   unsigned Half = NumOps / 2;
2160   for (unsigned i = 0; i < Half; ++i)
2161     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2162       return false;
2163   for (unsigned i = Half; i < NumOps; ++i)
2164     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2165       return false;
2166   return true;
2167 }
2168
2169 static bool isCommutedSHUFP(SDNode *N) {
2170   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2171   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2172 }
2173
2174 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2175 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2176 bool X86::isMOVHLPSMask(SDNode *N) {
2177   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178
2179   if (N->getNumOperands() != 4)
2180     return false;
2181
2182   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2183   return isUndefOrEqual(N->getOperand(0), 6) &&
2184          isUndefOrEqual(N->getOperand(1), 7) &&
2185          isUndefOrEqual(N->getOperand(2), 2) &&
2186          isUndefOrEqual(N->getOperand(3), 3);
2187 }
2188
2189 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2190 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2191 /// <2, 3, 2, 3>
2192 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2193   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2194
2195   if (N->getNumOperands() != 4)
2196     return false;
2197
2198   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2199   return isUndefOrEqual(N->getOperand(0), 2) &&
2200          isUndefOrEqual(N->getOperand(1), 3) &&
2201          isUndefOrEqual(N->getOperand(2), 2) &&
2202          isUndefOrEqual(N->getOperand(3), 3);
2203 }
2204
2205 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2206 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2207 bool X86::isMOVLPMask(SDNode *N) {
2208   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2209
2210   unsigned NumElems = N->getNumOperands();
2211   if (NumElems != 2 && NumElems != 4)
2212     return false;
2213
2214   for (unsigned i = 0; i < NumElems/2; ++i)
2215     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2216       return false;
2217
2218   for (unsigned i = NumElems/2; i < NumElems; ++i)
2219     if (!isUndefOrEqual(N->getOperand(i), i))
2220       return false;
2221
2222   return true;
2223 }
2224
2225 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2226 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2227 /// and MOVLHPS.
2228 bool X86::isMOVHPMask(SDNode *N) {
2229   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2230
2231   unsigned NumElems = N->getNumOperands();
2232   if (NumElems != 2 && NumElems != 4)
2233     return false;
2234
2235   for (unsigned i = 0; i < NumElems/2; ++i)
2236     if (!isUndefOrEqual(N->getOperand(i), i))
2237       return false;
2238
2239   for (unsigned i = 0; i < NumElems/2; ++i) {
2240     SDValue Arg = N->getOperand(i + NumElems/2);
2241     if (!isUndefOrEqual(Arg, i + NumElems))
2242       return false;
2243   }
2244
2245   return true;
2246 }
2247
2248 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2249 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2250 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2251                          bool V2IsSplat = false) {
2252   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2253     return false;
2254
2255   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2256     SDValue BitI  = Elts[i];
2257     SDValue BitI1 = Elts[i+1];
2258     if (!isUndefOrEqual(BitI, j))
2259       return false;
2260     if (V2IsSplat) {
2261       if (isUndefOrEqual(BitI1, NumElts))
2262         return false;
2263     } else {
2264       if (!isUndefOrEqual(BitI1, j + NumElts))
2265         return false;
2266     }
2267   }
2268
2269   return true;
2270 }
2271
2272 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2273   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2274   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2275 }
2276
2277 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2278 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2279 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2280                          bool V2IsSplat = false) {
2281   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2282     return false;
2283
2284   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2285     SDValue BitI  = Elts[i];
2286     SDValue BitI1 = Elts[i+1];
2287     if (!isUndefOrEqual(BitI, j + NumElts/2))
2288       return false;
2289     if (V2IsSplat) {
2290       if (isUndefOrEqual(BitI1, NumElts))
2291         return false;
2292     } else {
2293       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2294         return false;
2295     }
2296   }
2297
2298   return true;
2299 }
2300
2301 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2302   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2303   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2304 }
2305
2306 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2307 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2308 /// <0, 0, 1, 1>
2309 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2310   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2311
2312   unsigned NumElems = N->getNumOperands();
2313   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2314     return false;
2315
2316   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2317     SDValue BitI  = N->getOperand(i);
2318     SDValue BitI1 = N->getOperand(i+1);
2319
2320     if (!isUndefOrEqual(BitI, j))
2321       return false;
2322     if (!isUndefOrEqual(BitI1, j))
2323       return false;
2324   }
2325
2326   return true;
2327 }
2328
2329 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2330 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2331 /// <2, 2, 3, 3>
2332 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2333   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2334
2335   unsigned NumElems = N->getNumOperands();
2336   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2337     return false;
2338
2339   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2340     SDValue BitI  = N->getOperand(i);
2341     SDValue BitI1 = N->getOperand(i + 1);
2342
2343     if (!isUndefOrEqual(BitI, j))
2344       return false;
2345     if (!isUndefOrEqual(BitI1, j))
2346       return false;
2347   }
2348
2349   return true;
2350 }
2351
2352 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2353 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2354 /// MOVSD, and MOVD, i.e. setting the lowest element.
2355 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2356   if (NumElts != 2 && NumElts != 4)
2357     return false;
2358
2359   if (!isUndefOrEqual(Elts[0], NumElts))
2360     return false;
2361
2362   for (unsigned i = 1; i < NumElts; ++i) {
2363     if (!isUndefOrEqual(Elts[i], i))
2364       return false;
2365   }
2366
2367   return true;
2368 }
2369
2370 bool X86::isMOVLMask(SDNode *N) {
2371   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2372   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2373 }
2374
2375 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2376 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2377 /// element of vector 2 and the other elements to come from vector 1 in order.
2378 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2379                            bool V2IsSplat = false,
2380                            bool V2IsUndef = false) {
2381   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2382     return false;
2383
2384   if (!isUndefOrEqual(Ops[0], 0))
2385     return false;
2386
2387   for (unsigned i = 1; i < NumOps; ++i) {
2388     SDValue Arg = Ops[i];
2389     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2390           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2391           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2392       return false;
2393   }
2394
2395   return true;
2396 }
2397
2398 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2399                            bool V2IsUndef = false) {
2400   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2401   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2402                         V2IsSplat, V2IsUndef);
2403 }
2404
2405 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2406 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2407 bool X86::isMOVSHDUPMask(SDNode *N) {
2408   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2409
2410   if (N->getNumOperands() != 4)
2411     return false;
2412
2413   // Expect 1, 1, 3, 3
2414   for (unsigned i = 0; i < 2; ++i) {
2415     SDValue Arg = N->getOperand(i);
2416     if (Arg.getOpcode() == ISD::UNDEF) continue;
2417     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2418     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2419     if (Val != 1) return false;
2420   }
2421
2422   bool HasHi = false;
2423   for (unsigned i = 2; i < 4; ++i) {
2424     SDValue Arg = N->getOperand(i);
2425     if (Arg.getOpcode() == ISD::UNDEF) continue;
2426     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2427     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2428     if (Val != 3) return false;
2429     HasHi = true;
2430   }
2431
2432   // Don't use movshdup if it can be done with a shufps.
2433   return HasHi;
2434 }
2435
2436 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2437 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2438 bool X86::isMOVSLDUPMask(SDNode *N) {
2439   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2440
2441   if (N->getNumOperands() != 4)
2442     return false;
2443
2444   // Expect 0, 0, 2, 2
2445   for (unsigned i = 0; i < 2; ++i) {
2446     SDValue Arg = N->getOperand(i);
2447     if (Arg.getOpcode() == ISD::UNDEF) continue;
2448     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2449     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2450     if (Val != 0) return false;
2451   }
2452
2453   bool HasHi = false;
2454   for (unsigned i = 2; i < 4; ++i) {
2455     SDValue Arg = N->getOperand(i);
2456     if (Arg.getOpcode() == ISD::UNDEF) continue;
2457     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2458     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2459     if (Val != 2) return false;
2460     HasHi = true;
2461   }
2462
2463   // Don't use movshdup if it can be done with a shufps.
2464   return HasHi;
2465 }
2466
2467 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2468 /// specifies a identity operation on the LHS or RHS.
2469 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2470   unsigned NumElems = N->getNumOperands();
2471   for (unsigned i = 0; i < NumElems; ++i)
2472     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2473       return false;
2474   return true;
2475 }
2476
2477 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2478 /// a splat of a single element.
2479 static bool isSplatMask(SDNode *N) {
2480   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2481
2482   // This is a splat operation if each element of the permute is the same, and
2483   // if the value doesn't reference the second vector.
2484   unsigned NumElems = N->getNumOperands();
2485   SDValue ElementBase;
2486   unsigned i = 0;
2487   for (; i != NumElems; ++i) {
2488     SDValue Elt = N->getOperand(i);
2489     if (isa<ConstantSDNode>(Elt)) {
2490       ElementBase = Elt;
2491       break;
2492     }
2493   }
2494
2495   if (!ElementBase.getNode())
2496     return false;
2497
2498   for (; i != NumElems; ++i) {
2499     SDValue Arg = N->getOperand(i);
2500     if (Arg.getOpcode() == ISD::UNDEF) continue;
2501     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2502     if (Arg != ElementBase) return false;
2503   }
2504
2505   // Make sure it is a splat of the first vector operand.
2506   return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2507 }
2508
2509 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2510 /// a splat of a single element and it's a 2 or 4 element mask.
2511 bool X86::isSplatMask(SDNode *N) {
2512   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2513
2514   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2515   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2516     return false;
2517   return ::isSplatMask(N);
2518 }
2519
2520 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2521 /// specifies a splat of zero element.
2522 bool X86::isSplatLoMask(SDNode *N) {
2523   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2524
2525   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2526     if (!isUndefOrEqual(N->getOperand(i), 0))
2527       return false;
2528   return true;
2529 }
2530
2531 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2532 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2533 /// instructions.
2534 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2535   unsigned NumOperands = N->getNumOperands();
2536   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2537   unsigned Mask = 0;
2538   for (unsigned i = 0; i < NumOperands; ++i) {
2539     unsigned Val = 0;
2540     SDValue Arg = N->getOperand(NumOperands-i-1);
2541     if (Arg.getOpcode() != ISD::UNDEF)
2542       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2543     if (Val >= NumOperands) Val -= NumOperands;
2544     Mask |= Val;
2545     if (i != NumOperands - 1)
2546       Mask <<= Shift;
2547   }
2548
2549   return Mask;
2550 }
2551
2552 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2553 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2554 /// instructions.
2555 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2556   unsigned Mask = 0;
2557   // 8 nodes, but we only care about the last 4.
2558   for (unsigned i = 7; i >= 4; --i) {
2559     unsigned Val = 0;
2560     SDValue Arg = N->getOperand(i);
2561     if (Arg.getOpcode() != ISD::UNDEF)
2562       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2563     Mask |= (Val - 4);
2564     if (i != 4)
2565       Mask <<= 2;
2566   }
2567
2568   return Mask;
2569 }
2570
2571 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2572 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2573 /// instructions.
2574 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2575   unsigned Mask = 0;
2576   // 8 nodes, but we only care about the first 4.
2577   for (int i = 3; i >= 0; --i) {
2578     unsigned Val = 0;
2579     SDValue Arg = N->getOperand(i);
2580     if (Arg.getOpcode() != ISD::UNDEF)
2581       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2582     Mask |= Val;
2583     if (i != 0)
2584       Mask <<= 2;
2585   }
2586
2587   return Mask;
2588 }
2589
2590 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2591 /// specifies a 8 element shuffle that can be broken into a pair of
2592 /// PSHUFHW and PSHUFLW.
2593 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2594   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2595
2596   if (N->getNumOperands() != 8)
2597     return false;
2598
2599   // Lower quadword shuffled.
2600   for (unsigned i = 0; i != 4; ++i) {
2601     SDValue Arg = N->getOperand(i);
2602     if (Arg.getOpcode() == ISD::UNDEF) continue;
2603     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2604     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2605     if (Val >= 4)
2606       return false;
2607   }
2608
2609   // Upper quadword shuffled.
2610   for (unsigned i = 4; i != 8; ++i) {
2611     SDValue Arg = N->getOperand(i);
2612     if (Arg.getOpcode() == ISD::UNDEF) continue;
2613     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2614     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2615     if (Val < 4 || Val > 7)
2616       return false;
2617   }
2618
2619   return true;
2620 }
2621
2622 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2623 /// values in ther permute mask.
2624 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2625                                       SDValue &V2, SDValue &Mask,
2626                                       SelectionDAG &DAG) {
2627   MVT VT = Op.getValueType();
2628   MVT MaskVT = Mask.getValueType();
2629   MVT EltVT = MaskVT.getVectorElementType();
2630   unsigned NumElems = Mask.getNumOperands();
2631   SmallVector<SDValue, 8> MaskVec;
2632
2633   for (unsigned i = 0; i != NumElems; ++i) {
2634     SDValue Arg = Mask.getOperand(i);
2635     if (Arg.getOpcode() == ISD::UNDEF) {
2636       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2637       continue;
2638     }
2639     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2640     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2641     if (Val < NumElems)
2642       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2643     else
2644       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2645   }
2646
2647   std::swap(V1, V2);
2648   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2649   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2650 }
2651
2652 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2653 /// the two vector operands have swapped position.
2654 static
2655 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2656   MVT MaskVT = Mask.getValueType();
2657   MVT EltVT = MaskVT.getVectorElementType();
2658   unsigned NumElems = Mask.getNumOperands();
2659   SmallVector<SDValue, 8> MaskVec;
2660   for (unsigned i = 0; i != NumElems; ++i) {
2661     SDValue Arg = Mask.getOperand(i);
2662     if (Arg.getOpcode() == ISD::UNDEF) {
2663       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2664       continue;
2665     }
2666     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2667     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2668     if (Val < NumElems)
2669       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2670     else
2671       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2672   }
2673   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2674 }
2675
2676
2677 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2678 /// match movhlps. The lower half elements should come from upper half of
2679 /// V1 (and in order), and the upper half elements should come from the upper
2680 /// half of V2 (and in order).
2681 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2682   unsigned NumElems = Mask->getNumOperands();
2683   if (NumElems != 4)
2684     return false;
2685   for (unsigned i = 0, e = 2; i != e; ++i)
2686     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2687       return false;
2688   for (unsigned i = 2; i != 4; ++i)
2689     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2690       return false;
2691   return true;
2692 }
2693
2694 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2695 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2696 /// required.
2697 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2698   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2699     N = N->getOperand(0).getNode();
2700     if (ISD::isNON_EXTLoad(N)) {
2701       if (LD)
2702         *LD = cast<LoadSDNode>(N);
2703       return true;
2704     }
2705   }
2706   return false;
2707 }
2708
2709 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2710 /// match movlp{s|d}. The lower half elements should come from lower half of
2711 /// V1 (and in order), and the upper half elements should come from the upper
2712 /// half of V2 (and in order). And since V1 will become the source of the
2713 /// MOVLP, it must be either a vector load or a scalar load to vector.
2714 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2715   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2716     return false;
2717   // Is V2 is a vector load, don't do this transformation. We will try to use
2718   // load folding shufps op.
2719   if (ISD::isNON_EXTLoad(V2))
2720     return false;
2721
2722   unsigned NumElems = Mask->getNumOperands();
2723   if (NumElems != 2 && NumElems != 4)
2724     return false;
2725   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2726     if (!isUndefOrEqual(Mask->getOperand(i), i))
2727       return false;
2728   for (unsigned i = NumElems/2; i != NumElems; ++i)
2729     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2730       return false;
2731   return true;
2732 }
2733
2734 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2735 /// all the same.
2736 static bool isSplatVector(SDNode *N) {
2737   if (N->getOpcode() != ISD::BUILD_VECTOR)
2738     return false;
2739
2740   SDValue SplatValue = N->getOperand(0);
2741   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2742     if (N->getOperand(i) != SplatValue)
2743       return false;
2744   return true;
2745 }
2746
2747 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2748 /// to an undef.
2749 static bool isUndefShuffle(SDNode *N) {
2750   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2751     return false;
2752
2753   SDValue V1 = N->getOperand(0);
2754   SDValue V2 = N->getOperand(1);
2755   SDValue Mask = N->getOperand(2);
2756   unsigned NumElems = Mask.getNumOperands();
2757   for (unsigned i = 0; i != NumElems; ++i) {
2758     SDValue Arg = Mask.getOperand(i);
2759     if (Arg.getOpcode() != ISD::UNDEF) {
2760       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2761       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2762         return false;
2763       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2764         return false;
2765     }
2766   }
2767   return true;
2768 }
2769
2770 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2771 /// constant +0.0.
2772 static inline bool isZeroNode(SDValue Elt) {
2773   return ((isa<ConstantSDNode>(Elt) &&
2774            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2775           (isa<ConstantFPSDNode>(Elt) &&
2776            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2777 }
2778
2779 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2780 /// to an zero vector.
2781 static bool isZeroShuffle(SDNode *N) {
2782   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2783     return false;
2784
2785   SDValue V1 = N->getOperand(0);
2786   SDValue V2 = N->getOperand(1);
2787   SDValue Mask = N->getOperand(2);
2788   unsigned NumElems = Mask.getNumOperands();
2789   for (unsigned i = 0; i != NumElems; ++i) {
2790     SDValue Arg = Mask.getOperand(i);
2791     if (Arg.getOpcode() == ISD::UNDEF)
2792       continue;
2793     
2794     unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2795     if (Idx < NumElems) {
2796       unsigned Opc = V1.getNode()->getOpcode();
2797       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2798         continue;
2799       if (Opc != ISD::BUILD_VECTOR ||
2800           !isZeroNode(V1.getNode()->getOperand(Idx)))
2801         return false;
2802     } else if (Idx >= NumElems) {
2803       unsigned Opc = V2.getNode()->getOpcode();
2804       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2805         continue;
2806       if (Opc != ISD::BUILD_VECTOR ||
2807           !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2808         return false;
2809     }
2810   }
2811   return true;
2812 }
2813
2814 /// getZeroVector - Returns a vector of specified type with all zero elements.
2815 ///
2816 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2817   assert(VT.isVector() && "Expected a vector type");
2818   
2819   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2820   // type.  This ensures they get CSE'd.
2821   SDValue Vec;
2822   if (VT.getSizeInBits() == 64) { // MMX
2823     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2824     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2825   } else if (HasSSE2) {  // SSE2
2826     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2827     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2828   } else { // SSE1
2829     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2830     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2831   }
2832   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2833 }
2834
2835 /// getOnesVector - Returns a vector of specified type with all bits set.
2836 ///
2837 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2838   assert(VT.isVector() && "Expected a vector type");
2839   
2840   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2841   // type.  This ensures they get CSE'd.
2842   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2843   SDValue Vec;
2844   if (VT.getSizeInBits() == 64)  // MMX
2845     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2846   else                                              // SSE
2847     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2848   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2849 }
2850
2851
2852 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2853 /// that point to V2 points to its first element.
2854 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2855   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2856
2857   bool Changed = false;
2858   SmallVector<SDValue, 8> MaskVec;
2859   unsigned NumElems = Mask.getNumOperands();
2860   for (unsigned i = 0; i != NumElems; ++i) {
2861     SDValue Arg = Mask.getOperand(i);
2862     if (Arg.getOpcode() != ISD::UNDEF) {
2863       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2864       if (Val > NumElems) {
2865         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2866         Changed = true;
2867       }
2868     }
2869     MaskVec.push_back(Arg);
2870   }
2871
2872   if (Changed)
2873     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2874                        &MaskVec[0], MaskVec.size());
2875   return Mask;
2876 }
2877
2878 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2879 /// operation of specified width.
2880 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2881   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2882   MVT BaseVT = MaskVT.getVectorElementType();
2883
2884   SmallVector<SDValue, 8> MaskVec;
2885   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2886   for (unsigned i = 1; i != NumElems; ++i)
2887     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2888   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2889 }
2890
2891 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2892 /// of specified width.
2893 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2894   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2895   MVT BaseVT = MaskVT.getVectorElementType();
2896   SmallVector<SDValue, 8> MaskVec;
2897   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2898     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2899     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2900   }
2901   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2902 }
2903
2904 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2905 /// of specified width.
2906 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2907   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2908   MVT BaseVT = MaskVT.getVectorElementType();
2909   unsigned Half = NumElems/2;
2910   SmallVector<SDValue, 8> MaskVec;
2911   for (unsigned i = 0; i != Half; ++i) {
2912     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2913     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2914   }
2915   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2916 }
2917
2918 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2919 /// element #0 of a vector with the specified index, leaving the rest of the
2920 /// elements in place.
2921 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2922                                    SelectionDAG &DAG) {
2923   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2924   MVT BaseVT = MaskVT.getVectorElementType();
2925   SmallVector<SDValue, 8> MaskVec;
2926   // Element #0 of the result gets the elt we are replacing.
2927   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2928   for (unsigned i = 1; i != NumElems; ++i)
2929     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2930   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2931 }
2932
2933 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2934 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2935   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2936   MVT VT = Op.getValueType();
2937   if (PVT == VT)
2938     return Op;
2939   SDValue V1 = Op.getOperand(0);
2940   SDValue Mask = Op.getOperand(2);
2941   unsigned NumElems = Mask.getNumOperands();
2942   // Special handling of v4f32 -> v4i32.
2943   if (VT != MVT::v4f32) {
2944     Mask = getUnpacklMask(NumElems, DAG);
2945     while (NumElems > 4) {
2946       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2947       NumElems >>= 1;
2948     }
2949     Mask = getZeroVector(MVT::v4i32, true, DAG);
2950   }
2951
2952   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2953   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2954                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
2955   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2956 }
2957
2958 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2959 /// vector of zero or undef vector.  This produces a shuffle where the low
2960 /// element of V2 is swizzled into the zero/undef vector, landing at element
2961 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2962 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2963                                              bool isZero, bool HasSSE2,
2964                                              SelectionDAG &DAG) {
2965   MVT VT = V2.getValueType();
2966   SDValue V1 = isZero
2967     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2968   unsigned NumElems = V2.getValueType().getVectorNumElements();
2969   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2970   MVT EVT = MaskVT.getVectorElementType();
2971   SmallVector<SDValue, 16> MaskVec;
2972   for (unsigned i = 0; i != NumElems; ++i)
2973     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2974       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2975     else
2976       MaskVec.push_back(DAG.getConstant(i, EVT));
2977   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2978                                &MaskVec[0], MaskVec.size());
2979   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2980 }
2981
2982 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2983 /// a shuffle that is zero.
2984 static
2985 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2986                                   unsigned NumElems, bool Low,
2987                                   SelectionDAG &DAG) {
2988   unsigned NumZeros = 0;
2989   for (unsigned i = 0; i < NumElems; ++i) {
2990     unsigned Index = Low ? i : NumElems-i-1;
2991     SDValue Idx = Mask.getOperand(Index);
2992     if (Idx.getOpcode() == ISD::UNDEF) {
2993       ++NumZeros;
2994       continue;
2995     }
2996     SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
2997     if (Elt.getNode() && isZeroNode(Elt))
2998       ++NumZeros;
2999     else
3000       break;
3001   }
3002   return NumZeros;
3003 }
3004
3005 /// isVectorShift - Returns true if the shuffle can be implemented as a
3006 /// logical left or right shift of a vector.
3007 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3008                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3009   unsigned NumElems = Mask.getNumOperands();
3010
3011   isLeft = true;
3012   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3013   if (!NumZeros) {
3014     isLeft = false;
3015     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3016     if (!NumZeros)
3017       return false;
3018   }
3019
3020   bool SeenV1 = false;
3021   bool SeenV2 = false;
3022   for (unsigned i = NumZeros; i < NumElems; ++i) {
3023     unsigned Val = isLeft ? (i - NumZeros) : i;
3024     SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3025     if (Idx.getOpcode() == ISD::UNDEF)
3026       continue;
3027     unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3028     if (Index < NumElems)
3029       SeenV1 = true;
3030     else {
3031       Index -= NumElems;
3032       SeenV2 = true;
3033     }
3034     if (Index != Val)
3035       return false;
3036   }
3037   if (SeenV1 && SeenV2)
3038     return false;
3039
3040   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3041   ShAmt = NumZeros;
3042   return true;
3043 }
3044
3045
3046 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3047 ///
3048 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3049                                        unsigned NumNonZero, unsigned NumZero,
3050                                        SelectionDAG &DAG, TargetLowering &TLI) {
3051   if (NumNonZero > 8)
3052     return SDValue();
3053
3054   SDValue V(0, 0);
3055   bool First = true;
3056   for (unsigned i = 0; i < 16; ++i) {
3057     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3058     if (ThisIsNonZero && First) {
3059       if (NumZero)
3060         V = getZeroVector(MVT::v8i16, true, DAG);
3061       else
3062         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3063       First = false;
3064     }
3065
3066     if ((i & 1) != 0) {
3067       SDValue ThisElt(0, 0), LastElt(0, 0);
3068       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3069       if (LastIsNonZero) {
3070         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3071       }
3072       if (ThisIsNonZero) {
3073         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3074         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3075                               ThisElt, DAG.getConstant(8, MVT::i8));
3076         if (LastIsNonZero)
3077           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3078       } else
3079         ThisElt = LastElt;
3080
3081       if (ThisElt.getNode())
3082         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3083                         DAG.getIntPtrConstant(i/2));
3084     }
3085   }
3086
3087   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3088 }
3089
3090 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3091 ///
3092 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3093                                        unsigned NumNonZero, unsigned NumZero,
3094                                        SelectionDAG &DAG, TargetLowering &TLI) {
3095   if (NumNonZero > 4)
3096     return SDValue();
3097
3098   SDValue V(0, 0);
3099   bool First = true;
3100   for (unsigned i = 0; i < 8; ++i) {
3101     bool isNonZero = (NonZeros & (1 << i)) != 0;
3102     if (isNonZero) {
3103       if (First) {
3104         if (NumZero)
3105           V = getZeroVector(MVT::v8i16, true, DAG);
3106         else
3107           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3108         First = false;
3109       }
3110       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3111                       DAG.getIntPtrConstant(i));
3112     }
3113   }
3114
3115   return V;
3116 }
3117
3118 /// getVShift - Return a vector logical shift node.
3119 ///
3120 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3121                            unsigned NumBits, SelectionDAG &DAG,
3122                            const TargetLowering &TLI) {
3123   bool isMMX = VT.getSizeInBits() == 64;
3124   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3125   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3126   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3127   return DAG.getNode(ISD::BIT_CONVERT, VT,
3128                      DAG.getNode(Opc, ShVT, SrcOp,
3129                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3130 }
3131
3132 SDValue
3133 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3134   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3135   if (ISD::isBuildVectorAllZeros(Op.getNode())
3136       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3137     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3138     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3139     // eliminated on x86-32 hosts.
3140     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3141       return Op;
3142
3143     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3144       return getOnesVector(Op.getValueType(), DAG);
3145     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3146   }
3147
3148   MVT VT = Op.getValueType();
3149   MVT EVT = VT.getVectorElementType();
3150   unsigned EVTBits = EVT.getSizeInBits();
3151
3152   unsigned NumElems = Op.getNumOperands();
3153   unsigned NumZero  = 0;
3154   unsigned NumNonZero = 0;
3155   unsigned NonZeros = 0;
3156   bool IsAllConstants = true;
3157   SmallSet<SDValue, 8> Values;
3158   for (unsigned i = 0; i < NumElems; ++i) {
3159     SDValue Elt = Op.getOperand(i);
3160     if (Elt.getOpcode() == ISD::UNDEF)
3161       continue;
3162     Values.insert(Elt);
3163     if (Elt.getOpcode() != ISD::Constant &&
3164         Elt.getOpcode() != ISD::ConstantFP)
3165       IsAllConstants = false;
3166     if (isZeroNode(Elt))
3167       NumZero++;
3168     else {
3169       NonZeros |= (1 << i);
3170       NumNonZero++;
3171     }
3172   }
3173
3174   if (NumNonZero == 0) {
3175     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3176     return DAG.getNode(ISD::UNDEF, VT);
3177   }
3178
3179   // Special case for single non-zero, non-undef, element.
3180   if (NumNonZero == 1 && NumElems <= 4) {
3181     unsigned Idx = CountTrailingZeros_32(NonZeros);
3182     SDValue Item = Op.getOperand(Idx);
3183     
3184     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3185     // the value are obviously zero, truncate the value to i32 and do the
3186     // insertion that way.  Only do this if the value is non-constant or if the
3187     // value is a constant being inserted into element 0.  It is cheaper to do
3188     // a constant pool load than it is to do a movd + shuffle.
3189     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3190         (!IsAllConstants || Idx == 0)) {
3191       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3192         // Handle MMX and SSE both.
3193         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3194         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3195         
3196         // Truncate the value (which may itself be a constant) to i32, and
3197         // convert it to a vector with movd (S2V+shuffle to zero extend).
3198         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3199         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3200         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3201                                            Subtarget->hasSSE2(), DAG);
3202         
3203         // Now we have our 32-bit value zero extended in the low element of
3204         // a vector.  If Idx != 0, swizzle it into place.
3205         if (Idx != 0) {
3206           SDValue Ops[] = { 
3207             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3208             getSwapEltZeroMask(VecElts, Idx, DAG)
3209           };
3210           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3211         }
3212         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3213       }
3214     }
3215     
3216     // If we have a constant or non-constant insertion into the low element of
3217     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3218     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3219     // depending on what the source datatype is.  Because we can only get here
3220     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3221     if (Idx == 0 &&
3222         // Don't do this for i64 values on x86-32.
3223         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3224       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3225       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3226       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3227                                          Subtarget->hasSSE2(), DAG);
3228     }
3229
3230     // Is it a vector logical left shift?
3231     if (NumElems == 2 && Idx == 1 &&
3232         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3233       unsigned NumBits = VT.getSizeInBits();
3234       return getVShift(true, VT,
3235                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3236                        NumBits/2, DAG, *this);
3237     }
3238     
3239     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3240       return SDValue();
3241
3242     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3243     // is a non-constant being inserted into an element other than the low one,
3244     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3245     // movd/movss) to move this into the low element, then shuffle it into
3246     // place.
3247     if (EVTBits == 32) {
3248       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3249       
3250       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3251       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3252                                          Subtarget->hasSSE2(), DAG);
3253       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3254       MVT MaskEVT = MaskVT.getVectorElementType();
3255       SmallVector<SDValue, 8> MaskVec;
3256       for (unsigned i = 0; i < NumElems; i++)
3257         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3258       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3259                                    &MaskVec[0], MaskVec.size());
3260       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3261                          DAG.getNode(ISD::UNDEF, VT), Mask);
3262     }
3263   }
3264
3265   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3266   if (Values.size() == 1)
3267     return SDValue();
3268   
3269   // A vector full of immediates; various special cases are already
3270   // handled, so this is best done with a single constant-pool load.
3271   if (IsAllConstants)
3272     return SDValue();
3273
3274   // Let legalizer expand 2-wide build_vectors.
3275   if (EVTBits == 64) {
3276     if (NumNonZero == 1) {
3277       // One half is zero or undef.
3278       unsigned Idx = CountTrailingZeros_32(NonZeros);
3279       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3280                                  Op.getOperand(Idx));
3281       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3282                                          Subtarget->hasSSE2(), DAG);
3283     }
3284     return SDValue();
3285   }
3286
3287   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3288   if (EVTBits == 8 && NumElems == 16) {
3289     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3290                                         *this);
3291     if (V.getNode()) return V;
3292   }
3293
3294   if (EVTBits == 16 && NumElems == 8) {
3295     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3296                                         *this);
3297     if (V.getNode()) return V;
3298   }
3299
3300   // If element VT is == 32 bits, turn it into a number of shuffles.
3301   SmallVector<SDValue, 8> V;
3302   V.resize(NumElems);
3303   if (NumElems == 4 && NumZero > 0) {
3304     for (unsigned i = 0; i < 4; ++i) {
3305       bool isZero = !(NonZeros & (1 << i));
3306       if (isZero)
3307         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3308       else
3309         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3310     }
3311
3312     for (unsigned i = 0; i < 2; ++i) {
3313       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3314         default: break;
3315         case 0:
3316           V[i] = V[i*2];  // Must be a zero vector.
3317           break;
3318         case 1:
3319           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3320                              getMOVLMask(NumElems, DAG));
3321           break;
3322         case 2:
3323           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3324                              getMOVLMask(NumElems, DAG));
3325           break;
3326         case 3:
3327           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3328                              getUnpacklMask(NumElems, DAG));
3329           break;
3330       }
3331     }
3332
3333     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3334     MVT EVT = MaskVT.getVectorElementType();
3335     SmallVector<SDValue, 8> MaskVec;
3336     bool Reverse = (NonZeros & 0x3) == 2;
3337     for (unsigned i = 0; i < 2; ++i)
3338       if (Reverse)
3339         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3340       else
3341         MaskVec.push_back(DAG.getConstant(i, EVT));
3342     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3343     for (unsigned i = 0; i < 2; ++i)
3344       if (Reverse)
3345         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3346       else
3347         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3348     SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3349                                      &MaskVec[0], MaskVec.size());
3350     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3351   }
3352
3353   if (Values.size() > 2) {
3354     // Expand into a number of unpckl*.
3355     // e.g. for v4f32
3356     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3357     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3358     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3359     SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3360     for (unsigned i = 0; i < NumElems; ++i)
3361       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3362     NumElems >>= 1;
3363     while (NumElems != 0) {
3364       for (unsigned i = 0; i < NumElems; ++i)
3365         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3366                            UnpckMask);
3367       NumElems >>= 1;
3368     }
3369     return V[0];
3370   }
3371
3372   return SDValue();
3373 }
3374
3375 static
3376 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3377                                  SDValue PermMask, SelectionDAG &DAG,
3378                                  TargetLowering &TLI) {
3379   SDValue NewV;
3380   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3381   MVT MaskEVT = MaskVT.getVectorElementType();
3382   MVT PtrVT = TLI.getPointerTy();
3383   SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3384                                    PermMask.getNode()->op_end());
3385
3386   // First record which half of which vector the low elements come from.
3387   SmallVector<unsigned, 4> LowQuad(4);
3388   for (unsigned i = 0; i < 4; ++i) {
3389     SDValue Elt = MaskElts[i];
3390     if (Elt.getOpcode() == ISD::UNDEF)
3391       continue;
3392     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3393     int QuadIdx = EltIdx / 4;
3394     ++LowQuad[QuadIdx];
3395   }
3396
3397   int BestLowQuad = -1;
3398   unsigned MaxQuad = 1;
3399   for (unsigned i = 0; i < 4; ++i) {
3400     if (LowQuad[i] > MaxQuad) {
3401       BestLowQuad = i;
3402       MaxQuad = LowQuad[i];
3403     }
3404   }
3405
3406   // Record which half of which vector the high elements come from.
3407   SmallVector<unsigned, 4> HighQuad(4);
3408   for (unsigned i = 4; i < 8; ++i) {
3409     SDValue Elt = MaskElts[i];
3410     if (Elt.getOpcode() == ISD::UNDEF)
3411       continue;
3412     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3413     int QuadIdx = EltIdx / 4;
3414     ++HighQuad[QuadIdx];
3415   }
3416
3417   int BestHighQuad = -1;
3418   MaxQuad = 1;
3419   for (unsigned i = 0; i < 4; ++i) {
3420     if (HighQuad[i] > MaxQuad) {
3421       BestHighQuad = i;
3422       MaxQuad = HighQuad[i];
3423     }
3424   }
3425
3426   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3427   if (BestLowQuad != -1 || BestHighQuad != -1) {
3428     // First sort the 4 chunks in order using shufpd.
3429     SmallVector<SDValue, 8> MaskVec;
3430
3431     if (BestLowQuad != -1)
3432       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3433     else
3434       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3435
3436     if (BestHighQuad != -1)
3437       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3438     else
3439       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3440
3441     SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3442     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3443                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3444                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3445     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3446
3447     // Now sort high and low parts separately.
3448     BitVector InOrder(8);
3449     if (BestLowQuad != -1) {
3450       // Sort lower half in order using PSHUFLW.
3451       MaskVec.clear();
3452       bool AnyOutOrder = false;
3453
3454       for (unsigned i = 0; i != 4; ++i) {
3455         SDValue Elt = MaskElts[i];
3456         if (Elt.getOpcode() == ISD::UNDEF) {
3457           MaskVec.push_back(Elt);
3458           InOrder.set(i);
3459         } else {
3460           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3461           if (EltIdx != i)
3462             AnyOutOrder = true;
3463
3464           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3465
3466           // If this element is in the right place after this shuffle, then
3467           // remember it.
3468           if ((int)(EltIdx / 4) == BestLowQuad)
3469             InOrder.set(i);
3470         }
3471       }
3472       if (AnyOutOrder) {
3473         for (unsigned i = 4; i != 8; ++i)
3474           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3475         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3476         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3477       }
3478     }
3479
3480     if (BestHighQuad != -1) {
3481       // Sort high half in order using PSHUFHW if possible.
3482       MaskVec.clear();
3483
3484       for (unsigned i = 0; i != 4; ++i)
3485         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3486
3487       bool AnyOutOrder = false;
3488       for (unsigned i = 4; i != 8; ++i) {
3489         SDValue Elt = MaskElts[i];
3490         if (Elt.getOpcode() == ISD::UNDEF) {
3491           MaskVec.push_back(Elt);
3492           InOrder.set(i);
3493         } else {
3494           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3495           if (EltIdx != i)
3496             AnyOutOrder = true;
3497
3498           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3499
3500           // If this element is in the right place after this shuffle, then
3501           // remember it.
3502           if ((int)(EltIdx / 4) == BestHighQuad)
3503             InOrder.set(i);
3504         }
3505       }
3506
3507       if (AnyOutOrder) {
3508         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3509         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3510       }
3511     }
3512
3513     // The other elements are put in the right place using pextrw and pinsrw.
3514     for (unsigned i = 0; i != 8; ++i) {
3515       if (InOrder[i])
3516         continue;
3517       SDValue Elt = MaskElts[i];
3518       if (Elt.getOpcode() == ISD::UNDEF)
3519         continue;
3520       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3521       SDValue ExtOp = (EltIdx < 8)
3522         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3523                       DAG.getConstant(EltIdx, PtrVT))
3524         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3525                       DAG.getConstant(EltIdx - 8, PtrVT));
3526       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3527                          DAG.getConstant(i, PtrVT));
3528     }
3529
3530     return NewV;
3531   }
3532
3533   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3534   // few as possible. First, let's find out how many elements are already in the
3535   // right order.
3536   unsigned V1InOrder = 0;
3537   unsigned V1FromV1 = 0;
3538   unsigned V2InOrder = 0;
3539   unsigned V2FromV2 = 0;
3540   SmallVector<SDValue, 8> V1Elts;
3541   SmallVector<SDValue, 8> V2Elts;
3542   for (unsigned i = 0; i < 8; ++i) {
3543     SDValue Elt = MaskElts[i];
3544     if (Elt.getOpcode() == ISD::UNDEF) {
3545       V1Elts.push_back(Elt);
3546       V2Elts.push_back(Elt);
3547       ++V1InOrder;
3548       ++V2InOrder;
3549       continue;
3550     }
3551     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3552     if (EltIdx == i) {
3553       V1Elts.push_back(Elt);
3554       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3555       ++V1InOrder;
3556     } else if (EltIdx == i+8) {
3557       V1Elts.push_back(Elt);
3558       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3559       ++V2InOrder;
3560     } else if (EltIdx < 8) {
3561       V1Elts.push_back(Elt);
3562       ++V1FromV1;
3563     } else {
3564       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3565       ++V2FromV2;
3566     }
3567   }
3568
3569   if (V2InOrder > V1InOrder) {
3570     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3571     std::swap(V1, V2);
3572     std::swap(V1Elts, V2Elts);
3573     std::swap(V1FromV1, V2FromV2);
3574   }
3575
3576   if ((V1FromV1 + V1InOrder) != 8) {
3577     // Some elements are from V2.
3578     if (V1FromV1) {
3579       // If there are elements that are from V1 but out of place,
3580       // then first sort them in place
3581       SmallVector<SDValue, 8> MaskVec;
3582       for (unsigned i = 0; i < 8; ++i) {
3583         SDValue Elt = V1Elts[i];
3584         if (Elt.getOpcode() == ISD::UNDEF) {
3585           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3586           continue;
3587         }
3588         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3589         if (EltIdx >= 8)
3590           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3591         else
3592           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3593       }
3594       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3595       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3596     }
3597
3598     NewV = V1;
3599     for (unsigned i = 0; i < 8; ++i) {
3600       SDValue Elt = V1Elts[i];
3601       if (Elt.getOpcode() == ISD::UNDEF)
3602         continue;
3603       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3604       if (EltIdx < 8)
3605         continue;
3606       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3607                                     DAG.getConstant(EltIdx - 8, PtrVT));
3608       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3609                          DAG.getConstant(i, PtrVT));
3610     }
3611     return NewV;
3612   } else {
3613     // All elements are from V1.
3614     NewV = V1;
3615     for (unsigned i = 0; i < 8; ++i) {
3616       SDValue Elt = V1Elts[i];
3617       if (Elt.getOpcode() == ISD::UNDEF)
3618         continue;
3619       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3620       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3621                                     DAG.getConstant(EltIdx, PtrVT));
3622       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3623                          DAG.getConstant(i, PtrVT));
3624     }
3625     return NewV;
3626   }
3627 }
3628
3629 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3630 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3631 /// done when every pair / quad of shuffle mask elements point to elements in
3632 /// the right sequence. e.g.
3633 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3634 static
3635 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3636                                 MVT VT,
3637                                 SDValue PermMask, SelectionDAG &DAG,
3638                                 TargetLowering &TLI) {
3639   unsigned NumElems = PermMask.getNumOperands();
3640   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3641   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3642   MVT MaskEltVT = MaskVT.getVectorElementType();
3643   MVT NewVT = MaskVT;
3644   switch (VT.getSimpleVT()) {
3645   default: assert(false && "Unexpected!");
3646   case MVT::v4f32: NewVT = MVT::v2f64; break;
3647   case MVT::v4i32: NewVT = MVT::v2i64; break;
3648   case MVT::v8i16: NewVT = MVT::v4i32; break;
3649   case MVT::v16i8: NewVT = MVT::v4i32; break;
3650   }
3651
3652   if (NewWidth == 2) {
3653     if (VT.isInteger())
3654       NewVT = MVT::v2i64;
3655     else
3656       NewVT = MVT::v2f64;
3657   }
3658   unsigned Scale = NumElems / NewWidth;
3659   SmallVector<SDValue, 8> MaskVec;
3660   for (unsigned i = 0; i < NumElems; i += Scale) {
3661     unsigned StartIdx = ~0U;
3662     for (unsigned j = 0; j < Scale; ++j) {
3663       SDValue Elt = PermMask.getOperand(i+j);
3664       if (Elt.getOpcode() == ISD::UNDEF)
3665         continue;
3666       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3667       if (StartIdx == ~0U)
3668         StartIdx = EltIdx - (EltIdx % Scale);
3669       if (EltIdx != StartIdx + j)
3670         return SDValue();
3671     }
3672     if (StartIdx == ~0U)
3673       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3674     else
3675       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3676   }
3677
3678   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3679   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3680   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3681                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3682                                  &MaskVec[0], MaskVec.size()));
3683 }
3684
3685 /// getVZextMovL - Return a zero-extending vector move low node.
3686 ///
3687 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3688                               SDValue SrcOp, SelectionDAG &DAG,
3689                               const X86Subtarget *Subtarget) {
3690   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3691     LoadSDNode *LD = NULL;
3692     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3693       LD = dyn_cast<LoadSDNode>(SrcOp);
3694     if (!LD) {
3695       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3696       // instead.
3697       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3698       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3699           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3700           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3701           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3702         // PR2108
3703         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3704         return DAG.getNode(ISD::BIT_CONVERT, VT,
3705                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3706                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3707                                                    SrcOp.getOperand(0)
3708                                                           .getOperand(0))));
3709       }
3710     }
3711   }
3712
3713   return DAG.getNode(ISD::BIT_CONVERT, VT,
3714                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3715                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3716 }
3717
3718 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3719 /// shuffles.
3720 static SDValue
3721 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3722                           SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3723   MVT MaskVT = PermMask.getValueType();
3724   MVT MaskEVT = MaskVT.getVectorElementType();
3725   SmallVector<std::pair<int, int>, 8> Locs;
3726   Locs.resize(4);
3727   SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3728   unsigned NumHi = 0;
3729   unsigned NumLo = 0;
3730   for (unsigned i = 0; i != 4; ++i) {
3731     SDValue Elt = PermMask.getOperand(i);
3732     if (Elt.getOpcode() == ISD::UNDEF) {
3733       Locs[i] = std::make_pair(-1, -1);
3734     } else {
3735       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3736       assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3737       if (Val < 4) {
3738         Locs[i] = std::make_pair(0, NumLo);
3739         Mask1[NumLo] = Elt;
3740         NumLo++;
3741       } else {
3742         Locs[i] = std::make_pair(1, NumHi);
3743         if (2+NumHi < 4)
3744           Mask1[2+NumHi] = Elt;
3745         NumHi++;
3746       }
3747     }
3748   }
3749
3750   if (NumLo <= 2 && NumHi <= 2) {
3751     // If no more than two elements come from either vector. This can be
3752     // implemented with two shuffles. First shuffle gather the elements.
3753     // The second shuffle, which takes the first shuffle as both of its
3754     // vector operands, put the elements into the right order.
3755     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3756                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3757                                  &Mask1[0], Mask1.size()));
3758
3759     SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3760     for (unsigned i = 0; i != 4; ++i) {
3761       if (Locs[i].first == -1)
3762         continue;
3763       else {
3764         unsigned Idx = (i < 2) ? 0 : 4;
3765         Idx += Locs[i].first * 2 + Locs[i].second;
3766         Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3767       }
3768     }
3769
3770     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3771                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3772                                    &Mask2[0], Mask2.size()));
3773   } else if (NumLo == 3 || NumHi == 3) {
3774     // Otherwise, we must have three elements from one vector, call it X, and
3775     // one element from the other, call it Y.  First, use a shufps to build an
3776     // intermediate vector with the one element from Y and the element from X
3777     // that will be in the same half in the final destination (the indexes don't
3778     // matter). Then, use a shufps to build the final vector, taking the half
3779     // containing the element from Y from the intermediate, and the other half
3780     // from X.
3781     if (NumHi == 3) {
3782       // Normalize it so the 3 elements come from V1.
3783       PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3784       std::swap(V1, V2);
3785     }
3786
3787     // Find the element from V2.
3788     unsigned HiIndex;
3789     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3790       SDValue Elt = PermMask.getOperand(HiIndex);
3791       if (Elt.getOpcode() == ISD::UNDEF)
3792         continue;
3793       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3794       if (Val >= 4)
3795         break;
3796     }
3797
3798     Mask1[0] = PermMask.getOperand(HiIndex);
3799     Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3800     Mask1[2] = PermMask.getOperand(HiIndex^1);
3801     Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3802     V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3803                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3804
3805     if (HiIndex >= 2) {
3806       Mask1[0] = PermMask.getOperand(0);
3807       Mask1[1] = PermMask.getOperand(1);
3808       Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3809       Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3810       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3811                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3812     } else {
3813       Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3814       Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3815       Mask1[2] = PermMask.getOperand(2);
3816       Mask1[3] = PermMask.getOperand(3);
3817       if (Mask1[2].getOpcode() != ISD::UNDEF)
3818         Mask1[2] =
3819           DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3820                           MaskEVT);
3821       if (Mask1[3].getOpcode() != ISD::UNDEF)
3822         Mask1[3] =
3823           DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3824                           MaskEVT);
3825       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3826                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3827     }
3828   }
3829
3830   // Break it into (shuffle shuffle_hi, shuffle_lo).
3831   Locs.clear();
3832   SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3833   SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3834   SmallVector<SDValue,8> *MaskPtr = &LoMask;
3835   unsigned MaskIdx = 0;
3836   unsigned LoIdx = 0;
3837   unsigned HiIdx = 2;
3838   for (unsigned i = 0; i != 4; ++i) {
3839     if (i == 2) {
3840       MaskPtr = &HiMask;
3841       MaskIdx = 1;
3842       LoIdx = 0;
3843       HiIdx = 2;
3844     }
3845     SDValue Elt = PermMask.getOperand(i);
3846     if (Elt.getOpcode() == ISD::UNDEF) {
3847       Locs[i] = std::make_pair(-1, -1);
3848     } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3849       Locs[i] = std::make_pair(MaskIdx, LoIdx);
3850       (*MaskPtr)[LoIdx] = Elt;
3851       LoIdx++;
3852     } else {
3853       Locs[i] = std::make_pair(MaskIdx, HiIdx);
3854       (*MaskPtr)[HiIdx] = Elt;
3855       HiIdx++;
3856     }
3857   }
3858
3859   SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3860                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3861                                                 &LoMask[0], LoMask.size()));
3862   SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3863                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3864                                                 &HiMask[0], HiMask.size()));
3865   SmallVector<SDValue, 8> MaskOps;
3866   for (unsigned i = 0; i != 4; ++i) {
3867     if (Locs[i].first == -1) {
3868       MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3869     } else {
3870       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3871       MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3872     }
3873   }
3874   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3875                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3876                                  &MaskOps[0], MaskOps.size()));
3877 }
3878
3879 SDValue
3880 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3881   SDValue V1 = Op.getOperand(0);
3882   SDValue V2 = Op.getOperand(1);
3883   SDValue PermMask = Op.getOperand(2);
3884   MVT VT = Op.getValueType();
3885   unsigned NumElems = PermMask.getNumOperands();
3886   bool isMMX = VT.getSizeInBits() == 64;
3887   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3888   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3889   bool V1IsSplat = false;
3890   bool V2IsSplat = false;
3891
3892   if (isUndefShuffle(Op.getNode()))
3893     return DAG.getNode(ISD::UNDEF, VT);
3894
3895   if (isZeroShuffle(Op.getNode()))
3896     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3897
3898   if (isIdentityMask(PermMask.getNode()))
3899     return V1;
3900   else if (isIdentityMask(PermMask.getNode(), true))
3901     return V2;
3902
3903   if (isSplatMask(PermMask.getNode())) {
3904     if (isMMX || NumElems < 4) return Op;
3905     // Promote it to a v4{if}32 splat.
3906     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3907   }
3908
3909   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3910   // do it!
3911   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3912     SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3913     if (NewOp.getNode())
3914       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3915   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3916     // FIXME: Figure out a cleaner way to do this.
3917     // Try to make use of movq to zero out the top part.
3918     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3919       SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3920                                                  DAG, *this);
3921       if (NewOp.getNode()) {
3922         SDValue NewV1 = NewOp.getOperand(0);
3923         SDValue NewV2 = NewOp.getOperand(1);
3924         SDValue NewMask = NewOp.getOperand(2);
3925         if (isCommutedMOVL(NewMask.getNode(), true, false)) {
3926           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3927           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3928         }
3929       }
3930     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3931       SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3932                                                 DAG, *this);
3933       if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
3934         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3935                              DAG, Subtarget);
3936     }
3937   }
3938
3939   // Check if this can be converted into a logical shift.
3940   bool isLeft = false;
3941   unsigned ShAmt = 0;
3942   SDValue ShVal;
3943   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3944   if (isShift && ShVal.hasOneUse()) {
3945     // If the shifted value has multiple uses, it may be cheaper to use 
3946     // v_set0 + movlhps or movhlps, etc.
3947     MVT EVT = VT.getVectorElementType();
3948     ShAmt *= EVT.getSizeInBits();
3949     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3950   }
3951
3952   if (X86::isMOVLMask(PermMask.getNode())) {
3953     if (V1IsUndef)
3954       return V2;
3955     if (ISD::isBuildVectorAllZeros(V1.getNode()))
3956       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3957     if (!isMMX)
3958       return Op;
3959   }
3960
3961   if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
3962                  X86::isMOVSLDUPMask(PermMask.getNode()) ||
3963                  X86::isMOVHLPSMask(PermMask.getNode()) ||
3964                  X86::isMOVHPMask(PermMask.getNode()) ||
3965                  X86::isMOVLPMask(PermMask.getNode())))
3966     return Op;
3967
3968   if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
3969       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
3970     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3971
3972   if (isShift) {
3973     // No better options. Use a vshl / vsrl.
3974     MVT EVT = VT.getVectorElementType();
3975     ShAmt *= EVT.getSizeInBits();
3976     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3977   }
3978
3979   bool Commuted = false;
3980   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3981   // 1,1,1,1 -> v8i16 though.
3982   V1IsSplat = isSplatVector(V1.getNode());
3983   V2IsSplat = isSplatVector(V2.getNode());
3984   
3985   // Canonicalize the splat or undef, if present, to be on the RHS.
3986   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3987     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3988     std::swap(V1IsSplat, V2IsSplat);
3989     std::swap(V1IsUndef, V2IsUndef);
3990     Commuted = true;
3991   }
3992
3993   // FIXME: Figure out a cleaner way to do this.
3994   if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
3995     if (V2IsUndef) return V1;
3996     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3997     if (V2IsSplat) {
3998       // V2 is a splat, so the mask may be malformed. That is, it may point
3999       // to any V2 element. The instruction selectior won't like this. Get
4000       // a corrected mask and commute to form a proper MOVS{S|D}.
4001       SDValue NewMask = getMOVLMask(NumElems, DAG);
4002       if (NewMask.getNode() != PermMask.getNode())
4003         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4004     }
4005     return Op;
4006   }
4007
4008   if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4009       X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4010       X86::isUNPCKLMask(PermMask.getNode()) ||
4011       X86::isUNPCKHMask(PermMask.getNode()))
4012     return Op;
4013
4014   if (V2IsSplat) {
4015     // Normalize mask so all entries that point to V2 points to its first
4016     // element then try to match unpck{h|l} again. If match, return a
4017     // new vector_shuffle with the corrected mask.
4018     SDValue NewMask = NormalizeMask(PermMask, DAG);
4019     if (NewMask.getNode() != PermMask.getNode()) {
4020       if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4021         SDValue NewMask = getUnpacklMask(NumElems, DAG);
4022         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4023       } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4024         SDValue NewMask = getUnpackhMask(NumElems, DAG);
4025         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4026       }
4027     }
4028   }
4029
4030   // Normalize the node to match x86 shuffle ops if needed
4031   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4032       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4033
4034   if (Commuted) {
4035     // Commute is back and try unpck* again.
4036     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4037     if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4038         X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4039         X86::isUNPCKLMask(PermMask.getNode()) ||
4040         X86::isUNPCKHMask(PermMask.getNode()))
4041       return Op;
4042   }
4043
4044   // Try PSHUF* first, then SHUFP*.
4045   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4046   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4047   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4048     if (V2.getOpcode() != ISD::UNDEF)
4049       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4050                          DAG.getNode(ISD::UNDEF, VT), PermMask);
4051     return Op;
4052   }
4053
4054   if (!isMMX) {
4055     if (Subtarget->hasSSE2() &&
4056         (X86::isPSHUFDMask(PermMask.getNode()) ||
4057          X86::isPSHUFHWMask(PermMask.getNode()) ||
4058          X86::isPSHUFLWMask(PermMask.getNode()))) {
4059       MVT RVT = VT;
4060       if (VT == MVT::v4f32) {
4061         RVT = MVT::v4i32;
4062         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4063                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4064                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4065       } else if (V2.getOpcode() != ISD::UNDEF)
4066         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4067                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4068       if (RVT != VT)
4069         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4070       return Op;
4071     }
4072
4073     // Binary or unary shufps.
4074     if (X86::isSHUFPMask(PermMask.getNode()) ||
4075         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4076       return Op;
4077   }
4078
4079   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4080   if (VT == MVT::v8i16) {
4081     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4082     if (NewOp.getNode())
4083       return NewOp;
4084   }
4085
4086   // Handle all 4 wide cases with a number of shuffles except for MMX.
4087   if (NumElems == 4 && !isMMX)
4088     return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4089
4090   return SDValue();
4091 }
4092
4093 SDValue
4094 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4095                                                 SelectionDAG &DAG) {
4096   MVT VT = Op.getValueType();
4097   if (VT.getSizeInBits() == 8) {
4098     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4099                                     Op.getOperand(0), Op.getOperand(1));
4100     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4101                                     DAG.getValueType(VT));
4102     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4103   } else if (VT.getSizeInBits() == 16) {
4104     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4105                                     Op.getOperand(0), Op.getOperand(1));
4106     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4107                                     DAG.getValueType(VT));
4108     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4109   } else if (VT == MVT::f32) {
4110     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4111     // the result back to FR32 register. It's only worth matching if the
4112     // result has a single use which is a store or a bitcast to i32.
4113     if (!Op.hasOneUse())
4114       return SDValue();
4115     SDNode *User = *Op.getNode()->use_begin();
4116     if (User->getOpcode() != ISD::STORE &&
4117         (User->getOpcode() != ISD::BIT_CONVERT ||
4118          User->getValueType(0) != MVT::i32))
4119       return SDValue();
4120     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4121                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4122                                     Op.getOperand(1));
4123     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4124   }
4125   return SDValue();
4126 }
4127
4128
4129 SDValue
4130 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4131   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4132     return SDValue();
4133
4134   if (Subtarget->hasSSE41()) {
4135     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4136     if (Res.getNode())
4137       return Res;
4138   }
4139
4140   MVT VT = Op.getValueType();
4141   // TODO: handle v16i8.
4142   if (VT.getSizeInBits() == 16) {
4143     SDValue Vec = Op.getOperand(0);
4144     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4145     if (Idx == 0)
4146       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4147                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4148                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4149                                      Op.getOperand(1)));
4150     // Transform it so it match pextrw which produces a 32-bit result.
4151     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4152     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4153                                     Op.getOperand(0), Op.getOperand(1));
4154     SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4155                                     DAG.getValueType(VT));
4156     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4157   } else if (VT.getSizeInBits() == 32) {
4158     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4159     if (Idx == 0)
4160       return Op;
4161     // SHUFPS the element to the lowest double word, then movss.
4162     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4163     SmallVector<SDValue, 8> IdxVec;
4164     IdxVec.
4165       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4166     IdxVec.
4167       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4168     IdxVec.
4169       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4170     IdxVec.
4171       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4172     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4173                                  &IdxVec[0], IdxVec.size());
4174     SDValue Vec = Op.getOperand(0);
4175     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4176                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4177     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4178                        DAG.getIntPtrConstant(0));
4179   } else if (VT.getSizeInBits() == 64) {
4180     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4181     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4182     //        to match extract_elt for f64.
4183     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4184     if (Idx == 0)
4185       return Op;
4186
4187     // UNPCKHPD the element to the lowest double word, then movsd.
4188     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4189     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4190     MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4191     SmallVector<SDValue, 8> IdxVec;
4192     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4193     IdxVec.
4194       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4195     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4196                                  &IdxVec[0], IdxVec.size());
4197     SDValue Vec = Op.getOperand(0);
4198     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4199                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4200     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4201                        DAG.getIntPtrConstant(0));
4202   }
4203
4204   return SDValue();
4205 }
4206
4207 SDValue
4208 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4209   MVT VT = Op.getValueType();
4210   MVT EVT = VT.getVectorElementType();
4211
4212   SDValue N0 = Op.getOperand(0);
4213   SDValue N1 = Op.getOperand(1);
4214   SDValue N2 = Op.getOperand(2);
4215
4216   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4217       isa<ConstantSDNode>(N2)) {
4218     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4219                                                   : X86ISD::PINSRW;
4220     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4221     // argument.
4222     if (N1.getValueType() != MVT::i32)
4223       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4224     if (N2.getValueType() != MVT::i32)
4225       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4226     return DAG.getNode(Opc, VT, N0, N1, N2);
4227   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4228     // Bits [7:6] of the constant are the source select.  This will always be
4229     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4230     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4231     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4232     // Bits [5:4] of the constant are the destination select.  This is the 
4233     //  value of the incoming immediate.
4234     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
4235     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4236     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4237     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4238   }
4239   return SDValue();
4240 }
4241
4242 SDValue
4243 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4244   MVT VT = Op.getValueType();
4245   MVT EVT = VT.getVectorElementType();
4246
4247   if (Subtarget->hasSSE41())
4248     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4249
4250   if (EVT == MVT::i8)
4251     return SDValue();
4252
4253   SDValue N0 = Op.getOperand(0);
4254   SDValue N1 = Op.getOperand(1);
4255   SDValue N2 = Op.getOperand(2);
4256
4257   if (EVT.getSizeInBits() == 16) {
4258     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4259     // as its second argument.
4260     if (N1.getValueType() != MVT::i32)
4261       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4262     if (N2.getValueType() != MVT::i32)
4263       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4264     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4265   }
4266   return SDValue();
4267 }
4268
4269 SDValue
4270 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4271   if (Op.getValueType() == MVT::v2f32)
4272     return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4273                        DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4274                                    DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4275                                                Op.getOperand(0))));
4276
4277   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4278   MVT VT = MVT::v2i32;
4279   switch (Op.getValueType().getSimpleVT()) {
4280   default: break;
4281   case MVT::v16i8:
4282   case MVT::v8i16:
4283     VT = MVT::v4i32;
4284     break;
4285   }
4286   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4287                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4288 }
4289
4290 // ConstantPool, JumpTable, GlobalAddress, and Symbol are lowered as their
4291 // target countpart wrapped in the X86ISD::Wrapper node. Suppose N is one of the
4292 // above mentioned nodes. It has to be wrapped because otherwise Select(N)
4293 // returns N. So the raw TargetGlobalAddress nodes, etc. can only be used to
4294 // form addressing mode. These wrapped nodes will be selected into MOV32ri.
4295 SDValue
4296 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4297   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4298   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4299                                                getPointerTy(),
4300                                                CP->getAlignment());
4301   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4302   // With PIC, the address is actually $g + Offset.
4303   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4304       !Subtarget->isPICStyleRIPRel()) {
4305     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4306                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4307                          Result);
4308   }
4309
4310   return Result;
4311 }
4312
4313 SDValue
4314 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4315   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4316   SDValue Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4317   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4318   // With PIC, the address is actually $g + Offset.
4319   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4320       !Subtarget->isPICStyleRIPRel()) {
4321     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4322                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4323                          Result);
4324   }
4325   
4326   // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4327   // load the value at address GV, not the value of GV itself. This means that
4328   // the GlobalAddress must be in the base or index register of the address, not
4329   // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4330   // The same applies for external symbols during PIC codegen
4331   if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4332     Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4333                          PseudoSourceValue::getGOT(), 0);
4334
4335   return Result;
4336 }
4337
4338 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4339 static SDValue
4340 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4341                                 const MVT PtrVT) {
4342   SDValue InFlag;
4343   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4344                                      DAG.getNode(X86ISD::GlobalBaseReg,
4345                                                  PtrVT), InFlag);
4346   InFlag = Chain.getValue(1);
4347
4348   // emit leal symbol@TLSGD(,%ebx,1), %eax
4349   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4350   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4351                                              GA->getValueType(0),
4352                                              GA->getOffset());
4353   SDValue Ops[] = { Chain,  TGA, InFlag };
4354   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4355   InFlag = Result.getValue(2);
4356   Chain = Result.getValue(1);
4357
4358   // call ___tls_get_addr. This function receives its argument in
4359   // the register EAX.
4360   Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4361   InFlag = Chain.getValue(1);
4362
4363   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4364   SDValue Ops1[] = { Chain,
4365                       DAG.getTargetSymbol("___tls_get_addr", PtrVT),
4366                       DAG.getRegister(X86::EAX, PtrVT),
4367                       DAG.getRegister(X86::EBX, PtrVT),
4368                       InFlag };
4369   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4370   InFlag = Chain.getValue(1);
4371
4372   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4373 }
4374
4375 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4376 static SDValue
4377 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4378                                 const MVT PtrVT) {
4379   SDValue InFlag, Chain;
4380
4381   // emit leaq symbol@TLSGD(%rip), %rdi
4382   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4383   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4384                                              GA->getValueType(0),
4385                                              GA->getOffset());
4386   SDValue Ops[]  = { DAG.getEntryNode(), TGA};
4387   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4388   Chain  = Result.getValue(1);
4389   InFlag = Result.getValue(2);
4390
4391   // call __tls_get_addr. This function receives its argument in
4392   // the register RDI.
4393   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4394   InFlag = Chain.getValue(1);
4395
4396   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4397   SDValue Ops1[] = { Chain,
4398                       DAG.getTargetSymbol("__tls_get_addr", PtrVT),
4399                       DAG.getRegister(X86::RDI, PtrVT),
4400                       InFlag };
4401   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4402   InFlag = Chain.getValue(1);
4403
4404   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4405 }
4406
4407 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4408 // "local exec" model.
4409 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4410                                      const MVT PtrVT) {
4411   // Get the Thread Pointer
4412   SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4413   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4414   // exec)
4415   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4416                                              GA->getValueType(0),
4417                                              GA->getOffset());
4418   SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4419
4420   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4421     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4422                          PseudoSourceValue::getGOT(), 0);
4423
4424   // The address of the thread local variable is the add of the thread
4425   // pointer with the offset of the variable.
4426   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4427 }
4428
4429 SDValue
4430 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4431   // TODO: implement the "local dynamic" model
4432   // TODO: implement the "initial exec"model for pic executables
4433   assert(Subtarget->isTargetELF() &&
4434          "TLS not implemented for non-ELF targets");
4435   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4436   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4437   // otherwise use the "Local Exec"TLS Model
4438   if (Subtarget->is64Bit()) {
4439     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4440   } else {
4441     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4442       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4443     else
4444       return LowerToTLSExecModel(GA, DAG, getPointerTy());
4445   }
4446 }
4447
4448 SDValue
4449 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4450   SymbolSDNode *Sym = cast<SymbolSDNode>(Op);
4451   SDValue Result = DAG.getTargetSymbol(Sym->getSymbol(), getPointerTy(),
4452                                        Sym->getLinkage());
4453   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4454   // With PIC, the address is actually $g + Offset.
4455   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4456       !Subtarget->isPICStyleRIPRel()) {
4457     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4458                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4459                          Result);
4460   }
4461
4462   return Result;
4463 }
4464
4465 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4466   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4467   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4468   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4469   // With PIC, the address is actually $g + Offset.
4470   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4471       !Subtarget->isPICStyleRIPRel()) {
4472     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4473                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4474                          Result);
4475   }
4476
4477   return Result;
4478 }
4479
4480 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4481 /// take a 2 x i32 value to shift plus a shift amount. 
4482 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4483   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4484   MVT VT = Op.getValueType();
4485   unsigned VTBits = VT.getSizeInBits();
4486   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4487   SDValue ShOpLo = Op.getOperand(0);
4488   SDValue ShOpHi = Op.getOperand(1);
4489   SDValue ShAmt  = Op.getOperand(2);
4490   SDValue Tmp1 = isSRA ?
4491     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4492     DAG.getConstant(0, VT);
4493
4494   SDValue Tmp2, Tmp3;
4495   if (Op.getOpcode() == ISD::SHL_PARTS) {
4496     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4497     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4498   } else {
4499     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4500     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4501   }
4502
4503   SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4504                                   DAG.getConstant(VTBits, MVT::i8));
4505   SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4506                                AndNode, DAG.getConstant(0, MVT::i8));
4507
4508   SDValue Hi, Lo;
4509   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4510   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4511   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4512
4513   if (Op.getOpcode() == ISD::SHL_PARTS) {
4514     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4515     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4516   } else {
4517     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4518     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4519   }
4520
4521   SDValue Ops[2] = { Lo, Hi };
4522   return DAG.getMergeValues(Ops, 2);
4523 }
4524
4525 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4526   MVT SrcVT = Op.getOperand(0).getValueType();
4527   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4528          "Unknown SINT_TO_FP to lower!");
4529   
4530   // These are really Legal; caller falls through into that case.
4531   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4532     return SDValue();
4533   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4534       Subtarget->is64Bit())
4535     return SDValue();
4536   
4537   unsigned Size = SrcVT.getSizeInBits()/8;
4538   MachineFunction &MF = DAG.getMachineFunction();
4539   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4540   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4541   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4542                                  StackSlot,
4543                                  PseudoSourceValue::getFixedStack(SSFI), 0);
4544
4545   // Build the FILD
4546   SDVTList Tys;
4547   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4548   if (useSSE)
4549     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4550   else
4551     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4552   SmallVector<SDValue, 8> Ops;
4553   Ops.push_back(Chain);
4554   Ops.push_back(StackSlot);
4555   Ops.push_back(DAG.getValueType(SrcVT));
4556   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4557                                  Tys, &Ops[0], Ops.size());
4558
4559   if (useSSE) {
4560     Chain = Result.getValue(1);
4561     SDValue InFlag = Result.getValue(2);
4562
4563     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4564     // shouldn't be necessary except that RFP cannot be live across
4565     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4566     MachineFunction &MF = DAG.getMachineFunction();
4567     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4568     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4569     Tys = DAG.getVTList(MVT::Other);
4570     SmallVector<SDValue, 8> Ops;
4571     Ops.push_back(Chain);
4572     Ops.push_back(Result);
4573     Ops.push_back(StackSlot);
4574     Ops.push_back(DAG.getValueType(Op.getValueType()));
4575     Ops.push_back(InFlag);
4576     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4577     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4578                          PseudoSourceValue::getFixedStack(SSFI), 0);
4579   }
4580
4581   return Result;
4582 }
4583
4584 std::pair<SDValue,SDValue> X86TargetLowering::
4585 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4586   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4587          Op.getValueType().getSimpleVT() >= MVT::i16 &&
4588          "Unknown FP_TO_SINT to lower!");
4589
4590   // These are really Legal.
4591   if (Op.getValueType() == MVT::i32 && 
4592       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4593     return std::make_pair(SDValue(), SDValue());
4594   if (Subtarget->is64Bit() &&
4595       Op.getValueType() == MVT::i64 &&
4596       Op.getOperand(0).getValueType() != MVT::f80)
4597     return std::make_pair(SDValue(), SDValue());
4598
4599   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4600   // stack slot.
4601   MachineFunction &MF = DAG.getMachineFunction();
4602   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4603   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4604   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4605   unsigned Opc;
4606   switch (Op.getValueType().getSimpleVT()) {
4607   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4608   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4609   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4610   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4611   }
4612
4613   SDValue Chain = DAG.getEntryNode();
4614   SDValue Value = Op.getOperand(0);
4615   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4616     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4617     Chain = DAG.getStore(Chain, Value, StackSlot,
4618                          PseudoSourceValue::getFixedStack(SSFI), 0);
4619     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4620     SDValue Ops[] = {
4621       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4622     };
4623     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4624     Chain = Value.getValue(1);
4625     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4626     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4627   }
4628
4629   // Build the FP_TO_INT*_IN_MEM
4630   SDValue Ops[] = { Chain, Value, StackSlot };
4631   SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4632
4633   return std::make_pair(FIST, StackSlot);
4634 }
4635
4636 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4637   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4638   SDValue FIST = Vals.first, StackSlot = Vals.second;
4639   if (FIST.getNode() == 0) return SDValue();
4640   
4641   // Load the result.
4642   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4643 }
4644
4645 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4646   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4647   SDValue FIST = Vals.first, StackSlot = Vals.second;
4648   if (FIST.getNode() == 0) return 0;
4649
4650   MVT VT = N->getValueType(0);
4651
4652   // Return a load from the stack slot.
4653   SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4654
4655   // Use MERGE_VALUES to drop the chain result value and get a node with one
4656   // result.  This requires turning off getMergeValues simplification, since
4657   // otherwise it will give us Res back.
4658   return DAG.getMergeValues(&Res, 1, false).getNode();
4659 }
4660
4661 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4662   MVT VT = Op.getValueType();
4663   MVT EltVT = VT;
4664   if (VT.isVector())
4665     EltVT = VT.getVectorElementType();
4666   std::vector<Constant*> CV;
4667   if (EltVT == MVT::f64) {
4668     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4669     CV.push_back(C);
4670     CV.push_back(C);
4671   } else {
4672     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4673     CV.push_back(C);
4674     CV.push_back(C);
4675     CV.push_back(C);
4676     CV.push_back(C);
4677   }
4678   Constant *C = ConstantVector::get(CV);
4679   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4680   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4681                                PseudoSourceValue::getConstantPool(), 0,
4682                                false, 16);
4683   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4684 }
4685
4686 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4687   MVT VT = Op.getValueType();
4688   MVT EltVT = VT;
4689   unsigned EltNum = 1;
4690   if (VT.isVector()) {
4691     EltVT = VT.getVectorElementType();
4692     EltNum = VT.getVectorNumElements();
4693   }
4694   std::vector<Constant*> CV;
4695   if (EltVT == MVT::f64) {
4696     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4697     CV.push_back(C);
4698     CV.push_back(C);
4699   } else {
4700     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4701     CV.push_back(C);
4702     CV.push_back(C);
4703     CV.push_back(C);
4704     CV.push_back(C);
4705   }
4706   Constant *C = ConstantVector::get(CV);
4707   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4708   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4709                                PseudoSourceValue::getConstantPool(), 0,
4710                                false, 16);
4711   if (VT.isVector()) {
4712     return DAG.getNode(ISD::BIT_CONVERT, VT,
4713                        DAG.getNode(ISD::XOR, MVT::v2i64,
4714                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4715                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4716   } else {
4717     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4718   }
4719 }
4720
4721 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4722   SDValue Op0 = Op.getOperand(0);
4723   SDValue Op1 = Op.getOperand(1);
4724   MVT VT = Op.getValueType();
4725   MVT SrcVT = Op1.getValueType();
4726
4727   // If second operand is smaller, extend it first.
4728   if (SrcVT.bitsLT(VT)) {
4729     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4730     SrcVT = VT;
4731   }
4732   // And if it is bigger, shrink it first.
4733   if (SrcVT.bitsGT(VT)) {
4734     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4735     SrcVT = VT;
4736   }
4737
4738   // At this point the operands and the result should have the same
4739   // type, and that won't be f80 since that is not custom lowered.
4740
4741   // First get the sign bit of second operand.
4742   std::vector<Constant*> CV;
4743   if (SrcVT == MVT::f64) {
4744     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4745     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4746   } else {
4747     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4748     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4749     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4750     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4751   }
4752   Constant *C = ConstantVector::get(CV);
4753   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4754   SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4755                                 PseudoSourceValue::getConstantPool(), 0,
4756                                 false, 16);
4757   SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4758
4759   // Shift sign bit right or left if the two operands have different types.
4760   if (SrcVT.bitsGT(VT)) {
4761     // Op0 is MVT::f32, Op1 is MVT::f64.
4762     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4763     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4764                           DAG.getConstant(32, MVT::i32));
4765     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4766     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4767                           DAG.getIntPtrConstant(0));
4768   }
4769
4770   // Clear first operand sign bit.
4771   CV.clear();
4772   if (VT == MVT::f64) {
4773     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4774     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4775   } else {
4776     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4777     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4778     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4779     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4780   }
4781   C = ConstantVector::get(CV);
4782   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4783   SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4784                                 PseudoSourceValue::getConstantPool(), 0,
4785                                 false, 16);
4786   SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4787
4788   // Or the value with the sign bit.
4789   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4790 }
4791
4792 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4793   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4794   SDValue Cond;
4795   SDValue Op0 = Op.getOperand(0);
4796   SDValue Op1 = Op.getOperand(1);
4797   SDValue CC = Op.getOperand(2);
4798   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4799   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4800   unsigned X86CC;
4801
4802   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4803                      Op0, Op1, DAG)) {
4804     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4805     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4806                        DAG.getConstant(X86CC, MVT::i8), Cond);
4807   }
4808
4809   assert(isFP && "Illegal integer SetCC!");
4810
4811   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4812   switch (SetCCOpcode) {
4813   default: assert(false && "Illegal floating point SetCC!");
4814   case ISD::SETOEQ: {  // !PF & ZF
4815     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4816                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4817     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4818                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4819     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4820   }
4821   case ISD::SETUNE: {  // PF | !ZF
4822     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4823                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4824     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4825                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4826     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4827   }
4828   }
4829 }
4830
4831 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4832   SDValue Cond;
4833   SDValue Op0 = Op.getOperand(0);
4834   SDValue Op1 = Op.getOperand(1);
4835   SDValue CC = Op.getOperand(2);
4836   MVT VT = Op.getValueType();
4837   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4838   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4839
4840   if (isFP) {
4841     unsigned SSECC = 8;
4842     MVT VT0 = Op0.getValueType();
4843     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4844     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4845     bool Swap = false;
4846
4847     switch (SetCCOpcode) {
4848     default: break;
4849     case ISD::SETOEQ:
4850     case ISD::SETEQ:  SSECC = 0; break;
4851     case ISD::SETOGT: 
4852     case ISD::SETGT: Swap = true; // Fallthrough
4853     case ISD::SETLT:
4854     case ISD::SETOLT: SSECC = 1; break;
4855     case ISD::SETOGE:
4856     case ISD::SETGE: Swap = true; // Fallthrough
4857     case ISD::SETLE:
4858     case ISD::SETOLE: SSECC = 2; break;
4859     case ISD::SETUO:  SSECC = 3; break;
4860     case ISD::SETUNE:
4861     case ISD::SETNE:  SSECC = 4; break;
4862     case ISD::SETULE: Swap = true;
4863     case ISD::SETUGE: SSECC = 5; break;
4864     case ISD::SETULT: Swap = true;
4865     case ISD::SETUGT: SSECC = 6; break;
4866     case ISD::SETO:   SSECC = 7; break;
4867     }
4868     if (Swap)
4869       std::swap(Op0, Op1);
4870
4871     // In the two special cases we can't handle, emit two comparisons.
4872     if (SSECC == 8) {
4873       if (SetCCOpcode == ISD::SETUEQ) {
4874         SDValue UNORD, EQ;
4875         UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4876         EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4877         return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4878       }
4879       else if (SetCCOpcode == ISD::SETONE) {
4880         SDValue ORD, NEQ;
4881         ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4882         NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4883         return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4884       }
4885       assert(0 && "Illegal FP comparison");
4886     }
4887     // Handle all other FP comparisons here.
4888     return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4889   }
4890   
4891   // We are handling one of the integer comparisons here.  Since SSE only has
4892   // GT and EQ comparisons for integer, swapping operands and multiple
4893   // operations may be required for some comparisons.
4894   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4895   bool Swap = false, Invert = false, FlipSigns = false;
4896   
4897   switch (VT.getSimpleVT()) {
4898   default: break;
4899   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4900   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4901   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4902   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4903   }
4904   
4905   switch (SetCCOpcode) {
4906   default: break;
4907   case ISD::SETNE:  Invert = true;
4908   case ISD::SETEQ:  Opc = EQOpc; break;
4909   case ISD::SETLT:  Swap = true;
4910   case ISD::SETGT:  Opc = GTOpc; break;
4911   case ISD::SETGE:  Swap = true;
4912   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
4913   case ISD::SETULT: Swap = true;
4914   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4915   case ISD::SETUGE: Swap = true;
4916   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4917   }
4918   if (Swap)
4919     std::swap(Op0, Op1);
4920   
4921   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
4922   // bits of the inputs before performing those operations.
4923   if (FlipSigns) {
4924     MVT EltVT = VT.getVectorElementType();
4925     SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4926     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4927     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4928                                     SignBits.size());
4929     Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4930     Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4931   }
4932   
4933   SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4934
4935   // If the logical-not of the result is required, perform that now.
4936   if (Invert) {
4937     MVT EltVT = VT.getVectorElementType();
4938     SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4939     std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4940     SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4941                                     NegOnes.size());
4942     Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4943   }
4944   return Result;
4945 }
4946
4947 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4948   bool addTest = true;
4949   SDValue Cond  = Op.getOperand(0);
4950   SDValue CC;
4951
4952   if (Cond.getOpcode() == ISD::SETCC)
4953     Cond = LowerSETCC(Cond, DAG);
4954
4955   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4956   // setting operand in place of the X86ISD::SETCC.
4957   if (Cond.getOpcode() == X86ISD::SETCC) {
4958     CC = Cond.getOperand(0);
4959
4960     SDValue Cmp = Cond.getOperand(1);
4961     unsigned Opc = Cmp.getOpcode();
4962     MVT VT = Op.getValueType();
4963     
4964     bool IllegalFPCMov = false;
4965     if (VT.isFloatingPoint() && !VT.isVector() &&
4966         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4967       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4968     
4969     if ((Opc == X86ISD::CMP ||
4970          Opc == X86ISD::COMI ||
4971          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4972       Cond = Cmp;
4973       addTest = false;
4974     }
4975   }
4976
4977   if (addTest) {
4978     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4979     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4980   }
4981
4982   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4983                                                     MVT::Flag);
4984   SmallVector<SDValue, 4> Ops;
4985   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4986   // condition is true.
4987   Ops.push_back(Op.getOperand(2));
4988   Ops.push_back(Op.getOperand(1));
4989   Ops.push_back(CC);
4990   Ops.push_back(Cond);
4991   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4992 }
4993
4994 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4995   bool addTest = true;
4996   SDValue Chain = Op.getOperand(0);
4997   SDValue Cond  = Op.getOperand(1);
4998   SDValue Dest  = Op.getOperand(2);
4999   SDValue CC;
5000
5001   if (Cond.getOpcode() == ISD::SETCC)
5002     Cond = LowerSETCC(Cond, DAG);
5003
5004   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5005   // setting operand in place of the X86ISD::SETCC.
5006   if (Cond.getOpcode() == X86ISD::SETCC) {
5007     CC = Cond.getOperand(0);
5008
5009     SDValue Cmp = Cond.getOperand(1);
5010     unsigned Opc = Cmp.getOpcode();
5011     if (Opc == X86ISD::CMP ||
5012         Opc == X86ISD::COMI ||
5013         Opc == X86ISD::UCOMI) {
5014       Cond = Cmp;
5015       addTest = false;
5016     }
5017   }
5018
5019   if (addTest) {
5020     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5021     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5022   }
5023   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5024                      Chain, Op.getOperand(2), CC, Cond);
5025 }
5026
5027
5028 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5029 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5030 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5031 // that the guard pages used by the OS virtual memory manager are allocated in
5032 // correct sequence.
5033 SDValue
5034 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5035                                            SelectionDAG &DAG) {
5036   assert(Subtarget->isTargetCygMing() &&
5037          "This should be used only on Cygwin/Mingw targets");
5038
5039   // Get the inputs.
5040   SDValue Chain = Op.getOperand(0);
5041   SDValue Size  = Op.getOperand(1);
5042   // FIXME: Ensure alignment here
5043
5044   SDValue Flag;
5045
5046   MVT IntPtr = getPointerTy();
5047   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5048
5049   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
5050
5051   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5052   Flag = Chain.getValue(1);
5053
5054   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5055   SDValue Ops[] = { Chain,
5056                       DAG.getTargetSymbol("_alloca", IntPtr),
5057                       DAG.getRegister(X86::EAX, IntPtr),
5058                       DAG.getRegister(X86StackPtr, SPTy),
5059                       Flag };
5060   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5061   Flag = Chain.getValue(1);
5062
5063   Chain = DAG.getCALLSEQ_END(Chain,
5064                              DAG.getIntPtrConstant(0),
5065                              DAG.getIntPtrConstant(0),
5066                              Flag);
5067
5068   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5069
5070   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5071   return DAG.getMergeValues(Ops1, 2);
5072 }
5073
5074 SDValue
5075 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5076                                         SDValue Chain,
5077                                         SDValue Dst, SDValue Src,
5078                                         SDValue Size, unsigned Align,
5079                                         const Value *DstSV, uint64_t DstSVOff) {
5080   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5081
5082   /// If not DWORD aligned or size is more than the threshold, call the library.
5083   /// The libc version is likely to be faster for these cases. It can use the
5084   /// address value and run time information about the CPU.
5085   if ((Align & 3) != 0 ||
5086       !ConstantSize ||
5087       ConstantSize->getZExtValue() >
5088         getSubtarget()->getMaxInlineSizeThreshold()) {
5089     SDValue InFlag(0, 0);
5090
5091     // Check to see if there is a specialized entry-point for memory zeroing.
5092     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5093     if (const char *bzeroEntry = 
5094           V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5095       MVT IntPtr = getPointerTy();
5096       const Type *IntPtrTy = TD->getIntPtrType();
5097       TargetLowering::ArgListTy Args; 
5098       TargetLowering::ArgListEntry Entry;
5099       Entry.Node = Dst;
5100       Entry.Ty = IntPtrTy;
5101       Args.push_back(Entry);
5102       Entry.Node = Size;
5103       Args.push_back(Entry);
5104       std::pair<SDValue,SDValue> CallResult =
5105         LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5106                     false, DAG.getSymbol(bzeroEntry, IntPtr),
5107                     Args, DAG);
5108       return CallResult.second;
5109     }
5110
5111     // Otherwise have the target-independent code call memset.
5112     return SDValue();
5113   }
5114
5115   uint64_t SizeVal = ConstantSize->getZExtValue();
5116   SDValue InFlag(0, 0);
5117   MVT AVT;
5118   SDValue Count;
5119   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5120   unsigned BytesLeft = 0;
5121   bool TwoRepStos = false;
5122   if (ValC) {
5123     unsigned ValReg;
5124     uint64_t Val = ValC->getZExtValue() & 255;
5125
5126     // If the value is a constant, then we can potentially use larger sets.
5127     switch (Align & 3) {
5128     case 2:   // WORD aligned
5129       AVT = MVT::i16;
5130       ValReg = X86::AX;
5131       Val = (Val << 8) | Val;
5132       break;
5133     case 0:  // DWORD aligned
5134       AVT = MVT::i32;
5135       ValReg = X86::EAX;
5136       Val = (Val << 8)  | Val;
5137       Val = (Val << 16) | Val;
5138       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5139         AVT = MVT::i64;
5140         ValReg = X86::RAX;
5141         Val = (Val << 32) | Val;
5142       }
5143       break;
5144     default:  // Byte aligned
5145       AVT = MVT::i8;
5146       ValReg = X86::AL;
5147       Count = DAG.getIntPtrConstant(SizeVal);
5148       break;
5149     }
5150
5151     if (AVT.bitsGT(MVT::i8)) {
5152       unsigned UBytes = AVT.getSizeInBits() / 8;
5153       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5154       BytesLeft = SizeVal % UBytes;
5155     }
5156
5157     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5158                               InFlag);
5159     InFlag = Chain.getValue(1);
5160   } else {
5161     AVT = MVT::i8;
5162     Count  = DAG.getIntPtrConstant(SizeVal);
5163     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5164     InFlag = Chain.getValue(1);
5165   }
5166
5167   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5168                             Count, InFlag);
5169   InFlag = Chain.getValue(1);
5170   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5171                             Dst, InFlag);
5172   InFlag = Chain.getValue(1);
5173
5174   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5175   SmallVector<SDValue, 8> Ops;
5176   Ops.push_back(Chain);
5177   Ops.push_back(DAG.getValueType(AVT));
5178   Ops.push_back(InFlag);
5179   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5180
5181   if (TwoRepStos) {
5182     InFlag = Chain.getValue(1);
5183     Count  = Size;
5184     MVT CVT = Count.getValueType();
5185     SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5186                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5187     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5188                               Left, InFlag);
5189     InFlag = Chain.getValue(1);
5190     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5191     Ops.clear();
5192     Ops.push_back(Chain);
5193     Ops.push_back(DAG.getValueType(MVT::i8));
5194     Ops.push_back(InFlag);
5195     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5196   } else if (BytesLeft) {
5197     // Handle the last 1 - 7 bytes.
5198     unsigned Offset = SizeVal - BytesLeft;
5199     MVT AddrVT = Dst.getValueType();
5200     MVT SizeVT = Size.getValueType();
5201
5202     Chain = DAG.getMemset(Chain,
5203                           DAG.getNode(ISD::ADD, AddrVT, Dst,
5204                                       DAG.getConstant(Offset, AddrVT)),
5205                           Src,
5206                           DAG.getConstant(BytesLeft, SizeVT),
5207                           Align, DstSV, DstSVOff + Offset);
5208   }
5209
5210   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5211   return Chain;
5212 }
5213
5214 SDValue
5215 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5216                                       SDValue Chain, SDValue Dst, SDValue Src,
5217                                       SDValue Size, unsigned Align,
5218                                       bool AlwaysInline,
5219                                       const Value *DstSV, uint64_t DstSVOff,
5220                                       const Value *SrcSV, uint64_t SrcSVOff) {  
5221   // This requires the copy size to be a constant, preferrably
5222   // within a subtarget-specific limit.
5223   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5224   if (!ConstantSize)
5225     return SDValue();
5226   uint64_t SizeVal = ConstantSize->getZExtValue();
5227   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5228     return SDValue();
5229
5230   /// If not DWORD aligned, call the library.
5231   if ((Align & 3) != 0)
5232     return SDValue();
5233
5234   // DWORD aligned
5235   MVT AVT = MVT::i32;
5236   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5237     AVT = MVT::i64;
5238
5239   unsigned UBytes = AVT.getSizeInBits() / 8;
5240   unsigned CountVal = SizeVal / UBytes;
5241   SDValue Count = DAG.getIntPtrConstant(CountVal);
5242   unsigned BytesLeft = SizeVal % UBytes;
5243
5244   SDValue InFlag(0, 0);
5245   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5246                             Count, InFlag);
5247   InFlag = Chain.getValue(1);
5248   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5249                             Dst, InFlag);
5250   InFlag = Chain.getValue(1);
5251   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5252                             Src, InFlag);
5253   InFlag = Chain.getValue(1);
5254
5255   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5256   SmallVector<SDValue, 8> Ops;
5257   Ops.push_back(Chain);
5258   Ops.push_back(DAG.getValueType(AVT));
5259   Ops.push_back(InFlag);
5260   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5261
5262   SmallVector<SDValue, 4> Results;
5263   Results.push_back(RepMovs);
5264   if (BytesLeft) {
5265     // Handle the last 1 - 7 bytes.
5266     unsigned Offset = SizeVal - BytesLeft;
5267     MVT DstVT = Dst.getValueType();
5268     MVT SrcVT = Src.getValueType();
5269     MVT SizeVT = Size.getValueType();
5270     Results.push_back(DAG.getMemcpy(Chain,
5271                                     DAG.getNode(ISD::ADD, DstVT, Dst,
5272                                                 DAG.getConstant(Offset, DstVT)),
5273                                     DAG.getNode(ISD::ADD, SrcVT, Src,
5274                                                 DAG.getConstant(Offset, SrcVT)),
5275                                     DAG.getConstant(BytesLeft, SizeVT),
5276                                     Align, AlwaysInline,
5277                                     DstSV, DstSVOff + Offset,
5278                                     SrcSV, SrcSVOff + Offset));
5279   }
5280
5281   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5282 }
5283
5284 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5285 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5286   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5287   SDValue TheChain = N->getOperand(0);
5288   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5289   if (Subtarget->is64Bit()) {
5290     SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5291     SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5292                                        MVT::i64, rax.getValue(2));
5293     SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5294                                 DAG.getConstant(32, MVT::i8));
5295     SDValue Ops[] = {
5296       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5297     };
5298     
5299     return DAG.getMergeValues(Ops, 2).getNode();
5300   }
5301   
5302   SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5303   SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5304                                        MVT::i32, eax.getValue(2));
5305   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
5306   SDValue Ops[] = { eax, edx };
5307   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5308
5309   // Use a MERGE_VALUES to return the value and chain.
5310   Ops[1] = edx.getValue(1);
5311   return DAG.getMergeValues(Ops, 2).getNode();
5312 }
5313
5314 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5315   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5316
5317   if (!Subtarget->is64Bit()) {
5318     // vastart just stores the address of the VarArgsFrameIndex slot into the
5319     // memory location argument.
5320     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5321     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5322   }
5323
5324   // __va_list_tag:
5325   //   gp_offset         (0 - 6 * 8)
5326   //   fp_offset         (48 - 48 + 8 * 16)
5327   //   overflow_arg_area (point to parameters coming in memory).
5328   //   reg_save_area
5329   SmallVector<SDValue, 8> MemOps;
5330   SDValue FIN = Op.getOperand(1);
5331   // Store gp_offset
5332   SDValue Store = DAG.getStore(Op.getOperand(0),
5333                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5334                                  FIN, SV, 0);
5335   MemOps.push_back(Store);
5336
5337   // Store fp_offset
5338   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5339   Store = DAG.getStore(Op.getOperand(0),
5340                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5341                        FIN, SV, 0);
5342   MemOps.push_back(Store);
5343
5344   // Store ptr to overflow_arg_area
5345   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5346   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5347   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5348   MemOps.push_back(Store);
5349
5350   // Store ptr to reg_save_area.
5351   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5352   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5353   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5354   MemOps.push_back(Store);
5355   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5356 }
5357
5358 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5359   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5360   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5361   SDValue Chain = Op.getOperand(0);
5362   SDValue SrcPtr = Op.getOperand(1);
5363   SDValue SrcSV = Op.getOperand(2);
5364
5365   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5366   abort();
5367   return SDValue();
5368 }
5369
5370 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5371   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5372   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5373   SDValue Chain = Op.getOperand(0);
5374   SDValue DstPtr = Op.getOperand(1);
5375   SDValue SrcPtr = Op.getOperand(2);
5376   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5377   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5378
5379   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5380                        DAG.getIntPtrConstant(24), 8, false,
5381                        DstSV, 0, SrcSV, 0);
5382 }
5383
5384 SDValue
5385 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5386   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5387   switch (IntNo) {
5388   default: return SDValue();    // Don't custom lower most intrinsics.
5389   // Comparison intrinsics.
5390   case Intrinsic::x86_sse_comieq_ss:
5391   case Intrinsic::x86_sse_comilt_ss:
5392   case Intrinsic::x86_sse_comile_ss:
5393   case Intrinsic::x86_sse_comigt_ss:
5394   case Intrinsic::x86_sse_comige_ss:
5395   case Intrinsic::x86_sse_comineq_ss:
5396   case Intrinsic::x86_sse_ucomieq_ss:
5397   case Intrinsic::x86_sse_ucomilt_ss:
5398   case Intrinsic::x86_sse_ucomile_ss:
5399   case Intrinsic::x86_sse_ucomigt_ss:
5400   case Intrinsic::x86_sse_ucomige_ss:
5401   case Intrinsic::x86_sse_ucomineq_ss:
5402   case Intrinsic::x86_sse2_comieq_sd:
5403   case Intrinsic::x86_sse2_comilt_sd:
5404   case Intrinsic::x86_sse2_comile_sd:
5405   case Intrinsic::x86_sse2_comigt_sd:
5406   case Intrinsic::x86_sse2_comige_sd:
5407   case Intrinsic::x86_sse2_comineq_sd:
5408   case Intrinsic::x86_sse2_ucomieq_sd:
5409   case Intrinsic::x86_sse2_ucomilt_sd:
5410   case Intrinsic::x86_sse2_ucomile_sd:
5411   case Intrinsic::x86_sse2_ucomigt_sd:
5412   case Intrinsic::x86_sse2_ucomige_sd:
5413   case Intrinsic::x86_sse2_ucomineq_sd: {
5414     unsigned Opc = 0;
5415     ISD::CondCode CC = ISD::SETCC_INVALID;
5416     switch (IntNo) {
5417     default: break;
5418     case Intrinsic::x86_sse_comieq_ss:
5419     case Intrinsic::x86_sse2_comieq_sd:
5420       Opc = X86ISD::COMI;
5421       CC = ISD::SETEQ;
5422       break;
5423     case Intrinsic::x86_sse_comilt_ss:
5424     case Intrinsic::x86_sse2_comilt_sd:
5425       Opc = X86ISD::COMI;
5426       CC = ISD::SETLT;
5427       break;
5428     case Intrinsic::x86_sse_comile_ss:
5429     case Intrinsic::x86_sse2_comile_sd:
5430       Opc = X86ISD::COMI;
5431       CC = ISD::SETLE;
5432       break;
5433     case Intrinsic::x86_sse_comigt_ss:
5434     case Intrinsic::x86_sse2_comigt_sd:
5435       Opc = X86ISD::COMI;
5436       CC = ISD::SETGT;
5437       break;
5438     case Intrinsic::x86_sse_comige_ss:
5439     case Intrinsic::x86_sse2_comige_sd:
5440       Opc = X86ISD::COMI;
5441       CC = ISD::SETGE;
5442       break;
5443     case Intrinsic::x86_sse_comineq_ss:
5444     case Intrinsic::x86_sse2_comineq_sd:
5445       Opc = X86ISD::COMI;
5446       CC = ISD::SETNE;
5447       break;
5448     case Intrinsic::x86_sse_ucomieq_ss:
5449     case Intrinsic::x86_sse2_ucomieq_sd:
5450       Opc = X86ISD::UCOMI;
5451       CC = ISD::SETEQ;
5452       break;
5453     case Intrinsic::x86_sse_ucomilt_ss:
5454     case Intrinsic::x86_sse2_ucomilt_sd:
5455       Opc = X86ISD::UCOMI;
5456       CC = ISD::SETLT;
5457       break;
5458     case Intrinsic::x86_sse_ucomile_ss:
5459     case Intrinsic::x86_sse2_ucomile_sd:
5460       Opc = X86ISD::UCOMI;
5461       CC = ISD::SETLE;
5462       break;
5463     case Intrinsic::x86_sse_ucomigt_ss:
5464     case Intrinsic::x86_sse2_ucomigt_sd:
5465       Opc = X86ISD::UCOMI;
5466       CC = ISD::SETGT;
5467       break;
5468     case Intrinsic::x86_sse_ucomige_ss:
5469     case Intrinsic::x86_sse2_ucomige_sd:
5470       Opc = X86ISD::UCOMI;
5471       CC = ISD::SETGE;
5472       break;
5473     case Intrinsic::x86_sse_ucomineq_ss:
5474     case Intrinsic::x86_sse2_ucomineq_sd:
5475       Opc = X86ISD::UCOMI;
5476       CC = ISD::SETNE;
5477       break;
5478     }
5479
5480     unsigned X86CC;
5481     SDValue LHS = Op.getOperand(1);
5482     SDValue RHS = Op.getOperand(2);
5483     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5484
5485     SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5486     SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5487                                 DAG.getConstant(X86CC, MVT::i8), Cond);
5488     return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5489   }
5490
5491   // Fix vector shift instructions where the last operand is a non-immediate
5492   // i32 value.
5493   case Intrinsic::x86_sse2_pslli_w:
5494   case Intrinsic::x86_sse2_pslli_d:
5495   case Intrinsic::x86_sse2_pslli_q:
5496   case Intrinsic::x86_sse2_psrli_w:
5497   case Intrinsic::x86_sse2_psrli_d:
5498   case Intrinsic::x86_sse2_psrli_q:
5499   case Intrinsic::x86_sse2_psrai_w:
5500   case Intrinsic::x86_sse2_psrai_d:
5501   case Intrinsic::x86_mmx_pslli_w:
5502   case Intrinsic::x86_mmx_pslli_d:
5503   case Intrinsic::x86_mmx_pslli_q:
5504   case Intrinsic::x86_mmx_psrli_w:
5505   case Intrinsic::x86_mmx_psrli_d:
5506   case Intrinsic::x86_mmx_psrli_q:
5507   case Intrinsic::x86_mmx_psrai_w:
5508   case Intrinsic::x86_mmx_psrai_d: {
5509     SDValue ShAmt = Op.getOperand(2);
5510     if (isa<ConstantSDNode>(ShAmt))
5511       return SDValue();
5512
5513     unsigned NewIntNo = 0;
5514     MVT ShAmtVT = MVT::v4i32;
5515     switch (IntNo) {
5516     case Intrinsic::x86_sse2_pslli_w:
5517       NewIntNo = Intrinsic::x86_sse2_psll_w;
5518       break;
5519     case Intrinsic::x86_sse2_pslli_d:
5520       NewIntNo = Intrinsic::x86_sse2_psll_d;
5521       break;
5522     case Intrinsic::x86_sse2_pslli_q:
5523       NewIntNo = Intrinsic::x86_sse2_psll_q;
5524       break;
5525     case Intrinsic::x86_sse2_psrli_w:
5526       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5527       break;
5528     case Intrinsic::x86_sse2_psrli_d:
5529       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5530       break;
5531     case Intrinsic::x86_sse2_psrli_q:
5532       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5533       break;
5534     case Intrinsic::x86_sse2_psrai_w:
5535       NewIntNo = Intrinsic::x86_sse2_psra_w;
5536       break;
5537     case Intrinsic::x86_sse2_psrai_d:
5538       NewIntNo = Intrinsic::x86_sse2_psra_d;
5539       break;
5540     default: {
5541       ShAmtVT = MVT::v2i32;
5542       switch (IntNo) {
5543       case Intrinsic::x86_mmx_pslli_w:
5544         NewIntNo = Intrinsic::x86_mmx_psll_w;
5545         break;
5546       case Intrinsic::x86_mmx_pslli_d:
5547         NewIntNo = Intrinsic::x86_mmx_psll_d;
5548         break;
5549       case Intrinsic::x86_mmx_pslli_q:
5550         NewIntNo = Intrinsic::x86_mmx_psll_q;
5551         break;
5552       case Intrinsic::x86_mmx_psrli_w:
5553         NewIntNo = Intrinsic::x86_mmx_psrl_w;
5554         break;
5555       case Intrinsic::x86_mmx_psrli_d:
5556         NewIntNo = Intrinsic::x86_mmx_psrl_d;
5557         break;
5558       case Intrinsic::x86_mmx_psrli_q:
5559         NewIntNo = Intrinsic::x86_mmx_psrl_q;
5560         break;
5561       case Intrinsic::x86_mmx_psrai_w:
5562         NewIntNo = Intrinsic::x86_mmx_psra_w;
5563         break;
5564       case Intrinsic::x86_mmx_psrai_d:
5565         NewIntNo = Intrinsic::x86_mmx_psra_d;
5566         break;
5567       default: abort();  // Can't reach here.
5568       }
5569       break;
5570     }
5571     }
5572     MVT VT = Op.getValueType();
5573     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5574                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5575     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5576                        DAG.getConstant(NewIntNo, MVT::i32),
5577                        Op.getOperand(1), ShAmt);
5578   }
5579   }
5580 }
5581
5582 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5583   // Depths > 0 not supported yet!
5584   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5585     return SDValue();
5586   
5587   // Just load the return address
5588   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5589   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5590 }
5591
5592 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5593   // Depths > 0 not supported yet!
5594   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5595     return SDValue();
5596
5597   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5598   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5599                      DAG.getIntPtrConstant(TD->getPointerSize()));
5600 }
5601
5602 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5603                                                      SelectionDAG &DAG) {
5604   return DAG.getIntPtrConstant(2*TD->getPointerSize());
5605 }
5606
5607 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5608 {
5609   MachineFunction &MF = DAG.getMachineFunction();
5610   SDValue Chain     = Op.getOperand(0);
5611   SDValue Offset    = Op.getOperand(1);
5612   SDValue Handler   = Op.getOperand(2);
5613
5614   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5615                                   getPointerTy());
5616   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5617
5618   SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5619                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
5620   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5621   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5622   Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5623   MF.getRegInfo().addLiveOut(StoreAddrReg);
5624
5625   return DAG.getNode(X86ISD::EH_RETURN,
5626                      MVT::Other,
5627                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5628 }
5629
5630 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5631                                              SelectionDAG &DAG) {
5632   SDValue Root = Op.getOperand(0);
5633   SDValue Trmp = Op.getOperand(1); // trampoline
5634   SDValue FPtr = Op.getOperand(2); // nested function
5635   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5636
5637   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5638
5639   const X86InstrInfo *TII =
5640     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5641
5642   if (Subtarget->is64Bit()) {
5643     SDValue OutChains[6];
5644
5645     // Large code-model.
5646
5647     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5648     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5649
5650     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5651     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5652
5653     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5654
5655     // Load the pointer to the nested function into R11.
5656     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5657     SDValue Addr = Trmp;
5658     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5659                                 TrmpAddr, 0);
5660
5661     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5662     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5663
5664     // Load the 'nest' parameter value into R10.
5665     // R10 is specified in X86CallingConv.td
5666     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5667     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5668     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5669                                 TrmpAddr, 10);
5670
5671     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5672     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5673
5674     // Jump to the nested function.
5675     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5676     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5677     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5678                                 TrmpAddr, 20);
5679
5680     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5681     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5682     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5683                                 TrmpAddr, 22);
5684
5685     SDValue Ops[] =
5686       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5687     return DAG.getMergeValues(Ops, 2);
5688   } else {
5689     const Function *Func =
5690       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5691     unsigned CC = Func->getCallingConv();
5692     unsigned NestReg;
5693
5694     switch (CC) {
5695     default:
5696       assert(0 && "Unsupported calling convention");
5697     case CallingConv::C:
5698     case CallingConv::X86_StdCall: {
5699       // Pass 'nest' parameter in ECX.
5700       // Must be kept in sync with X86CallingConv.td
5701       NestReg = X86::ECX;
5702
5703       // Check that ECX wasn't needed by an 'inreg' parameter.
5704       const FunctionType *FTy = Func->getFunctionType();
5705       const PAListPtr &Attrs = Func->getParamAttrs();
5706
5707       if (!Attrs.isEmpty() && !Func->isVarArg()) {
5708         unsigned InRegCount = 0;
5709         unsigned Idx = 1;
5710
5711         for (FunctionType::param_iterator I = FTy->param_begin(),
5712              E = FTy->param_end(); I != E; ++I, ++Idx)
5713           if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5714             // FIXME: should only count parameters that are lowered to integers.
5715             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5716
5717         if (InRegCount > 2) {
5718           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5719           abort();
5720         }
5721       }
5722       break;
5723     }
5724     case CallingConv::X86_FastCall:
5725     case CallingConv::Fast:
5726       // Pass 'nest' parameter in EAX.
5727       // Must be kept in sync with X86CallingConv.td
5728       NestReg = X86::EAX;
5729       break;
5730     }
5731
5732     SDValue OutChains[4];
5733     SDValue Addr, Disp;
5734
5735     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5736     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5737
5738     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5739     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5740     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5741                                 Trmp, TrmpAddr, 0);
5742
5743     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5744     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5745
5746     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5747     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5748     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5749                                 TrmpAddr, 5, false, 1);
5750
5751     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5752     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5753
5754     SDValue Ops[] =
5755       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5756     return DAG.getMergeValues(Ops, 2);
5757   }
5758 }
5759
5760 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5761   /*
5762    The rounding mode is in bits 11:10 of FPSR, and has the following
5763    settings:
5764      00 Round to nearest
5765      01 Round to -inf
5766      10 Round to +inf
5767      11 Round to 0
5768
5769   FLT_ROUNDS, on the other hand, expects the following:
5770     -1 Undefined
5771      0 Round to 0
5772      1 Round to nearest
5773      2 Round to +inf
5774      3 Round to -inf
5775
5776   To perform the conversion, we do:
5777     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5778   */
5779
5780   MachineFunction &MF = DAG.getMachineFunction();
5781   const TargetMachine &TM = MF.getTarget();
5782   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5783   unsigned StackAlignment = TFI.getStackAlignment();
5784   MVT VT = Op.getValueType();
5785
5786   // Save FP Control Word to stack slot
5787   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5788   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5789
5790   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5791                                 DAG.getEntryNode(), StackSlot);
5792
5793   // Load FP Control Word from stack slot
5794   SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5795
5796   // Transform as necessary
5797   SDValue CWD1 =
5798     DAG.getNode(ISD::SRL, MVT::i16,
5799                 DAG.getNode(ISD::AND, MVT::i16,
5800                             CWD, DAG.getConstant(0x800, MVT::i16)),
5801                 DAG.getConstant(11, MVT::i8));
5802   SDValue CWD2 =
5803     DAG.getNode(ISD::SRL, MVT::i16,
5804                 DAG.getNode(ISD::AND, MVT::i16,
5805                             CWD, DAG.getConstant(0x400, MVT::i16)),
5806                 DAG.getConstant(9, MVT::i8));
5807
5808   SDValue RetVal =
5809     DAG.getNode(ISD::AND, MVT::i16,
5810                 DAG.getNode(ISD::ADD, MVT::i16,
5811                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5812                             DAG.getConstant(1, MVT::i16)),
5813                 DAG.getConstant(3, MVT::i16));
5814
5815
5816   return DAG.getNode((VT.getSizeInBits() < 16 ?
5817                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5818 }
5819
5820 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5821   MVT VT = Op.getValueType();
5822   MVT OpVT = VT;
5823   unsigned NumBits = VT.getSizeInBits();
5824
5825   Op = Op.getOperand(0);
5826   if (VT == MVT::i8) {
5827     // Zero extend to i32 since there is not an i8 bsr.
5828     OpVT = MVT::i32;
5829     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5830   }
5831
5832   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5833   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5834   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5835
5836   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5837   SmallVector<SDValue, 4> Ops;
5838   Ops.push_back(Op);
5839   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5840   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5841   Ops.push_back(Op.getValue(1));
5842   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5843
5844   // Finally xor with NumBits-1.
5845   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5846
5847   if (VT == MVT::i8)
5848     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5849   return Op;
5850 }
5851
5852 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5853   MVT VT = Op.getValueType();
5854   MVT OpVT = VT;
5855   unsigned NumBits = VT.getSizeInBits();
5856
5857   Op = Op.getOperand(0);
5858   if (VT == MVT::i8) {
5859     OpVT = MVT::i32;
5860     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5861   }
5862
5863   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5864   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5865   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5866
5867   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5868   SmallVector<SDValue, 4> Ops;
5869   Ops.push_back(Op);
5870   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5871   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5872   Ops.push_back(Op.getValue(1));
5873   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5874
5875   if (VT == MVT::i8)
5876     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5877   return Op;
5878 }
5879
5880 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5881   MVT T = Op.getValueType();
5882   unsigned Reg = 0;
5883   unsigned size = 0;
5884   switch(T.getSimpleVT()) {
5885   default:
5886     assert(false && "Invalid value type!");
5887   case MVT::i8:  Reg = X86::AL;  size = 1; break;
5888   case MVT::i16: Reg = X86::AX;  size = 2; break;
5889   case MVT::i32: Reg = X86::EAX; size = 4; break;
5890   case MVT::i64: 
5891     if (Subtarget->is64Bit()) {
5892       Reg = X86::RAX; size = 8;
5893     } else //Should go away when LowerType stuff lands
5894       return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
5895     break;
5896   };
5897   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5898                                     Op.getOperand(2), SDValue());
5899   SDValue Ops[] = { cpIn.getValue(0),
5900                       Op.getOperand(1),
5901                       Op.getOperand(3),
5902                       DAG.getTargetConstant(size, MVT::i8),
5903                       cpIn.getValue(1) };
5904   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5905   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5906   SDValue cpOut = 
5907     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5908   return cpOut;
5909 }
5910
5911 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
5912                                                  SelectionDAG &DAG) {
5913   MVT T = Op->getValueType(0);
5914   assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5915   SDValue cpInL, cpInH;
5916   cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5917                       DAG.getConstant(0, MVT::i32));
5918   cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5919                       DAG.getConstant(1, MVT::i32));
5920   cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5921                            cpInL, SDValue());
5922   cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5923                            cpInH, cpInL.getValue(1));
5924   SDValue swapInL, swapInH;
5925   swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5926                         DAG.getConstant(0, MVT::i32));
5927   swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5928                         DAG.getConstant(1, MVT::i32));
5929   swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5930                              swapInL, cpInH.getValue(1));
5931   swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5932                              swapInH, swapInL.getValue(1));
5933   SDValue Ops[] = { swapInH.getValue(0),
5934                       Op->getOperand(1),
5935                       swapInH.getValue(1)};
5936   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5937   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5938   SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32, 
5939                                         Result.getValue(1));
5940   SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32, 
5941                                         cpOutL.getValue(2));
5942   SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5943   SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5944   SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5945   return DAG.getMergeValues(Vals, 2).getNode();
5946 }
5947
5948 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op,
5949                                                  SelectionDAG &DAG) {
5950   MVT T = Op->getValueType(0);
5951   SDValue negOp = DAG.getNode(ISD::SUB, T,
5952                                 DAG.getConstant(0, T), Op->getOperand(2));
5953   return DAG.getAtomic((T==MVT::i8 ? ISD::ATOMIC_LOAD_ADD_8:
5954                         T==MVT::i16 ? ISD::ATOMIC_LOAD_ADD_16:
5955                         T==MVT::i32 ? ISD::ATOMIC_LOAD_ADD_32:
5956                         T==MVT::i64 ? ISD::ATOMIC_LOAD_ADD_64: 0),
5957                        Op->getOperand(0), Op->getOperand(1), negOp,
5958                        cast<AtomicSDNode>(Op)->getSrcValue(),
5959                        cast<AtomicSDNode>(Op)->getAlignment()).getNode();
5960 }
5961
5962 /// LowerOperation - Provide custom lowering hooks for some operations.
5963 ///
5964 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5965   switch (Op.getOpcode()) {
5966   default: assert(0 && "Should not custom lower this!");
5967   case ISD::ATOMIC_CMP_SWAP_8:  return LowerCMP_SWAP(Op,DAG);
5968   case ISD::ATOMIC_CMP_SWAP_16: return LowerCMP_SWAP(Op,DAG);
5969   case ISD::ATOMIC_CMP_SWAP_32: return LowerCMP_SWAP(Op,DAG);
5970   case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
5971   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5972   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5973   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5974   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5975   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5976   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5977   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5978   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5979   case ISD::Symbol:             return LowerExternalSymbol(Op, DAG);
5980   case ISD::SHL_PARTS:
5981   case ISD::SRA_PARTS:
5982   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5983   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5984   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5985   case ISD::FABS:               return LowerFABS(Op, DAG);
5986   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5987   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5988   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5989   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
5990   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5991   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5992   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5993   case ISD::CALL:               return LowerCALL(Op, DAG);
5994   case ISD::RET:                return LowerRET(Op, DAG);
5995   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5996   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5997   case ISD::VAARG:              return LowerVAARG(Op, DAG);
5998   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
5999   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6000   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6001   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6002   case ISD::FRAME_TO_ARGS_OFFSET:
6003                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6004   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6005   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6006   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6007   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6008   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6009   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6010       
6011   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6012   case ISD::READCYCLECOUNTER:
6013     return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6014   }
6015 }
6016
6017 /// ReplaceNodeResults - Replace a node with an illegal result type
6018 /// with a new node built out of custom code.
6019 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6020   switch (N->getOpcode()) {
6021   default: assert(0 && "Should not custom lower this!");
6022   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
6023   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
6024   case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6025   case ISD::ATOMIC_LOAD_SUB_8:  return ExpandATOMIC_LOAD_SUB(N,DAG);
6026   case ISD::ATOMIC_LOAD_SUB_16: return ExpandATOMIC_LOAD_SUB(N,DAG);
6027   case ISD::ATOMIC_LOAD_SUB_32: return ExpandATOMIC_LOAD_SUB(N,DAG);
6028   case ISD::ATOMIC_LOAD_SUB_64: return ExpandATOMIC_LOAD_SUB(N,DAG);
6029   }
6030 }
6031
6032 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6033   switch (Opcode) {
6034   default: return NULL;
6035   case X86ISD::BSF:                return "X86ISD::BSF";
6036   case X86ISD::BSR:                return "X86ISD::BSR";
6037   case X86ISD::SHLD:               return "X86ISD::SHLD";
6038   case X86ISD::SHRD:               return "X86ISD::SHRD";
6039   case X86ISD::FAND:               return "X86ISD::FAND";
6040   case X86ISD::FOR:                return "X86ISD::FOR";
6041   case X86ISD::FXOR:               return "X86ISD::FXOR";
6042   case X86ISD::FSRL:               return "X86ISD::FSRL";
6043   case X86ISD::FILD:               return "X86ISD::FILD";
6044   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6045   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6046   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6047   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6048   case X86ISD::FLD:                return "X86ISD::FLD";
6049   case X86ISD::FST:                return "X86ISD::FST";
6050   case X86ISD::CALL:               return "X86ISD::CALL";
6051   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6052   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6053   case X86ISD::CMP:                return "X86ISD::CMP";
6054   case X86ISD::COMI:               return "X86ISD::COMI";
6055   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6056   case X86ISD::SETCC:              return "X86ISD::SETCC";
6057   case X86ISD::CMOV:               return "X86ISD::CMOV";
6058   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
6059   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
6060   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
6061   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
6062   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
6063   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
6064   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
6065   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
6066   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
6067   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
6068   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
6069   case X86ISD::FMAX:               return "X86ISD::FMAX";
6070   case X86ISD::FMIN:               return "X86ISD::FMIN";
6071   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6072   case X86ISD::FRCP:               return "X86ISD::FRCP";
6073   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6074   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
6075   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6076   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6077   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6078   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6079   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6080   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6081   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6082   case X86ISD::VSHL:               return "X86ISD::VSHL";
6083   case X86ISD::VSRL:               return "X86ISD::VSRL";
6084   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6085   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6086   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6087   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6088   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6089   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6090   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6091   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6092   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6093   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6094   }
6095 }
6096
6097 // isLegalAddressingMode - Return true if the addressing mode represented
6098 // by AM is legal for this target, for a load/store of the specified type.
6099 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
6100                                               const Type *Ty) const {
6101   // X86 supports extremely general addressing modes.
6102   
6103   // X86 allows a sign-extended 32-bit immediate field as a displacement.
6104   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6105     return false;
6106   
6107   if (AM.BaseGV) {
6108     // We can only fold this if we don't need an extra load.
6109     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6110       return false;
6111
6112     // X86-64 only supports addr of globals in small code model.
6113     if (Subtarget->is64Bit()) {
6114       if (getTargetMachine().getCodeModel() != CodeModel::Small)
6115         return false;
6116       // If lower 4G is not available, then we must use rip-relative addressing.
6117       if (AM.BaseOffs || AM.Scale > 1)
6118         return false;
6119     }
6120   }
6121   
6122   switch (AM.Scale) {
6123   case 0:
6124   case 1:
6125   case 2:
6126   case 4:
6127   case 8:
6128     // These scales always work.
6129     break;
6130   case 3:
6131   case 5:
6132   case 9:
6133     // These scales are formed with basereg+scalereg.  Only accept if there is
6134     // no basereg yet.
6135     if (AM.HasBaseReg)
6136       return false;
6137     break;
6138   default:  // Other stuff never works.
6139     return false;
6140   }
6141   
6142   return true;
6143 }
6144
6145
6146 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6147   if (!Ty1->isInteger() || !Ty2->isInteger())
6148     return false;
6149   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6150   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6151   if (NumBits1 <= NumBits2)
6152     return false;
6153   return Subtarget->is64Bit() || NumBits1 < 64;
6154 }
6155
6156 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6157   if (!VT1.isInteger() || !VT2.isInteger())
6158     return false;
6159   unsigned NumBits1 = VT1.getSizeInBits();
6160   unsigned NumBits2 = VT2.getSizeInBits();
6161   if (NumBits1 <= NumBits2)
6162     return false;
6163   return Subtarget->is64Bit() || NumBits1 < 64;
6164 }
6165
6166 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6167 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6168 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6169 /// are assumed to be legal.
6170 bool
6171 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6172   // Only do shuffles on 128-bit vector types for now.
6173   if (VT.getSizeInBits() == 64) return false;
6174   return (Mask.getNode()->getNumOperands() <= 4 ||
6175           isIdentityMask(Mask.getNode()) ||
6176           isIdentityMask(Mask.getNode(), true) ||
6177           isSplatMask(Mask.getNode())  ||
6178           isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6179           X86::isUNPCKLMask(Mask.getNode()) ||
6180           X86::isUNPCKHMask(Mask.getNode()) ||
6181           X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6182           X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6183 }
6184
6185 bool
6186 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6187                                           MVT EVT, SelectionDAG &DAG) const {
6188   unsigned NumElts = BVOps.size();
6189   // Only do shuffles on 128-bit vector types for now.
6190   if (EVT.getSizeInBits() * NumElts == 64) return false;
6191   if (NumElts == 2) return true;
6192   if (NumElts == 4) {
6193     return (isMOVLMask(&BVOps[0], 4)  ||
6194             isCommutedMOVL(&BVOps[0], 4, true) ||
6195             isSHUFPMask(&BVOps[0], 4) || 
6196             isCommutedSHUFP(&BVOps[0], 4));
6197   }
6198   return false;
6199 }
6200
6201 //===----------------------------------------------------------------------===//
6202 //                           X86 Scheduler Hooks
6203 //===----------------------------------------------------------------------===//
6204
6205 // private utility function
6206 MachineBasicBlock *
6207 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6208                                                        MachineBasicBlock *MBB,
6209                                                        unsigned regOpc,
6210                                                        unsigned immOpc,
6211                                                        unsigned LoadOpc,
6212                                                        unsigned CXchgOpc,
6213                                                        unsigned copyOpc,
6214                                                        unsigned notOpc,
6215                                                        unsigned EAXreg,
6216                                                        TargetRegisterClass *RC,
6217                                                        bool invSrc) {
6218   // For the atomic bitwise operator, we generate
6219   //   thisMBB:
6220   //   newMBB:
6221   //     ld  t1 = [bitinstr.addr]
6222   //     op  t2 = t1, [bitinstr.val]
6223   //     mov EAX = t1
6224   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6225   //     bz  newMBB
6226   //     fallthrough -->nextMBB
6227   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6228   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6229   MachineFunction::iterator MBBIter = MBB;
6230   ++MBBIter;
6231   
6232   /// First build the CFG
6233   MachineFunction *F = MBB->getParent();
6234   MachineBasicBlock *thisMBB = MBB;
6235   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6236   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6237   F->insert(MBBIter, newMBB);
6238   F->insert(MBBIter, nextMBB);
6239   
6240   // Move all successors to thisMBB to nextMBB
6241   nextMBB->transferSuccessors(thisMBB);
6242     
6243   // Update thisMBB to fall through to newMBB
6244   thisMBB->addSuccessor(newMBB);
6245   
6246   // newMBB jumps to itself and fall through to nextMBB
6247   newMBB->addSuccessor(nextMBB);
6248   newMBB->addSuccessor(newMBB);
6249   
6250   // Insert instructions into newMBB based on incoming instruction
6251   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6252   MachineOperand& destOper = bInstr->getOperand(0);
6253   MachineOperand* argOpers[6];
6254   int numArgs = bInstr->getNumOperands() - 1;
6255   for (int i=0; i < numArgs; ++i)
6256     argOpers[i] = &bInstr->getOperand(i+1);
6257
6258   // x86 address has 4 operands: base, index, scale, and displacement
6259   int lastAddrIndx = 3; // [0,3]
6260   int valArgIndx = 4;
6261   
6262   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6263   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6264   for (int i=0; i <= lastAddrIndx; ++i)
6265     (*MIB).addOperand(*argOpers[i]);
6266
6267   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6268   if (invSrc) {
6269     MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6270   }
6271   else 
6272     tt = t1;
6273
6274   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6275   assert((argOpers[valArgIndx]->isRegister() ||
6276           argOpers[valArgIndx]->isImmediate()) &&
6277          "invalid operand");
6278   if (argOpers[valArgIndx]->isRegister())
6279     MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6280   else
6281     MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6282   MIB.addReg(tt);
6283   (*MIB).addOperand(*argOpers[valArgIndx]);
6284
6285   MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6286   MIB.addReg(t1);
6287   
6288   MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6289   for (int i=0; i <= lastAddrIndx; ++i)
6290     (*MIB).addOperand(*argOpers[i]);
6291   MIB.addReg(t2);
6292   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6293   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6294
6295   MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6296   MIB.addReg(EAXreg);
6297   
6298   // insert branch
6299   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6300
6301   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
6302   return nextMBB;
6303 }
6304
6305 // private utility function
6306 MachineBasicBlock *
6307 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6308                                                       MachineBasicBlock *MBB,
6309                                                       unsigned cmovOpc) {
6310   // For the atomic min/max operator, we generate
6311   //   thisMBB:
6312   //   newMBB:
6313   //     ld t1 = [min/max.addr]
6314   //     mov t2 = [min/max.val] 
6315   //     cmp  t1, t2
6316   //     cmov[cond] t2 = t1
6317   //     mov EAX = t1
6318   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6319   //     bz   newMBB
6320   //     fallthrough -->nextMBB
6321   //
6322   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6323   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6324   MachineFunction::iterator MBBIter = MBB;
6325   ++MBBIter;
6326   
6327   /// First build the CFG
6328   MachineFunction *F = MBB->getParent();
6329   MachineBasicBlock *thisMBB = MBB;
6330   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6331   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6332   F->insert(MBBIter, newMBB);
6333   F->insert(MBBIter, nextMBB);
6334   
6335   // Move all successors to thisMBB to nextMBB
6336   nextMBB->transferSuccessors(thisMBB);
6337   
6338   // Update thisMBB to fall through to newMBB
6339   thisMBB->addSuccessor(newMBB);
6340   
6341   // newMBB jumps to newMBB and fall through to nextMBB
6342   newMBB->addSuccessor(nextMBB);
6343   newMBB->addSuccessor(newMBB);
6344   
6345   // Insert instructions into newMBB based on incoming instruction
6346   assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6347   MachineOperand& destOper = mInstr->getOperand(0);
6348   MachineOperand* argOpers[6];
6349   int numArgs = mInstr->getNumOperands() - 1;
6350   for (int i=0; i < numArgs; ++i)
6351     argOpers[i] = &mInstr->getOperand(i+1);
6352   
6353   // x86 address has 4 operands: base, index, scale, and displacement
6354   int lastAddrIndx = 3; // [0,3]
6355   int valArgIndx = 4;
6356   
6357   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6358   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6359   for (int i=0; i <= lastAddrIndx; ++i)
6360     (*MIB).addOperand(*argOpers[i]);
6361
6362   // We only support register and immediate values
6363   assert((argOpers[valArgIndx]->isRegister() ||
6364           argOpers[valArgIndx]->isImmediate()) &&
6365          "invalid operand");
6366   
6367   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
6368   if (argOpers[valArgIndx]->isRegister())
6369     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6370   else 
6371     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6372   (*MIB).addOperand(*argOpers[valArgIndx]);
6373
6374   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6375   MIB.addReg(t1);
6376
6377   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6378   MIB.addReg(t1);
6379   MIB.addReg(t2);
6380
6381   // Generate movc
6382   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6383   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6384   MIB.addReg(t2);
6385   MIB.addReg(t1);
6386
6387   // Cmp and exchange if none has modified the memory location
6388   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6389   for (int i=0; i <= lastAddrIndx; ++i)
6390     (*MIB).addOperand(*argOpers[i]);
6391   MIB.addReg(t3);
6392   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6393   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6394   
6395   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6396   MIB.addReg(X86::EAX);
6397   
6398   // insert branch
6399   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6400
6401   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
6402   return nextMBB;
6403 }
6404
6405
6406 MachineBasicBlock *
6407 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6408                                                MachineBasicBlock *BB) {
6409   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6410   switch (MI->getOpcode()) {
6411   default: assert(false && "Unexpected instr type to insert");
6412   case X86::CMOV_FR32:
6413   case X86::CMOV_FR64:
6414   case X86::CMOV_V4F32:
6415   case X86::CMOV_V2F64:
6416   case X86::CMOV_V2I64: {
6417     // To "insert" a SELECT_CC instruction, we actually have to insert the
6418     // diamond control-flow pattern.  The incoming instruction knows the
6419     // destination vreg to set, the condition code register to branch on, the
6420     // true/false values to select between, and a branch opcode to use.
6421     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6422     MachineFunction::iterator It = BB;
6423     ++It;
6424
6425     //  thisMBB:
6426     //  ...
6427     //   TrueVal = ...
6428     //   cmpTY ccX, r1, r2
6429     //   bCC copy1MBB
6430     //   fallthrough --> copy0MBB
6431     MachineBasicBlock *thisMBB = BB;
6432     MachineFunction *F = BB->getParent();
6433     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6434     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6435     unsigned Opc =
6436       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6437     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6438     F->insert(It, copy0MBB);
6439     F->insert(It, sinkMBB);
6440     // Update machine-CFG edges by transferring all successors of the current
6441     // block to the new block which will contain the Phi node for the select.
6442     sinkMBB->transferSuccessors(BB);
6443
6444     // Add the true and fallthrough blocks as its successors.
6445     BB->addSuccessor(copy0MBB);
6446     BB->addSuccessor(sinkMBB);
6447
6448     //  copy0MBB:
6449     //   %FalseValue = ...
6450     //   # fallthrough to sinkMBB
6451     BB = copy0MBB;
6452
6453     // Update machine-CFG edges
6454     BB->addSuccessor(sinkMBB);
6455
6456     //  sinkMBB:
6457     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6458     //  ...
6459     BB = sinkMBB;
6460     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6461       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6462       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6463
6464     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6465     return BB;
6466   }
6467
6468   case X86::FP32_TO_INT16_IN_MEM:
6469   case X86::FP32_TO_INT32_IN_MEM:
6470   case X86::FP32_TO_INT64_IN_MEM:
6471   case X86::FP64_TO_INT16_IN_MEM:
6472   case X86::FP64_TO_INT32_IN_MEM:
6473   case X86::FP64_TO_INT64_IN_MEM:
6474   case X86::FP80_TO_INT16_IN_MEM:
6475   case X86::FP80_TO_INT32_IN_MEM:
6476   case X86::FP80_TO_INT64_IN_MEM: {
6477     // Change the floating point control register to use "round towards zero"
6478     // mode when truncating to an integer value.
6479     MachineFunction *F = BB->getParent();
6480     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6481     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6482
6483     // Load the old value of the high byte of the control word...
6484     unsigned OldCW =
6485       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6486     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6487
6488     // Set the high part to be round to zero...
6489     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6490       .addImm(0xC7F);
6491
6492     // Reload the modified control word now...
6493     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6494
6495     // Restore the memory image of control word to original value
6496     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6497       .addReg(OldCW);
6498
6499     // Get the X86 opcode to use.
6500     unsigned Opc;
6501     switch (MI->getOpcode()) {
6502     default: assert(0 && "illegal opcode!");
6503     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6504     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6505     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6506     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6507     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6508     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6509     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6510     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6511     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6512     }
6513
6514     X86AddressMode AM;
6515     MachineOperand &Op = MI->getOperand(0);
6516     if (Op.isRegister()) {
6517       AM.BaseType = X86AddressMode::RegBase;
6518       AM.Base.Reg = Op.getReg();
6519     } else {
6520       AM.BaseType = X86AddressMode::FrameIndexBase;
6521       AM.Base.FrameIndex = Op.getIndex();
6522     }
6523     Op = MI->getOperand(1);
6524     if (Op.isImmediate())
6525       AM.Scale = Op.getImm();
6526     Op = MI->getOperand(2);
6527     if (Op.isImmediate())
6528       AM.IndexReg = Op.getImm();
6529     Op = MI->getOperand(3);
6530     if (Op.isGlobalAddress()) {
6531       AM.GV = Op.getGlobal();
6532     } else {
6533       AM.Disp = Op.getImm();
6534     }
6535     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6536                       .addReg(MI->getOperand(4).getReg());
6537
6538     // Reload the original control word now.
6539     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6540
6541     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6542     return BB;
6543   }
6544   case X86::ATOMAND32:
6545     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6546                                                X86::AND32ri, X86::MOV32rm, 
6547                                                X86::LCMPXCHG32, X86::MOV32rr,
6548                                                X86::NOT32r, X86::EAX,
6549                                                X86::GR32RegisterClass);
6550   case X86::ATOMOR32:
6551     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
6552                                                X86::OR32ri, X86::MOV32rm, 
6553                                                X86::LCMPXCHG32, X86::MOV32rr,
6554                                                X86::NOT32r, X86::EAX,
6555                                                X86::GR32RegisterClass);
6556   case X86::ATOMXOR32:
6557     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6558                                                X86::XOR32ri, X86::MOV32rm, 
6559                                                X86::LCMPXCHG32, X86::MOV32rr,
6560                                                X86::NOT32r, X86::EAX,
6561                                                X86::GR32RegisterClass);
6562   case X86::ATOMNAND32:
6563     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6564                                                X86::AND32ri, X86::MOV32rm,
6565                                                X86::LCMPXCHG32, X86::MOV32rr,
6566                                                X86::NOT32r, X86::EAX,
6567                                                X86::GR32RegisterClass, true);
6568   case X86::ATOMMIN32:
6569     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6570   case X86::ATOMMAX32:
6571     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6572   case X86::ATOMUMIN32:
6573     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6574   case X86::ATOMUMAX32:
6575     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6576
6577   case X86::ATOMAND16:
6578     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6579                                                X86::AND16ri, X86::MOV16rm,
6580                                                X86::LCMPXCHG16, X86::MOV16rr,
6581                                                X86::NOT16r, X86::AX,
6582                                                X86::GR16RegisterClass);
6583   case X86::ATOMOR16:
6584     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 
6585                                                X86::OR16ri, X86::MOV16rm,
6586                                                X86::LCMPXCHG16, X86::MOV16rr,
6587                                                X86::NOT16r, X86::AX,
6588                                                X86::GR16RegisterClass);
6589   case X86::ATOMXOR16:
6590     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6591                                                X86::XOR16ri, X86::MOV16rm,
6592                                                X86::LCMPXCHG16, X86::MOV16rr,
6593                                                X86::NOT16r, X86::AX,
6594                                                X86::GR16RegisterClass);
6595   case X86::ATOMNAND16:
6596     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6597                                                X86::AND16ri, X86::MOV16rm,
6598                                                X86::LCMPXCHG16, X86::MOV16rr,
6599                                                X86::NOT16r, X86::AX,
6600                                                X86::GR16RegisterClass, true);
6601   case X86::ATOMMIN16:
6602     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6603   case X86::ATOMMAX16:
6604     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6605   case X86::ATOMUMIN16:
6606     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6607   case X86::ATOMUMAX16:
6608     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6609
6610   case X86::ATOMAND8:
6611     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6612                                                X86::AND8ri, X86::MOV8rm,
6613                                                X86::LCMPXCHG8, X86::MOV8rr,
6614                                                X86::NOT8r, X86::AL,
6615                                                X86::GR8RegisterClass);
6616   case X86::ATOMOR8:
6617     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 
6618                                                X86::OR8ri, X86::MOV8rm,
6619                                                X86::LCMPXCHG8, X86::MOV8rr,
6620                                                X86::NOT8r, X86::AL,
6621                                                X86::GR8RegisterClass);
6622   case X86::ATOMXOR8:
6623     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6624                                                X86::XOR8ri, X86::MOV8rm,
6625                                                X86::LCMPXCHG8, X86::MOV8rr,
6626                                                X86::NOT8r, X86::AL,
6627                                                X86::GR8RegisterClass);
6628   case X86::ATOMNAND8:
6629     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6630                                                X86::AND8ri, X86::MOV8rm,
6631                                                X86::LCMPXCHG8, X86::MOV8rr,
6632                                                X86::NOT8r, X86::AL,
6633                                                X86::GR8RegisterClass, true);
6634   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6635   case X86::ATOMAND64:
6636     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6637                                                X86::AND64ri32, X86::MOV64rm, 
6638                                                X86::LCMPXCHG64, X86::MOV64rr,
6639                                                X86::NOT64r, X86::RAX,
6640                                                X86::GR64RegisterClass);
6641   case X86::ATOMOR64:
6642     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 
6643                                                X86::OR64ri32, X86::MOV64rm, 
6644                                                X86::LCMPXCHG64, X86::MOV64rr,
6645                                                X86::NOT64r, X86::RAX,
6646                                                X86::GR64RegisterClass);
6647   case X86::ATOMXOR64:
6648     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
6649                                                X86::XOR64ri32, X86::MOV64rm, 
6650                                                X86::LCMPXCHG64, X86::MOV64rr,
6651                                                X86::NOT64r, X86::RAX,
6652                                                X86::GR64RegisterClass);
6653   case X86::ATOMNAND64:
6654     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6655                                                X86::AND64ri32, X86::MOV64rm,
6656                                                X86::LCMPXCHG64, X86::MOV64rr,
6657                                                X86::NOT64r, X86::RAX,
6658                                                X86::GR64RegisterClass, true);
6659   case X86::ATOMMIN64:
6660     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
6661   case X86::ATOMMAX64:
6662     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
6663   case X86::ATOMUMIN64:
6664     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
6665   case X86::ATOMUMAX64:
6666     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
6667   }
6668 }
6669
6670 //===----------------------------------------------------------------------===//
6671 //                           X86 Optimization Hooks
6672 //===----------------------------------------------------------------------===//
6673
6674 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6675                                                        const APInt &Mask,
6676                                                        APInt &KnownZero,
6677                                                        APInt &KnownOne,
6678                                                        const SelectionDAG &DAG,
6679                                                        unsigned Depth) const {
6680   unsigned Opc = Op.getOpcode();
6681   assert((Opc >= ISD::BUILTIN_OP_END ||
6682           Opc == ISD::INTRINSIC_WO_CHAIN ||
6683           Opc == ISD::INTRINSIC_W_CHAIN ||
6684           Opc == ISD::INTRINSIC_VOID) &&
6685          "Should use MaskedValueIsZero if you don't know whether Op"
6686          " is a target node!");
6687
6688   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
6689   switch (Opc) {
6690   default: break;
6691   case X86ISD::SETCC:
6692     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6693                                        Mask.getBitWidth() - 1);
6694     break;
6695   }
6696 }
6697
6698 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6699 /// node is a GlobalAddress + offset.
6700 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6701                                        GlobalValue* &GA, int64_t &Offset) const{
6702   if (N->getOpcode() == X86ISD::Wrapper) {
6703     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6704       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6705       return true;
6706     }
6707   }
6708   return TargetLowering::isGAPlusOffset(N, GA, Offset);
6709 }
6710
6711 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6712                                const TargetLowering &TLI) {
6713   GlobalValue *GV;
6714   int64_t Offset = 0;
6715   if (TLI.isGAPlusOffset(Base, GV, Offset))
6716     return (GV->getAlignment() >= N && (Offset % N) == 0);
6717   // DAG combine handles the stack object case.
6718   return false;
6719 }
6720
6721 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6722                                      unsigned NumElems, MVT EVT,
6723                                      SDNode *&Base,
6724                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
6725                                      const TargetLowering &TLI) {
6726   Base = NULL;
6727   for (unsigned i = 0; i < NumElems; ++i) {
6728     SDValue Idx = PermMask.getOperand(i);
6729     if (Idx.getOpcode() == ISD::UNDEF) {
6730       if (!Base)
6731         return false;
6732       continue;
6733     }
6734
6735     SDValue Elt = DAG.getShuffleScalarElt(N, i);
6736     if (!Elt.getNode() ||
6737         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6738       return false;
6739     if (!Base) {
6740       Base = Elt.getNode();
6741       if (Base->getOpcode() == ISD::UNDEF)
6742         return false;
6743       continue;
6744     }
6745     if (Elt.getOpcode() == ISD::UNDEF)
6746       continue;
6747
6748     if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
6749                                EVT.getSizeInBits()/8, i, MFI))
6750       return false;
6751   }
6752   return true;
6753 }
6754
6755 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6756 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6757 /// if the load addresses are consecutive, non-overlapping, and in the right
6758 /// order.
6759 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6760                                        const TargetLowering &TLI) {
6761   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6762   MVT VT = N->getValueType(0);
6763   MVT EVT = VT.getVectorElementType();
6764   SDValue PermMask = N->getOperand(2);
6765   unsigned NumElems = PermMask.getNumOperands();
6766   SDNode *Base = NULL;
6767   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6768                                 DAG, MFI, TLI))
6769     return SDValue();
6770
6771   LoadSDNode *LD = cast<LoadSDNode>(Base);
6772   if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
6773     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6774                        LD->getSrcValueOffset(), LD->isVolatile());
6775   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6776                      LD->getSrcValueOffset(), LD->isVolatile(),
6777                      LD->getAlignment());
6778 }
6779
6780 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6781 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6782                                            const X86Subtarget *Subtarget,
6783                                            const TargetLowering &TLI) {
6784   unsigned NumOps = N->getNumOperands();
6785
6786   // Ignore single operand BUILD_VECTOR.
6787   if (NumOps == 1)
6788     return SDValue();
6789
6790   MVT VT = N->getValueType(0);
6791   MVT EVT = VT.getVectorElementType();
6792   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6793     // We are looking for load i64 and zero extend. We want to transform
6794     // it before legalizer has a chance to expand it. Also look for i64
6795     // BUILD_PAIR bit casted to f64.
6796     return SDValue();
6797   // This must be an insertion into a zero vector.
6798   SDValue HighElt = N->getOperand(1);
6799   if (!isZeroNode(HighElt))
6800     return SDValue();
6801
6802   // Value must be a load.
6803   SDNode *Base = N->getOperand(0).getNode();
6804   if (!isa<LoadSDNode>(Base)) {
6805     if (Base->getOpcode() != ISD::BIT_CONVERT)
6806       return SDValue();
6807     Base = Base->getOperand(0).getNode();
6808     if (!isa<LoadSDNode>(Base))
6809       return SDValue();
6810   }
6811
6812   // Transform it into VZEXT_LOAD addr.
6813   LoadSDNode *LD = cast<LoadSDNode>(Base);
6814   
6815   // Load must not be an extload.
6816   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6817     return SDValue();
6818   
6819   return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6820 }                                           
6821
6822 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6823 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6824                                       const X86Subtarget *Subtarget) {
6825   SDValue Cond = N->getOperand(0);
6826
6827   // If we have SSE[12] support, try to form min/max nodes.
6828   if (Subtarget->hasSSE2() &&
6829       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6830     if (Cond.getOpcode() == ISD::SETCC) {
6831       // Get the LHS/RHS of the select.
6832       SDValue LHS = N->getOperand(1);
6833       SDValue RHS = N->getOperand(2);
6834       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6835
6836       unsigned Opcode = 0;
6837       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6838         switch (CC) {
6839         default: break;
6840         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6841         case ISD::SETULE:
6842         case ISD::SETLE:
6843           if (!UnsafeFPMath) break;
6844           // FALL THROUGH.
6845         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6846         case ISD::SETLT:
6847           Opcode = X86ISD::FMIN;
6848           break;
6849
6850         case ISD::SETOGT: // (X > Y) ? X : Y -> max
6851         case ISD::SETUGT:
6852         case ISD::SETGT:
6853           if (!UnsafeFPMath) break;
6854           // FALL THROUGH.
6855         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6856         case ISD::SETGE:
6857           Opcode = X86ISD::FMAX;
6858           break;
6859         }
6860       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6861         switch (CC) {
6862         default: break;
6863         case ISD::SETOGT: // (X > Y) ? Y : X -> min
6864         case ISD::SETUGT:
6865         case ISD::SETGT:
6866           if (!UnsafeFPMath) break;
6867           // FALL THROUGH.
6868         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6869         case ISD::SETGE:
6870           Opcode = X86ISD::FMIN;
6871           break;
6872
6873         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6874         case ISD::SETULE:
6875         case ISD::SETLE:
6876           if (!UnsafeFPMath) break;
6877           // FALL THROUGH.
6878         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6879         case ISD::SETLT:
6880           Opcode = X86ISD::FMAX;
6881           break;
6882         }
6883       }
6884
6885       if (Opcode)
6886         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6887     }
6888
6889   }
6890
6891   return SDValue();
6892 }
6893
6894 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6895 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6896                                      const X86Subtarget *Subtarget) {
6897   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6898   // the FP state in cases where an emms may be missing.
6899   // A preferable solution to the general problem is to figure out the right
6900   // places to insert EMMS.  This qualifies as a quick hack.
6901   StoreSDNode *St = cast<StoreSDNode>(N);
6902   if (St->getValue().getValueType().isVector() &&
6903       St->getValue().getValueType().getSizeInBits() == 64 &&
6904       isa<LoadSDNode>(St->getValue()) &&
6905       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6906       St->getChain().hasOneUse() && !St->isVolatile()) {
6907     SDNode* LdVal = St->getValue().getNode();
6908     LoadSDNode *Ld = 0;
6909     int TokenFactorIndex = -1;
6910     SmallVector<SDValue, 8> Ops;
6911     SDNode* ChainVal = St->getChain().getNode();
6912     // Must be a store of a load.  We currently handle two cases:  the load
6913     // is a direct child, and it's under an intervening TokenFactor.  It is
6914     // possible to dig deeper under nested TokenFactors.
6915     if (ChainVal == LdVal)
6916       Ld = cast<LoadSDNode>(St->getChain());
6917     else if (St->getValue().hasOneUse() &&
6918              ChainVal->getOpcode() == ISD::TokenFactor) {
6919       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6920         if (ChainVal->getOperand(i).getNode() == LdVal) {
6921           TokenFactorIndex = i;
6922           Ld = cast<LoadSDNode>(St->getValue());
6923         } else
6924           Ops.push_back(ChainVal->getOperand(i));
6925       }
6926     }
6927     if (Ld) {
6928       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6929       if (Subtarget->is64Bit()) {
6930         SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
6931                                       Ld->getBasePtr(), Ld->getSrcValue(), 
6932                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
6933                                       Ld->getAlignment());
6934         SDValue NewChain = NewLd.getValue(1);
6935         if (TokenFactorIndex != -1) {
6936           Ops.push_back(NewChain);
6937           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6938                                  Ops.size());
6939         }
6940         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6941                             St->getSrcValue(), St->getSrcValueOffset(),
6942                             St->isVolatile(), St->getAlignment());
6943       }
6944
6945       // Otherwise, lower to two 32-bit copies.
6946       SDValue LoAddr = Ld->getBasePtr();
6947       SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6948                                      DAG.getConstant(4, MVT::i32));
6949
6950       SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6951                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
6952                                    Ld->isVolatile(), Ld->getAlignment());
6953       SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6954                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6955                                    Ld->isVolatile(), 
6956                                    MinAlign(Ld->getAlignment(), 4));
6957
6958       SDValue NewChain = LoLd.getValue(1);
6959       if (TokenFactorIndex != -1) {
6960         Ops.push_back(LoLd);
6961         Ops.push_back(HiLd);
6962         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6963                                Ops.size());
6964       }
6965
6966       LoAddr = St->getBasePtr();
6967       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6968                            DAG.getConstant(4, MVT::i32));
6969
6970       SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6971                           St->getSrcValue(), St->getSrcValueOffset(),
6972                           St->isVolatile(), St->getAlignment());
6973       SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6974                                     St->getSrcValue(),
6975                                     St->getSrcValueOffset() + 4,
6976                                     St->isVolatile(), 
6977                                     MinAlign(St->getAlignment(), 4));
6978       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6979     }
6980   }
6981   return SDValue();
6982 }
6983
6984 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6985 /// X86ISD::FXOR nodes.
6986 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6987   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6988   // F[X]OR(0.0, x) -> x
6989   // F[X]OR(x, 0.0) -> x
6990   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6991     if (C->getValueAPF().isPosZero())
6992       return N->getOperand(1);
6993   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6994     if (C->getValueAPF().isPosZero())
6995       return N->getOperand(0);
6996   return SDValue();
6997 }
6998
6999 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7000 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7001   // FAND(0.0, x) -> 0.0
7002   // FAND(x, 0.0) -> 0.0
7003   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7004     if (C->getValueAPF().isPosZero())
7005       return N->getOperand(0);
7006   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7007     if (C->getValueAPF().isPosZero())
7008       return N->getOperand(1);
7009   return SDValue();
7010 }
7011
7012
7013 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7014                                                DAGCombinerInfo &DCI) const {
7015   SelectionDAG &DAG = DCI.DAG;
7016   switch (N->getOpcode()) {
7017   default: break;
7018   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7019   case ISD::BUILD_VECTOR:
7020     return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7021   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
7022   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
7023   case X86ISD::FXOR:
7024   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
7025   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
7026   }
7027
7028   return SDValue();
7029 }
7030
7031 //===----------------------------------------------------------------------===//
7032 //                           X86 Inline Assembly Support
7033 //===----------------------------------------------------------------------===//
7034
7035 /// getConstraintType - Given a constraint letter, return the type of
7036 /// constraint it is for this target.
7037 X86TargetLowering::ConstraintType
7038 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7039   if (Constraint.size() == 1) {
7040     switch (Constraint[0]) {
7041     case 'A':
7042     case 'f':
7043     case 'r':
7044     case 'R':
7045     case 'l':
7046     case 'q':
7047     case 'Q':
7048     case 'x':
7049     case 'y':
7050     case 'Y':
7051       return C_RegisterClass;
7052     default:
7053       break;
7054     }
7055   }
7056   return TargetLowering::getConstraintType(Constraint);
7057 }
7058
7059 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7060 /// with another that has more specific requirements based on the type of the
7061 /// corresponding operand.
7062 const char *X86TargetLowering::
7063 LowerXConstraint(MVT ConstraintVT) const {
7064   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7065   // 'f' like normal targets.
7066   if (ConstraintVT.isFloatingPoint()) {
7067     if (Subtarget->hasSSE2())
7068       return "Y";
7069     if (Subtarget->hasSSE1())
7070       return "x";
7071   }
7072   
7073   return TargetLowering::LowerXConstraint(ConstraintVT);
7074 }
7075
7076 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7077 /// vector.  If it is invalid, don't add anything to Ops.
7078 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7079                                                      char Constraint,
7080                                                      std::vector<SDValue>&Ops,
7081                                                      SelectionDAG &DAG) const {
7082   SDValue Result(0, 0);
7083   
7084   switch (Constraint) {
7085   default: break;
7086   case 'I':
7087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7088       if (C->getZExtValue() <= 31) {
7089         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7090         break;
7091       }
7092     }
7093     return;
7094   case 'N':
7095     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7096       if (C->getZExtValue() <= 255) {
7097         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7098         break;
7099       }
7100     }
7101     return;
7102   case 'i': {
7103     // Literal immediates are always ok.
7104     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7105       Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7106       break;
7107     }
7108
7109     // If we are in non-pic codegen mode, we allow the address of a global (with
7110     // an optional displacement) to be used with 'i'.
7111     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7112     int64_t Offset = 0;
7113     
7114     // Match either (GA) or (GA+C)
7115     if (GA) {
7116       Offset = GA->getOffset();
7117     } else if (Op.getOpcode() == ISD::ADD) {
7118       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7119       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7120       if (C && GA) {
7121         Offset = GA->getOffset()+C->getZExtValue();
7122       } else {
7123         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7124         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7125         if (C && GA)
7126           Offset = GA->getOffset()+C->getZExtValue();
7127         else
7128           C = 0, GA = 0;
7129       }
7130     }
7131     
7132     if (GA) {
7133       // If addressing this global requires a load (e.g. in PIC mode), we can't
7134       // match.
7135       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
7136                                          false))
7137         return;
7138
7139       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7140                                       Offset);
7141       Result = Op;
7142       break;
7143     }
7144
7145     // Otherwise, not valid for this mode.
7146     return;
7147   }
7148   }
7149   
7150   if (Result.getNode()) {
7151     Ops.push_back(Result);
7152     return;
7153   }
7154   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7155 }
7156
7157 std::vector<unsigned> X86TargetLowering::
7158 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7159                                   MVT VT) const {
7160   if (Constraint.size() == 1) {
7161     // FIXME: not handling fp-stack yet!
7162     switch (Constraint[0]) {      // GCC X86 Constraint Letters
7163     default: break;  // Unknown constraint letter
7164     case 'A':   // EAX/EDX
7165       if (VT == MVT::i32 || VT == MVT::i64)
7166         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7167       break;
7168     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
7169     case 'Q':   // Q_REGS
7170       if (VT == MVT::i32)
7171         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7172       else if (VT == MVT::i16)
7173         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7174       else if (VT == MVT::i8)
7175         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7176       else if (VT == MVT::i64)
7177         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7178       break;
7179     }
7180   }
7181
7182   return std::vector<unsigned>();
7183 }
7184
7185 std::pair<unsigned, const TargetRegisterClass*>
7186 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7187                                                 MVT VT) const {
7188   // First, see if this is a constraint that directly corresponds to an LLVM
7189   // register class.
7190   if (Constraint.size() == 1) {
7191     // GCC Constraint Letters
7192     switch (Constraint[0]) {
7193     default: break;
7194     case 'r':   // GENERAL_REGS
7195     case 'R':   // LEGACY_REGS
7196     case 'l':   // INDEX_REGS
7197       if (VT == MVT::i64 && Subtarget->is64Bit())
7198         return std::make_pair(0U, X86::GR64RegisterClass);
7199       if (VT == MVT::i32)
7200         return std::make_pair(0U, X86::GR32RegisterClass);
7201       else if (VT == MVT::i16)
7202         return std::make_pair(0U, X86::GR16RegisterClass);
7203       else if (VT == MVT::i8)
7204         return std::make_pair(0U, X86::GR8RegisterClass);
7205       break;
7206     case 'f':  // FP Stack registers.
7207       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7208       // value to the correct fpstack register class.
7209       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7210         return std::make_pair(0U, X86::RFP32RegisterClass);
7211       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7212         return std::make_pair(0U, X86::RFP64RegisterClass);
7213       return std::make_pair(0U, X86::RFP80RegisterClass);
7214     case 'y':   // MMX_REGS if MMX allowed.
7215       if (!Subtarget->hasMMX()) break;
7216       return std::make_pair(0U, X86::VR64RegisterClass);
7217       break;
7218     case 'Y':   // SSE_REGS if SSE2 allowed
7219       if (!Subtarget->hasSSE2()) break;
7220       // FALL THROUGH.
7221     case 'x':   // SSE_REGS if SSE1 allowed
7222       if (!Subtarget->hasSSE1()) break;
7223
7224       switch (VT.getSimpleVT()) {
7225       default: break;
7226       // Scalar SSE types.
7227       case MVT::f32:
7228       case MVT::i32:
7229         return std::make_pair(0U, X86::FR32RegisterClass);
7230       case MVT::f64:
7231       case MVT::i64:
7232         return std::make_pair(0U, X86::FR64RegisterClass);
7233       // Vector types.
7234       case MVT::v16i8:
7235       case MVT::v8i16:
7236       case MVT::v4i32:
7237       case MVT::v2i64:
7238       case MVT::v4f32:
7239       case MVT::v2f64:
7240         return std::make_pair(0U, X86::VR128RegisterClass);
7241       }
7242       break;
7243     }
7244   }
7245   
7246   // Use the default implementation in TargetLowering to convert the register
7247   // constraint into a member of a register class.
7248   std::pair<unsigned, const TargetRegisterClass*> Res;
7249   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7250
7251   // Not found as a standard register?
7252   if (Res.second == 0) {
7253     // GCC calls "st(0)" just plain "st".
7254     if (StringsEqualNoCase("{st}", Constraint)) {
7255       Res.first = X86::ST0;
7256       Res.second = X86::RFP80RegisterClass;
7257     }
7258
7259     return Res;
7260   }
7261
7262   // Otherwise, check to see if this is a register class of the wrong value
7263   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7264   // turn into {ax},{dx}.
7265   if (Res.second->hasType(VT))
7266     return Res;   // Correct type already, nothing to do.
7267
7268   // All of the single-register GCC register classes map their values onto
7269   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
7270   // really want an 8-bit or 32-bit register, map to the appropriate register
7271   // class and return the appropriate register.
7272   if (Res.second == X86::GR16RegisterClass) {
7273     if (VT == MVT::i8) {
7274       unsigned DestReg = 0;
7275       switch (Res.first) {
7276       default: break;
7277       case X86::AX: DestReg = X86::AL; break;
7278       case X86::DX: DestReg = X86::DL; break;
7279       case X86::CX: DestReg = X86::CL; break;
7280       case X86::BX: DestReg = X86::BL; break;
7281       }
7282       if (DestReg) {
7283         Res.first = DestReg;
7284         Res.second = Res.second = X86::GR8RegisterClass;
7285       }
7286     } else if (VT == MVT::i32) {
7287       unsigned DestReg = 0;
7288       switch (Res.first) {
7289       default: break;
7290       case X86::AX: DestReg = X86::EAX; break;
7291       case X86::DX: DestReg = X86::EDX; break;
7292       case X86::CX: DestReg = X86::ECX; break;
7293       case X86::BX: DestReg = X86::EBX; break;
7294       case X86::SI: DestReg = X86::ESI; break;
7295       case X86::DI: DestReg = X86::EDI; break;
7296       case X86::BP: DestReg = X86::EBP; break;
7297       case X86::SP: DestReg = X86::ESP; break;
7298       }
7299       if (DestReg) {
7300         Res.first = DestReg;
7301         Res.second = Res.second = X86::GR32RegisterClass;
7302       }
7303     } else if (VT == MVT::i64) {
7304       unsigned DestReg = 0;
7305       switch (Res.first) {
7306       default: break;
7307       case X86::AX: DestReg = X86::RAX; break;
7308       case X86::DX: DestReg = X86::RDX; break;
7309       case X86::CX: DestReg = X86::RCX; break;
7310       case X86::BX: DestReg = X86::RBX; break;
7311       case X86::SI: DestReg = X86::RSI; break;
7312       case X86::DI: DestReg = X86::RDI; break;
7313       case X86::BP: DestReg = X86::RBP; break;
7314       case X86::SP: DestReg = X86::RSP; break;
7315       }
7316       if (DestReg) {
7317         Res.first = DestReg;
7318         Res.second = Res.second = X86::GR64RegisterClass;
7319       }
7320     }
7321   } else if (Res.second == X86::FR32RegisterClass ||
7322              Res.second == X86::FR64RegisterClass ||
7323              Res.second == X86::VR128RegisterClass) {
7324     // Handle references to XMM physical registers that got mapped into the
7325     // wrong class.  This can happen with constraints like {xmm0} where the
7326     // target independent register mapper will just pick the first match it can
7327     // find, ignoring the required type.
7328     if (VT == MVT::f32)
7329       Res.second = X86::FR32RegisterClass;
7330     else if (VT == MVT::f64)
7331       Res.second = X86::FR64RegisterClass;
7332     else if (X86::VR128RegisterClass->hasType(VT))
7333       Res.second = X86::VR128RegisterClass;
7334   }
7335
7336   return Res;
7337 }