Define CallSDNode, an SDNode subclass for use with ISD::CALL.
[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::ExternalSymbol  , 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::ExternalSymbol, 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::TargetExternalSymbol ||
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<ExternalSymbolSDNode>(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 (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1701     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1702   } else if (IsTailCall) {
1703     unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1704
1705     Chain = DAG.getCopyToReg(Chain, 
1706                              DAG.getRegister(Opc, getPointerTy()), 
1707                              Callee,InFlag);
1708     Callee = DAG.getRegister(Opc, getPointerTy());
1709     // Add register as live out.
1710     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1711   }
1712  
1713   // Returns a chain & a flag for retval copy to use.
1714   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1715   SmallVector<SDValue, 8> Ops;
1716
1717   if (IsTailCall) {
1718     Ops.push_back(Chain);
1719     Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1720     Ops.push_back(DAG.getIntPtrConstant(0));
1721     if (InFlag.getNode())
1722       Ops.push_back(InFlag);
1723     Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1724     InFlag = Chain.getValue(1);
1725  
1726     // Returns a chain & a flag for retval copy to use.
1727     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1728     Ops.clear();
1729   }
1730   
1731   Ops.push_back(Chain);
1732   Ops.push_back(Callee);
1733
1734   if (IsTailCall)
1735     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1736
1737   // Add argument registers to the end of the list so that they are known live
1738   // into the call.
1739   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1740     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1741                                   RegsToPass[i].second.getValueType()));
1742   
1743   // Add an implicit use GOT pointer in EBX.
1744   if (!IsTailCall && !Is64Bit &&
1745       getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1746       Subtarget->isPICStyleGOT())
1747     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1748
1749   // Add an implicit use of AL for x86 vararg functions.
1750   if (Is64Bit && isVarArg)
1751     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1752
1753   if (InFlag.getNode())
1754     Ops.push_back(InFlag);
1755
1756   if (IsTailCall) {
1757     assert(InFlag.getNode() && 
1758            "Flag must be set. Depend on flag being set in LowerRET");
1759     Chain = DAG.getNode(X86ISD::TAILCALL,
1760                         TheCall->getVTList(), &Ops[0], Ops.size());
1761       
1762     return SDValue(Chain.getNode(), Op.getResNo());
1763   }
1764
1765   Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1766   InFlag = Chain.getValue(1);
1767
1768   // Create the CALLSEQ_END node.
1769   unsigned NumBytesForCalleeToPush;
1770   if (IsCalleePop(isVarArg, CC))
1771     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
1772   else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1773     // If this is is a call to a struct-return function, the callee
1774     // pops the hidden struct pointer, so we have to push it back.
1775     // This is common for Darwin/X86, Linux & Mingw32 targets.
1776     NumBytesForCalleeToPush = 4;
1777   else
1778     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
1779   
1780   // Returns a flag for retval copy to use.
1781   Chain = DAG.getCALLSEQ_END(Chain,
1782                              DAG.getIntPtrConstant(NumBytes),
1783                              DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1784                              InFlag);
1785   InFlag = Chain.getValue(1);
1786
1787   // Handle result values, copying them out of physregs into vregs that we
1788   // return.
1789   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1790                  Op.getResNo());
1791 }
1792
1793
1794 //===----------------------------------------------------------------------===//
1795 //                Fast Calling Convention (tail call) implementation
1796 //===----------------------------------------------------------------------===//
1797
1798 //  Like std call, callee cleans arguments, convention except that ECX is
1799 //  reserved for storing the tail called function address. Only 2 registers are
1800 //  free for argument passing (inreg). Tail call optimization is performed
1801 //  provided:
1802 //                * tailcallopt is enabled
1803 //                * caller/callee are fastcc
1804 //  On X86_64 architecture with GOT-style position independent code only local
1805 //  (within module) calls are supported at the moment.
1806 //  To keep the stack aligned according to platform abi the function
1807 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
1808 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1809 //  If a tail called function callee has more arguments than the caller the
1810 //  caller needs to make sure that there is room to move the RETADDR to. This is
1811 //  achieved by reserving an area the size of the argument delta right after the
1812 //  original REtADDR, but before the saved framepointer or the spilled registers
1813 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1814 //  stack layout:
1815 //    arg1
1816 //    arg2
1817 //    RETADDR
1818 //    [ new RETADDR 
1819 //      move area ]
1820 //    (possible EBP)
1821 //    ESI
1822 //    EDI
1823 //    local1 ..
1824
1825 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1826 /// for a 16 byte align requirement.
1827 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize, 
1828                                                         SelectionDAG& DAG) {
1829   MachineFunction &MF = DAG.getMachineFunction();
1830   const TargetMachine &TM = MF.getTarget();
1831   const TargetFrameInfo &TFI = *TM.getFrameInfo();
1832   unsigned StackAlignment = TFI.getStackAlignment();
1833   uint64_t AlignMask = StackAlignment - 1; 
1834   int64_t Offset = StackSize;
1835   uint64_t SlotSize = TD->getPointerSize();
1836   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1837     // Number smaller than 12 so just add the difference.
1838     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1839   } else {
1840     // Mask out lower bits, add stackalignment once plus the 12 bytes.
1841     Offset = ((~AlignMask) & Offset) + StackAlignment + 
1842       (StackAlignment-SlotSize);
1843   }
1844   return Offset;
1845 }
1846
1847 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1848 /// following the call is a return. A function is eligible if caller/callee
1849 /// calling conventions match, currently only fastcc supports tail calls, and
1850 /// the function CALL is immediatly followed by a RET.
1851 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1852                                                       SDValue Ret,
1853                                                       SelectionDAG& DAG) const {
1854   if (!PerformTailCallOpt)
1855     return false;
1856
1857   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1858     MachineFunction &MF = DAG.getMachineFunction();
1859     unsigned CallerCC = MF.getFunction()->getCallingConv();
1860     unsigned CalleeCC= TheCall->getCallingConv();
1861     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1862       SDValue Callee = TheCall->getCallee();
1863       // On x86/32Bit PIC/GOT  tail calls are supported.
1864       if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1865           !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1866         return true;
1867
1868       // Can only do local tail calls (in same module, hidden or protected) on
1869       // x86_64 PIC/GOT at the moment.
1870       if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1871         return G->getGlobal()->hasHiddenVisibility()
1872             || G->getGlobal()->hasProtectedVisibility();
1873     }
1874   }
1875
1876   return false;
1877 }
1878
1879 FastISel *
1880 X86TargetLowering::createFastISel(MachineFunction &mf,
1881                                   DenseMap<const Value *, unsigned> &vm,
1882                                   DenseMap<const BasicBlock *,
1883                                            MachineBasicBlock *> &bm,
1884                                   DenseMap<const AllocaInst *, int> &am) {
1885                                          
1886   return X86::createFastISel(mf, vm, bm, am);
1887 }
1888
1889
1890 //===----------------------------------------------------------------------===//
1891 //                           Other Lowering Hooks
1892 //===----------------------------------------------------------------------===//
1893
1894
1895 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1896   MachineFunction &MF = DAG.getMachineFunction();
1897   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1898   int ReturnAddrIndex = FuncInfo->getRAIndex();
1899   uint64_t SlotSize = TD->getPointerSize();
1900
1901   if (ReturnAddrIndex == 0) {
1902     // Set up a frame object for the return address.
1903     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1904     FuncInfo->setRAIndex(ReturnAddrIndex);
1905   }
1906
1907   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1908 }
1909
1910
1911 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1912 /// specific condition code. It returns a false if it cannot do a direct
1913 /// translation. X86CC is the translated CondCode.  LHS/RHS are modified as
1914 /// needed.
1915 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1916                            unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1917                            SelectionDAG &DAG) {
1918   X86CC = X86::COND_INVALID;
1919   if (!isFP) {
1920     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1921       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1922         // X > -1   -> X == 0, jump !sign.
1923         RHS = DAG.getConstant(0, RHS.getValueType());
1924         X86CC = X86::COND_NS;
1925         return true;
1926       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1927         // X < 0   -> X == 0, jump on sign.
1928         X86CC = X86::COND_S;
1929         return true;
1930       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1931         // X < 1   -> X <= 0
1932         RHS = DAG.getConstant(0, RHS.getValueType());
1933         X86CC = X86::COND_LE;
1934         return true;
1935       }
1936     }
1937
1938     switch (SetCCOpcode) {
1939     default: break;
1940     case ISD::SETEQ:  X86CC = X86::COND_E;  break;
1941     case ISD::SETGT:  X86CC = X86::COND_G;  break;
1942     case ISD::SETGE:  X86CC = X86::COND_GE; break;
1943     case ISD::SETLT:  X86CC = X86::COND_L;  break;
1944     case ISD::SETLE:  X86CC = X86::COND_LE; break;
1945     case ISD::SETNE:  X86CC = X86::COND_NE; break;
1946     case ISD::SETULT: X86CC = X86::COND_B;  break;
1947     case ISD::SETUGT: X86CC = X86::COND_A;  break;
1948     case ISD::SETULE: X86CC = X86::COND_BE; break;
1949     case ISD::SETUGE: X86CC = X86::COND_AE; break;
1950     }
1951   } else {
1952     // First determine if it requires or is profitable to flip the operands.
1953     bool Flip = false;
1954     switch (SetCCOpcode) {
1955     default: break;
1956     case ISD::SETOLT:
1957     case ISD::SETOLE:
1958     case ISD::SETUGT:
1959     case ISD::SETUGE:
1960       Flip = true;
1961       break;
1962     }
1963
1964     // If LHS is a foldable load, but RHS is not, flip the condition.
1965     if (!Flip &&
1966         (ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1967         !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1968       SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1969       Flip = true;
1970     }
1971     if (Flip)
1972       std::swap(LHS, RHS);
1973
1974     // On a floating point condition, the flags are set as follows:
1975     // ZF  PF  CF   op
1976     //  0 | 0 | 0 | X > Y
1977     //  0 | 0 | 1 | X < Y
1978     //  1 | 0 | 0 | X == Y
1979     //  1 | 1 | 1 | unordered
1980     switch (SetCCOpcode) {
1981     default: break;
1982     case ISD::SETUEQ:
1983     case ISD::SETEQ:
1984       X86CC = X86::COND_E;
1985       break;
1986     case ISD::SETOLT:              // flipped
1987     case ISD::SETOGT:
1988     case ISD::SETGT:
1989       X86CC = X86::COND_A;
1990       break;
1991     case ISD::SETOLE:              // flipped
1992     case ISD::SETOGE:
1993     case ISD::SETGE:
1994       X86CC = X86::COND_AE;
1995       break;
1996     case ISD::SETUGT:              // flipped
1997     case ISD::SETULT:
1998     case ISD::SETLT:
1999       X86CC = X86::COND_B;
2000       break;
2001     case ISD::SETUGE:              // flipped
2002     case ISD::SETULE:
2003     case ISD::SETLE:
2004       X86CC = X86::COND_BE;
2005       break;
2006     case ISD::SETONE:
2007     case ISD::SETNE:
2008       X86CC = X86::COND_NE;
2009       break;
2010     case ISD::SETUO:
2011       X86CC = X86::COND_P;
2012       break;
2013     case ISD::SETO:
2014       X86CC = X86::COND_NP;
2015       break;
2016     }
2017   }
2018
2019   return X86CC != X86::COND_INVALID;
2020 }
2021
2022 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2023 /// code. Current x86 isa includes the following FP cmov instructions:
2024 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2025 static bool hasFPCMov(unsigned X86CC) {
2026   switch (X86CC) {
2027   default:
2028     return false;
2029   case X86::COND_B:
2030   case X86::COND_BE:
2031   case X86::COND_E:
2032   case X86::COND_P:
2033   case X86::COND_A:
2034   case X86::COND_AE:
2035   case X86::COND_NE:
2036   case X86::COND_NP:
2037     return true;
2038   }
2039 }
2040
2041 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
2042 /// true if Op is undef or if its value falls within the specified range (L, H].
2043 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2044   if (Op.getOpcode() == ISD::UNDEF)
2045     return true;
2046
2047   unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2048   return (Val >= Low && Val < Hi);
2049 }
2050
2051 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
2052 /// true if Op is undef or if its value equal to the specified value.
2053 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2054   if (Op.getOpcode() == ISD::UNDEF)
2055     return true;
2056   return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2057 }
2058
2059 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2060 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2061 bool X86::isPSHUFDMask(SDNode *N) {
2062   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2063
2064   if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2065     return false;
2066
2067   // Check if the value doesn't reference the second vector.
2068   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2069     SDValue Arg = N->getOperand(i);
2070     if (Arg.getOpcode() == ISD::UNDEF) continue;
2071     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2072     if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2073       return false;
2074   }
2075
2076   return true;
2077 }
2078
2079 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2080 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2081 bool X86::isPSHUFHWMask(SDNode *N) {
2082   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2083
2084   if (N->getNumOperands() != 8)
2085     return false;
2086
2087   // Lower quadword copied in order.
2088   for (unsigned i = 0; i != 4; ++i) {
2089     SDValue Arg = N->getOperand(i);
2090     if (Arg.getOpcode() == ISD::UNDEF) continue;
2091     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2092     if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2093       return false;
2094   }
2095
2096   // Upper quadword shuffled.
2097   for (unsigned i = 4; i != 8; ++i) {
2098     SDValue Arg = N->getOperand(i);
2099     if (Arg.getOpcode() == ISD::UNDEF) continue;
2100     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2101     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2102     if (Val < 4 || Val > 7)
2103       return false;
2104   }
2105
2106   return true;
2107 }
2108
2109 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2110 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2111 bool X86::isPSHUFLWMask(SDNode *N) {
2112   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2113
2114   if (N->getNumOperands() != 8)
2115     return false;
2116
2117   // Upper quadword copied in order.
2118   for (unsigned i = 4; i != 8; ++i)
2119     if (!isUndefOrEqual(N->getOperand(i), i))
2120       return false;
2121
2122   // Lower quadword shuffled.
2123   for (unsigned i = 0; i != 4; ++i)
2124     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2125       return false;
2126
2127   return true;
2128 }
2129
2130 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2131 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2132 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2133   if (NumElems != 2 && NumElems != 4) return false;
2134
2135   unsigned Half = NumElems / 2;
2136   for (unsigned i = 0; i < Half; ++i)
2137     if (!isUndefOrInRange(Elems[i], 0, NumElems))
2138       return false;
2139   for (unsigned i = Half; i < NumElems; ++i)
2140     if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2141       return false;
2142
2143   return true;
2144 }
2145
2146 bool X86::isSHUFPMask(SDNode *N) {
2147   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2148   return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2149 }
2150
2151 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2152 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2153 /// half elements to come from vector 1 (which would equal the dest.) and
2154 /// the upper half to come from vector 2.
2155 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2156   if (NumOps != 2 && NumOps != 4) return false;
2157
2158   unsigned Half = NumOps / 2;
2159   for (unsigned i = 0; i < Half; ++i)
2160     if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2161       return false;
2162   for (unsigned i = Half; i < NumOps; ++i)
2163     if (!isUndefOrInRange(Ops[i], 0, NumOps))
2164       return false;
2165   return true;
2166 }
2167
2168 static bool isCommutedSHUFP(SDNode *N) {
2169   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2170   return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2171 }
2172
2173 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2174 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2175 bool X86::isMOVHLPSMask(SDNode *N) {
2176   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2177
2178   if (N->getNumOperands() != 4)
2179     return false;
2180
2181   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2182   return isUndefOrEqual(N->getOperand(0), 6) &&
2183          isUndefOrEqual(N->getOperand(1), 7) &&
2184          isUndefOrEqual(N->getOperand(2), 2) &&
2185          isUndefOrEqual(N->getOperand(3), 3);
2186 }
2187
2188 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2189 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2190 /// <2, 3, 2, 3>
2191 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2192   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2193
2194   if (N->getNumOperands() != 4)
2195     return false;
2196
2197   // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2198   return isUndefOrEqual(N->getOperand(0), 2) &&
2199          isUndefOrEqual(N->getOperand(1), 3) &&
2200          isUndefOrEqual(N->getOperand(2), 2) &&
2201          isUndefOrEqual(N->getOperand(3), 3);
2202 }
2203
2204 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2205 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2206 bool X86::isMOVLPMask(SDNode *N) {
2207   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2208
2209   unsigned NumElems = N->getNumOperands();
2210   if (NumElems != 2 && NumElems != 4)
2211     return false;
2212
2213   for (unsigned i = 0; i < NumElems/2; ++i)
2214     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2215       return false;
2216
2217   for (unsigned i = NumElems/2; i < NumElems; ++i)
2218     if (!isUndefOrEqual(N->getOperand(i), i))
2219       return false;
2220
2221   return true;
2222 }
2223
2224 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2225 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2226 /// and MOVLHPS.
2227 bool X86::isMOVHPMask(SDNode *N) {
2228   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2229
2230   unsigned NumElems = N->getNumOperands();
2231   if (NumElems != 2 && NumElems != 4)
2232     return false;
2233
2234   for (unsigned i = 0; i < NumElems/2; ++i)
2235     if (!isUndefOrEqual(N->getOperand(i), i))
2236       return false;
2237
2238   for (unsigned i = 0; i < NumElems/2; ++i) {
2239     SDValue Arg = N->getOperand(i + NumElems/2);
2240     if (!isUndefOrEqual(Arg, i + NumElems))
2241       return false;
2242   }
2243
2244   return true;
2245 }
2246
2247 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2248 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2249 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2250                          bool V2IsSplat = false) {
2251   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2252     return false;
2253
2254   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2255     SDValue BitI  = Elts[i];
2256     SDValue BitI1 = Elts[i+1];
2257     if (!isUndefOrEqual(BitI, j))
2258       return false;
2259     if (V2IsSplat) {
2260       if (isUndefOrEqual(BitI1, NumElts))
2261         return false;
2262     } else {
2263       if (!isUndefOrEqual(BitI1, j + NumElts))
2264         return false;
2265     }
2266   }
2267
2268   return true;
2269 }
2270
2271 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2272   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2273   return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2274 }
2275
2276 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2277 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2278 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2279                          bool V2IsSplat = false) {
2280   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2281     return false;
2282
2283   for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2284     SDValue BitI  = Elts[i];
2285     SDValue BitI1 = Elts[i+1];
2286     if (!isUndefOrEqual(BitI, j + NumElts/2))
2287       return false;
2288     if (V2IsSplat) {
2289       if (isUndefOrEqual(BitI1, NumElts))
2290         return false;
2291     } else {
2292       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2293         return false;
2294     }
2295   }
2296
2297   return true;
2298 }
2299
2300 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2301   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2302   return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2303 }
2304
2305 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2306 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2307 /// <0, 0, 1, 1>
2308 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2309   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2310
2311   unsigned NumElems = N->getNumOperands();
2312   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2313     return false;
2314
2315   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2316     SDValue BitI  = N->getOperand(i);
2317     SDValue BitI1 = N->getOperand(i+1);
2318
2319     if (!isUndefOrEqual(BitI, j))
2320       return false;
2321     if (!isUndefOrEqual(BitI1, j))
2322       return false;
2323   }
2324
2325   return true;
2326 }
2327
2328 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2329 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2330 /// <2, 2, 3, 3>
2331 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2332   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333
2334   unsigned NumElems = N->getNumOperands();
2335   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2336     return false;
2337
2338   for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2339     SDValue BitI  = N->getOperand(i);
2340     SDValue BitI1 = N->getOperand(i + 1);
2341
2342     if (!isUndefOrEqual(BitI, j))
2343       return false;
2344     if (!isUndefOrEqual(BitI1, j))
2345       return false;
2346   }
2347
2348   return true;
2349 }
2350
2351 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2352 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2353 /// MOVSD, and MOVD, i.e. setting the lowest element.
2354 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2355   if (NumElts != 2 && NumElts != 4)
2356     return false;
2357
2358   if (!isUndefOrEqual(Elts[0], NumElts))
2359     return false;
2360
2361   for (unsigned i = 1; i < NumElts; ++i) {
2362     if (!isUndefOrEqual(Elts[i], i))
2363       return false;
2364   }
2365
2366   return true;
2367 }
2368
2369 bool X86::isMOVLMask(SDNode *N) {
2370   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2371   return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2372 }
2373
2374 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2375 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2376 /// element of vector 2 and the other elements to come from vector 1 in order.
2377 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2378                            bool V2IsSplat = false,
2379                            bool V2IsUndef = false) {
2380   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2381     return false;
2382
2383   if (!isUndefOrEqual(Ops[0], 0))
2384     return false;
2385
2386   for (unsigned i = 1; i < NumOps; ++i) {
2387     SDValue Arg = Ops[i];
2388     if (!(isUndefOrEqual(Arg, i+NumOps) ||
2389           (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2390           (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2391       return false;
2392   }
2393
2394   return true;
2395 }
2396
2397 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2398                            bool V2IsUndef = false) {
2399   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2400   return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2401                         V2IsSplat, V2IsUndef);
2402 }
2403
2404 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2405 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2406 bool X86::isMOVSHDUPMask(SDNode *N) {
2407   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2408
2409   if (N->getNumOperands() != 4)
2410     return false;
2411
2412   // Expect 1, 1, 3, 3
2413   for (unsigned i = 0; i < 2; ++i) {
2414     SDValue Arg = N->getOperand(i);
2415     if (Arg.getOpcode() == ISD::UNDEF) continue;
2416     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2417     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2418     if (Val != 1) return false;
2419   }
2420
2421   bool HasHi = false;
2422   for (unsigned i = 2; i < 4; ++i) {
2423     SDValue Arg = N->getOperand(i);
2424     if (Arg.getOpcode() == ISD::UNDEF) continue;
2425     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2426     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2427     if (Val != 3) return false;
2428     HasHi = true;
2429   }
2430
2431   // Don't use movshdup if it can be done with a shufps.
2432   return HasHi;
2433 }
2434
2435 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2436 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2437 bool X86::isMOVSLDUPMask(SDNode *N) {
2438   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2439
2440   if (N->getNumOperands() != 4)
2441     return false;
2442
2443   // Expect 0, 0, 2, 2
2444   for (unsigned i = 0; i < 2; ++i) {
2445     SDValue Arg = N->getOperand(i);
2446     if (Arg.getOpcode() == ISD::UNDEF) continue;
2447     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2448     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2449     if (Val != 0) return false;
2450   }
2451
2452   bool HasHi = false;
2453   for (unsigned i = 2; i < 4; ++i) {
2454     SDValue Arg = N->getOperand(i);
2455     if (Arg.getOpcode() == ISD::UNDEF) continue;
2456     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2457     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2458     if (Val != 2) return false;
2459     HasHi = true;
2460   }
2461
2462   // Don't use movshdup if it can be done with a shufps.
2463   return HasHi;
2464 }
2465
2466 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2467 /// specifies a identity operation on the LHS or RHS.
2468 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2469   unsigned NumElems = N->getNumOperands();
2470   for (unsigned i = 0; i < NumElems; ++i)
2471     if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2472       return false;
2473   return true;
2474 }
2475
2476 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2477 /// a splat of a single element.
2478 static bool isSplatMask(SDNode *N) {
2479   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2480
2481   // This is a splat operation if each element of the permute is the same, and
2482   // if the value doesn't reference the second vector.
2483   unsigned NumElems = N->getNumOperands();
2484   SDValue ElementBase;
2485   unsigned i = 0;
2486   for (; i != NumElems; ++i) {
2487     SDValue Elt = N->getOperand(i);
2488     if (isa<ConstantSDNode>(Elt)) {
2489       ElementBase = Elt;
2490       break;
2491     }
2492   }
2493
2494   if (!ElementBase.getNode())
2495     return false;
2496
2497   for (; i != NumElems; ++i) {
2498     SDValue Arg = N->getOperand(i);
2499     if (Arg.getOpcode() == ISD::UNDEF) continue;
2500     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2501     if (Arg != ElementBase) return false;
2502   }
2503
2504   // Make sure it is a splat of the first vector operand.
2505   return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2506 }
2507
2508 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2509 /// a splat of a single element and it's a 2 or 4 element mask.
2510 bool X86::isSplatMask(SDNode *N) {
2511   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2512
2513   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2514   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2515     return false;
2516   return ::isSplatMask(N);
2517 }
2518
2519 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2520 /// specifies a splat of zero element.
2521 bool X86::isSplatLoMask(SDNode *N) {
2522   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2523
2524   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2525     if (!isUndefOrEqual(N->getOperand(i), 0))
2526       return false;
2527   return true;
2528 }
2529
2530 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2531 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2532 /// instructions.
2533 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2534   unsigned NumOperands = N->getNumOperands();
2535   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2536   unsigned Mask = 0;
2537   for (unsigned i = 0; i < NumOperands; ++i) {
2538     unsigned Val = 0;
2539     SDValue Arg = N->getOperand(NumOperands-i-1);
2540     if (Arg.getOpcode() != ISD::UNDEF)
2541       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2542     if (Val >= NumOperands) Val -= NumOperands;
2543     Mask |= Val;
2544     if (i != NumOperands - 1)
2545       Mask <<= Shift;
2546   }
2547
2548   return Mask;
2549 }
2550
2551 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2552 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2553 /// instructions.
2554 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2555   unsigned Mask = 0;
2556   // 8 nodes, but we only care about the last 4.
2557   for (unsigned i = 7; i >= 4; --i) {
2558     unsigned Val = 0;
2559     SDValue Arg = N->getOperand(i);
2560     if (Arg.getOpcode() != ISD::UNDEF)
2561       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2562     Mask |= (Val - 4);
2563     if (i != 4)
2564       Mask <<= 2;
2565   }
2566
2567   return Mask;
2568 }
2569
2570 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2571 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2572 /// instructions.
2573 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2574   unsigned Mask = 0;
2575   // 8 nodes, but we only care about the first 4.
2576   for (int i = 3; i >= 0; --i) {
2577     unsigned Val = 0;
2578     SDValue Arg = N->getOperand(i);
2579     if (Arg.getOpcode() != ISD::UNDEF)
2580       Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2581     Mask |= Val;
2582     if (i != 0)
2583       Mask <<= 2;
2584   }
2585
2586   return Mask;
2587 }
2588
2589 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2590 /// specifies a 8 element shuffle that can be broken into a pair of
2591 /// PSHUFHW and PSHUFLW.
2592 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2593   assert(N->getOpcode() == ISD::BUILD_VECTOR);
2594
2595   if (N->getNumOperands() != 8)
2596     return false;
2597
2598   // Lower quadword shuffled.
2599   for (unsigned i = 0; i != 4; ++i) {
2600     SDValue Arg = N->getOperand(i);
2601     if (Arg.getOpcode() == ISD::UNDEF) continue;
2602     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2603     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2604     if (Val >= 4)
2605       return false;
2606   }
2607
2608   // Upper quadword shuffled.
2609   for (unsigned i = 4; i != 8; ++i) {
2610     SDValue Arg = N->getOperand(i);
2611     if (Arg.getOpcode() == ISD::UNDEF) continue;
2612     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2613     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2614     if (Val < 4 || Val > 7)
2615       return false;
2616   }
2617
2618   return true;
2619 }
2620
2621 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2622 /// values in ther permute mask.
2623 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2624                                       SDValue &V2, SDValue &Mask,
2625                                       SelectionDAG &DAG) {
2626   MVT VT = Op.getValueType();
2627   MVT MaskVT = Mask.getValueType();
2628   MVT EltVT = MaskVT.getVectorElementType();
2629   unsigned NumElems = Mask.getNumOperands();
2630   SmallVector<SDValue, 8> MaskVec;
2631
2632   for (unsigned i = 0; i != NumElems; ++i) {
2633     SDValue Arg = Mask.getOperand(i);
2634     if (Arg.getOpcode() == ISD::UNDEF) {
2635       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2636       continue;
2637     }
2638     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2639     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2640     if (Val < NumElems)
2641       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2642     else
2643       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2644   }
2645
2646   std::swap(V1, V2);
2647   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2648   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2649 }
2650
2651 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2652 /// the two vector operands have swapped position.
2653 static
2654 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2655   MVT MaskVT = Mask.getValueType();
2656   MVT EltVT = MaskVT.getVectorElementType();
2657   unsigned NumElems = Mask.getNumOperands();
2658   SmallVector<SDValue, 8> MaskVec;
2659   for (unsigned i = 0; i != NumElems; ++i) {
2660     SDValue Arg = Mask.getOperand(i);
2661     if (Arg.getOpcode() == ISD::UNDEF) {
2662       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2663       continue;
2664     }
2665     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2666     unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2667     if (Val < NumElems)
2668       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2669     else
2670       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2671   }
2672   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2673 }
2674
2675
2676 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2677 /// match movhlps. The lower half elements should come from upper half of
2678 /// V1 (and in order), and the upper half elements should come from the upper
2679 /// half of V2 (and in order).
2680 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2681   unsigned NumElems = Mask->getNumOperands();
2682   if (NumElems != 4)
2683     return false;
2684   for (unsigned i = 0, e = 2; i != e; ++i)
2685     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2686       return false;
2687   for (unsigned i = 2; i != 4; ++i)
2688     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2689       return false;
2690   return true;
2691 }
2692
2693 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2694 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2695 /// required.
2696 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2697   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2698     N = N->getOperand(0).getNode();
2699     if (ISD::isNON_EXTLoad(N)) {
2700       if (LD)
2701         *LD = cast<LoadSDNode>(N);
2702       return true;
2703     }
2704   }
2705   return false;
2706 }
2707
2708 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2709 /// match movlp{s|d}. The lower half elements should come from lower half of
2710 /// V1 (and in order), and the upper half elements should come from the upper
2711 /// half of V2 (and in order). And since V1 will become the source of the
2712 /// MOVLP, it must be either a vector load or a scalar load to vector.
2713 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2714   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2715     return false;
2716   // Is V2 is a vector load, don't do this transformation. We will try to use
2717   // load folding shufps op.
2718   if (ISD::isNON_EXTLoad(V2))
2719     return false;
2720
2721   unsigned NumElems = Mask->getNumOperands();
2722   if (NumElems != 2 && NumElems != 4)
2723     return false;
2724   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2725     if (!isUndefOrEqual(Mask->getOperand(i), i))
2726       return false;
2727   for (unsigned i = NumElems/2; i != NumElems; ++i)
2728     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2729       return false;
2730   return true;
2731 }
2732
2733 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2734 /// all the same.
2735 static bool isSplatVector(SDNode *N) {
2736   if (N->getOpcode() != ISD::BUILD_VECTOR)
2737     return false;
2738
2739   SDValue SplatValue = N->getOperand(0);
2740   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2741     if (N->getOperand(i) != SplatValue)
2742       return false;
2743   return true;
2744 }
2745
2746 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2747 /// to an undef.
2748 static bool isUndefShuffle(SDNode *N) {
2749   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2750     return false;
2751
2752   SDValue V1 = N->getOperand(0);
2753   SDValue V2 = N->getOperand(1);
2754   SDValue Mask = N->getOperand(2);
2755   unsigned NumElems = Mask.getNumOperands();
2756   for (unsigned i = 0; i != NumElems; ++i) {
2757     SDValue Arg = Mask.getOperand(i);
2758     if (Arg.getOpcode() != ISD::UNDEF) {
2759       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2760       if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2761         return false;
2762       else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2763         return false;
2764     }
2765   }
2766   return true;
2767 }
2768
2769 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2770 /// constant +0.0.
2771 static inline bool isZeroNode(SDValue Elt) {
2772   return ((isa<ConstantSDNode>(Elt) &&
2773            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2774           (isa<ConstantFPSDNode>(Elt) &&
2775            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2776 }
2777
2778 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2779 /// to an zero vector.
2780 static bool isZeroShuffle(SDNode *N) {
2781   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2782     return false;
2783
2784   SDValue V1 = N->getOperand(0);
2785   SDValue V2 = N->getOperand(1);
2786   SDValue Mask = N->getOperand(2);
2787   unsigned NumElems = Mask.getNumOperands();
2788   for (unsigned i = 0; i != NumElems; ++i) {
2789     SDValue Arg = Mask.getOperand(i);
2790     if (Arg.getOpcode() == ISD::UNDEF)
2791       continue;
2792     
2793     unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2794     if (Idx < NumElems) {
2795       unsigned Opc = V1.getNode()->getOpcode();
2796       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2797         continue;
2798       if (Opc != ISD::BUILD_VECTOR ||
2799           !isZeroNode(V1.getNode()->getOperand(Idx)))
2800         return false;
2801     } else if (Idx >= NumElems) {
2802       unsigned Opc = V2.getNode()->getOpcode();
2803       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2804         continue;
2805       if (Opc != ISD::BUILD_VECTOR ||
2806           !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2807         return false;
2808     }
2809   }
2810   return true;
2811 }
2812
2813 /// getZeroVector - Returns a vector of specified type with all zero elements.
2814 ///
2815 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2816   assert(VT.isVector() && "Expected a vector type");
2817   
2818   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2819   // type.  This ensures they get CSE'd.
2820   SDValue Vec;
2821   if (VT.getSizeInBits() == 64) { // MMX
2822     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2823     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2824   } else if (HasSSE2) {  // SSE2
2825     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2826     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2827   } else { // SSE1
2828     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2829     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2830   }
2831   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2832 }
2833
2834 /// getOnesVector - Returns a vector of specified type with all bits set.
2835 ///
2836 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2837   assert(VT.isVector() && "Expected a vector type");
2838   
2839   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2840   // type.  This ensures they get CSE'd.
2841   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2842   SDValue Vec;
2843   if (VT.getSizeInBits() == 64)  // MMX
2844     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2845   else                                              // SSE
2846     Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2847   return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2848 }
2849
2850
2851 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2852 /// that point to V2 points to its first element.
2853 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2854   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2855
2856   bool Changed = false;
2857   SmallVector<SDValue, 8> MaskVec;
2858   unsigned NumElems = Mask.getNumOperands();
2859   for (unsigned i = 0; i != NumElems; ++i) {
2860     SDValue Arg = Mask.getOperand(i);
2861     if (Arg.getOpcode() != ISD::UNDEF) {
2862       unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2863       if (Val > NumElems) {
2864         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2865         Changed = true;
2866       }
2867     }
2868     MaskVec.push_back(Arg);
2869   }
2870
2871   if (Changed)
2872     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2873                        &MaskVec[0], MaskVec.size());
2874   return Mask;
2875 }
2876
2877 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2878 /// operation of specified width.
2879 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2880   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2881   MVT BaseVT = MaskVT.getVectorElementType();
2882
2883   SmallVector<SDValue, 8> MaskVec;
2884   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2885   for (unsigned i = 1; i != NumElems; ++i)
2886     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2887   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2888 }
2889
2890 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2891 /// of specified width.
2892 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2893   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2894   MVT BaseVT = MaskVT.getVectorElementType();
2895   SmallVector<SDValue, 8> MaskVec;
2896   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2897     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2898     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2899   }
2900   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2901 }
2902
2903 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2904 /// of specified width.
2905 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2906   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2907   MVT BaseVT = MaskVT.getVectorElementType();
2908   unsigned Half = NumElems/2;
2909   SmallVector<SDValue, 8> MaskVec;
2910   for (unsigned i = 0; i != Half; ++i) {
2911     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2912     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2913   }
2914   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2915 }
2916
2917 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2918 /// element #0 of a vector with the specified index, leaving the rest of the
2919 /// elements in place.
2920 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2921                                    SelectionDAG &DAG) {
2922   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2923   MVT BaseVT = MaskVT.getVectorElementType();
2924   SmallVector<SDValue, 8> MaskVec;
2925   // Element #0 of the result gets the elt we are replacing.
2926   MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2927   for (unsigned i = 1; i != NumElems; ++i)
2928     MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2929   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2930 }
2931
2932 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2933 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2934   MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2935   MVT VT = Op.getValueType();
2936   if (PVT == VT)
2937     return Op;
2938   SDValue V1 = Op.getOperand(0);
2939   SDValue Mask = Op.getOperand(2);
2940   unsigned NumElems = Mask.getNumOperands();
2941   // Special handling of v4f32 -> v4i32.
2942   if (VT != MVT::v4f32) {
2943     Mask = getUnpacklMask(NumElems, DAG);
2944     while (NumElems > 4) {
2945       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2946       NumElems >>= 1;
2947     }
2948     Mask = getZeroVector(MVT::v4i32, true, DAG);
2949   }
2950
2951   V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2952   SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2953                                   DAG.getNode(ISD::UNDEF, PVT), Mask);
2954   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2955 }
2956
2957 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2958 /// vector of zero or undef vector.  This produces a shuffle where the low
2959 /// element of V2 is swizzled into the zero/undef vector, landing at element
2960 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
2961 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2962                                              bool isZero, bool HasSSE2,
2963                                              SelectionDAG &DAG) {
2964   MVT VT = V2.getValueType();
2965   SDValue V1 = isZero
2966     ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
2967   unsigned NumElems = V2.getValueType().getVectorNumElements();
2968   MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2969   MVT EVT = MaskVT.getVectorElementType();
2970   SmallVector<SDValue, 16> MaskVec;
2971   for (unsigned i = 0; i != NumElems; ++i)
2972     if (i == Idx)  // If this is the insertion idx, put the low elt of V2 here.
2973       MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2974     else
2975       MaskVec.push_back(DAG.getConstant(i, EVT));
2976   SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2977                                &MaskVec[0], MaskVec.size());
2978   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2979 }
2980
2981 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2982 /// a shuffle that is zero.
2983 static
2984 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
2985                                   unsigned NumElems, bool Low,
2986                                   SelectionDAG &DAG) {
2987   unsigned NumZeros = 0;
2988   for (unsigned i = 0; i < NumElems; ++i) {
2989     unsigned Index = Low ? i : NumElems-i-1;
2990     SDValue Idx = Mask.getOperand(Index);
2991     if (Idx.getOpcode() == ISD::UNDEF) {
2992       ++NumZeros;
2993       continue;
2994     }
2995     SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
2996     if (Elt.getNode() && isZeroNode(Elt))
2997       ++NumZeros;
2998     else
2999       break;
3000   }
3001   return NumZeros;
3002 }
3003
3004 /// isVectorShift - Returns true if the shuffle can be implemented as a
3005 /// logical left or right shift of a vector.
3006 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3007                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3008   unsigned NumElems = Mask.getNumOperands();
3009
3010   isLeft = true;
3011   unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3012   if (!NumZeros) {
3013     isLeft = false;
3014     NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3015     if (!NumZeros)
3016       return false;
3017   }
3018
3019   bool SeenV1 = false;
3020   bool SeenV2 = false;
3021   for (unsigned i = NumZeros; i < NumElems; ++i) {
3022     unsigned Val = isLeft ? (i - NumZeros) : i;
3023     SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3024     if (Idx.getOpcode() == ISD::UNDEF)
3025       continue;
3026     unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3027     if (Index < NumElems)
3028       SeenV1 = true;
3029     else {
3030       Index -= NumElems;
3031       SeenV2 = true;
3032     }
3033     if (Index != Val)
3034       return false;
3035   }
3036   if (SeenV1 && SeenV2)
3037     return false;
3038
3039   ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3040   ShAmt = NumZeros;
3041   return true;
3042 }
3043
3044
3045 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3046 ///
3047 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3048                                        unsigned NumNonZero, unsigned NumZero,
3049                                        SelectionDAG &DAG, TargetLowering &TLI) {
3050   if (NumNonZero > 8)
3051     return SDValue();
3052
3053   SDValue V(0, 0);
3054   bool First = true;
3055   for (unsigned i = 0; i < 16; ++i) {
3056     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3057     if (ThisIsNonZero && First) {
3058       if (NumZero)
3059         V = getZeroVector(MVT::v8i16, true, DAG);
3060       else
3061         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3062       First = false;
3063     }
3064
3065     if ((i & 1) != 0) {
3066       SDValue ThisElt(0, 0), LastElt(0, 0);
3067       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3068       if (LastIsNonZero) {
3069         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3070       }
3071       if (ThisIsNonZero) {
3072         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3073         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3074                               ThisElt, DAG.getConstant(8, MVT::i8));
3075         if (LastIsNonZero)
3076           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3077       } else
3078         ThisElt = LastElt;
3079
3080       if (ThisElt.getNode())
3081         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3082                         DAG.getIntPtrConstant(i/2));
3083     }
3084   }
3085
3086   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3087 }
3088
3089 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3090 ///
3091 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3092                                        unsigned NumNonZero, unsigned NumZero,
3093                                        SelectionDAG &DAG, TargetLowering &TLI) {
3094   if (NumNonZero > 4)
3095     return SDValue();
3096
3097   SDValue V(0, 0);
3098   bool First = true;
3099   for (unsigned i = 0; i < 8; ++i) {
3100     bool isNonZero = (NonZeros & (1 << i)) != 0;
3101     if (isNonZero) {
3102       if (First) {
3103         if (NumZero)
3104           V = getZeroVector(MVT::v8i16, true, DAG);
3105         else
3106           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3107         First = false;
3108       }
3109       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3110                       DAG.getIntPtrConstant(i));
3111     }
3112   }
3113
3114   return V;
3115 }
3116
3117 /// getVShift - Return a vector logical shift node.
3118 ///
3119 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3120                            unsigned NumBits, SelectionDAG &DAG,
3121                            const TargetLowering &TLI) {
3122   bool isMMX = VT.getSizeInBits() == 64;
3123   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3124   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3125   SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3126   return DAG.getNode(ISD::BIT_CONVERT, VT,
3127                      DAG.getNode(Opc, ShVT, SrcOp,
3128                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3129 }
3130
3131 SDValue
3132 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3133   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3134   if (ISD::isBuildVectorAllZeros(Op.getNode())
3135       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3136     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3137     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3138     // eliminated on x86-32 hosts.
3139     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3140       return Op;
3141
3142     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3143       return getOnesVector(Op.getValueType(), DAG);
3144     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3145   }
3146
3147   MVT VT = Op.getValueType();
3148   MVT EVT = VT.getVectorElementType();
3149   unsigned EVTBits = EVT.getSizeInBits();
3150
3151   unsigned NumElems = Op.getNumOperands();
3152   unsigned NumZero  = 0;
3153   unsigned NumNonZero = 0;
3154   unsigned NonZeros = 0;
3155   bool IsAllConstants = true;
3156   SmallSet<SDValue, 8> Values;
3157   for (unsigned i = 0; i < NumElems; ++i) {
3158     SDValue Elt = Op.getOperand(i);
3159     if (Elt.getOpcode() == ISD::UNDEF)
3160       continue;
3161     Values.insert(Elt);
3162     if (Elt.getOpcode() != ISD::Constant &&
3163         Elt.getOpcode() != ISD::ConstantFP)
3164       IsAllConstants = false;
3165     if (isZeroNode(Elt))
3166       NumZero++;
3167     else {
3168       NonZeros |= (1 << i);
3169       NumNonZero++;
3170     }
3171   }
3172
3173   if (NumNonZero == 0) {
3174     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3175     return DAG.getNode(ISD::UNDEF, VT);
3176   }
3177
3178   // Special case for single non-zero, non-undef, element.
3179   if (NumNonZero == 1 && NumElems <= 4) {
3180     unsigned Idx = CountTrailingZeros_32(NonZeros);
3181     SDValue Item = Op.getOperand(Idx);
3182     
3183     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3184     // the value are obviously zero, truncate the value to i32 and do the
3185     // insertion that way.  Only do this if the value is non-constant or if the
3186     // value is a constant being inserted into element 0.  It is cheaper to do
3187     // a constant pool load than it is to do a movd + shuffle.
3188     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3189         (!IsAllConstants || Idx == 0)) {
3190       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3191         // Handle MMX and SSE both.
3192         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3193         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3194         
3195         // Truncate the value (which may itself be a constant) to i32, and
3196         // convert it to a vector with movd (S2V+shuffle to zero extend).
3197         Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3198         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3199         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3200                                            Subtarget->hasSSE2(), DAG);
3201         
3202         // Now we have our 32-bit value zero extended in the low element of
3203         // a vector.  If Idx != 0, swizzle it into place.
3204         if (Idx != 0) {
3205           SDValue Ops[] = { 
3206             Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3207             getSwapEltZeroMask(VecElts, Idx, DAG)
3208           };
3209           Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3210         }
3211         return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3212       }
3213     }
3214     
3215     // If we have a constant or non-constant insertion into the low element of
3216     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3217     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3218     // depending on what the source datatype is.  Because we can only get here
3219     // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3220     if (Idx == 0 &&
3221         // Don't do this for i64 values on x86-32.
3222         (EVT != MVT::i64 || Subtarget->is64Bit())) {
3223       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3224       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3225       return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3226                                          Subtarget->hasSSE2(), DAG);
3227     }
3228
3229     // Is it a vector logical left shift?
3230     if (NumElems == 2 && Idx == 1 &&
3231         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3232       unsigned NumBits = VT.getSizeInBits();
3233       return getVShift(true, VT,
3234                        DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3235                        NumBits/2, DAG, *this);
3236     }
3237     
3238     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3239       return SDValue();
3240
3241     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3242     // is a non-constant being inserted into an element other than the low one,
3243     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3244     // movd/movss) to move this into the low element, then shuffle it into
3245     // place.
3246     if (EVTBits == 32) {
3247       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3248       
3249       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3250       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3251                                          Subtarget->hasSSE2(), DAG);
3252       MVT MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
3253       MVT MaskEVT = MaskVT.getVectorElementType();
3254       SmallVector<SDValue, 8> MaskVec;
3255       for (unsigned i = 0; i < NumElems; i++)
3256         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3257       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3258                                    &MaskVec[0], MaskVec.size());
3259       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3260                          DAG.getNode(ISD::UNDEF, VT), Mask);
3261     }
3262   }
3263
3264   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3265   if (Values.size() == 1)
3266     return SDValue();
3267   
3268   // A vector full of immediates; various special cases are already
3269   // handled, so this is best done with a single constant-pool load.
3270   if (IsAllConstants)
3271     return SDValue();
3272
3273   // Let legalizer expand 2-wide build_vectors.
3274   if (EVTBits == 64) {
3275     if (NumNonZero == 1) {
3276       // One half is zero or undef.
3277       unsigned Idx = CountTrailingZeros_32(NonZeros);
3278       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3279                                  Op.getOperand(Idx));
3280       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3281                                          Subtarget->hasSSE2(), DAG);
3282     }
3283     return SDValue();
3284   }
3285
3286   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3287   if (EVTBits == 8 && NumElems == 16) {
3288     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3289                                         *this);
3290     if (V.getNode()) return V;
3291   }
3292
3293   if (EVTBits == 16 && NumElems == 8) {
3294     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3295                                         *this);
3296     if (V.getNode()) return V;
3297   }
3298
3299   // If element VT is == 32 bits, turn it into a number of shuffles.
3300   SmallVector<SDValue, 8> V;
3301   V.resize(NumElems);
3302   if (NumElems == 4 && NumZero > 0) {
3303     for (unsigned i = 0; i < 4; ++i) {
3304       bool isZero = !(NonZeros & (1 << i));
3305       if (isZero)
3306         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3307       else
3308         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3309     }
3310
3311     for (unsigned i = 0; i < 2; ++i) {
3312       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3313         default: break;
3314         case 0:
3315           V[i] = V[i*2];  // Must be a zero vector.
3316           break;
3317         case 1:
3318           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3319                              getMOVLMask(NumElems, DAG));
3320           break;
3321         case 2:
3322           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3323                              getMOVLMask(NumElems, DAG));
3324           break;
3325         case 3:
3326           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3327                              getUnpacklMask(NumElems, DAG));
3328           break;
3329       }
3330     }
3331
3332     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3333     MVT EVT = MaskVT.getVectorElementType();
3334     SmallVector<SDValue, 8> MaskVec;
3335     bool Reverse = (NonZeros & 0x3) == 2;
3336     for (unsigned i = 0; i < 2; ++i)
3337       if (Reverse)
3338         MaskVec.push_back(DAG.getConstant(1-i, EVT));
3339       else
3340         MaskVec.push_back(DAG.getConstant(i, EVT));
3341     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3342     for (unsigned i = 0; i < 2; ++i)
3343       if (Reverse)
3344         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3345       else
3346         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3347     SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3348                                      &MaskVec[0], MaskVec.size());
3349     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3350   }
3351
3352   if (Values.size() > 2) {
3353     // Expand into a number of unpckl*.
3354     // e.g. for v4f32
3355     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3356     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3357     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3358     SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3359     for (unsigned i = 0; i < NumElems; ++i)
3360       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3361     NumElems >>= 1;
3362     while (NumElems != 0) {
3363       for (unsigned i = 0; i < NumElems; ++i)
3364         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3365                            UnpckMask);
3366       NumElems >>= 1;
3367     }
3368     return V[0];
3369   }
3370
3371   return SDValue();
3372 }
3373
3374 static
3375 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3376                                  SDValue PermMask, SelectionDAG &DAG,
3377                                  TargetLowering &TLI) {
3378   SDValue NewV;
3379   MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3380   MVT MaskEVT = MaskVT.getVectorElementType();
3381   MVT PtrVT = TLI.getPointerTy();
3382   SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3383                                    PermMask.getNode()->op_end());
3384
3385   // First record which half of which vector the low elements come from.
3386   SmallVector<unsigned, 4> LowQuad(4);
3387   for (unsigned i = 0; i < 4; ++i) {
3388     SDValue Elt = MaskElts[i];
3389     if (Elt.getOpcode() == ISD::UNDEF)
3390       continue;
3391     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3392     int QuadIdx = EltIdx / 4;
3393     ++LowQuad[QuadIdx];
3394   }
3395
3396   int BestLowQuad = -1;
3397   unsigned MaxQuad = 1;
3398   for (unsigned i = 0; i < 4; ++i) {
3399     if (LowQuad[i] > MaxQuad) {
3400       BestLowQuad = i;
3401       MaxQuad = LowQuad[i];
3402     }
3403   }
3404
3405   // Record which half of which vector the high elements come from.
3406   SmallVector<unsigned, 4> HighQuad(4);
3407   for (unsigned i = 4; i < 8; ++i) {
3408     SDValue Elt = MaskElts[i];
3409     if (Elt.getOpcode() == ISD::UNDEF)
3410       continue;
3411     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3412     int QuadIdx = EltIdx / 4;
3413     ++HighQuad[QuadIdx];
3414   }
3415
3416   int BestHighQuad = -1;
3417   MaxQuad = 1;
3418   for (unsigned i = 0; i < 4; ++i) {
3419     if (HighQuad[i] > MaxQuad) {
3420       BestHighQuad = i;
3421       MaxQuad = HighQuad[i];
3422     }
3423   }
3424
3425   // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3426   if (BestLowQuad != -1 || BestHighQuad != -1) {
3427     // First sort the 4 chunks in order using shufpd.
3428     SmallVector<SDValue, 8> MaskVec;
3429
3430     if (BestLowQuad != -1)
3431       MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3432     else
3433       MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3434
3435     if (BestHighQuad != -1)
3436       MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3437     else
3438       MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3439
3440     SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3441     NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3442                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3443                        DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3444     NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3445
3446     // Now sort high and low parts separately.
3447     BitVector InOrder(8);
3448     if (BestLowQuad != -1) {
3449       // Sort lower half in order using PSHUFLW.
3450       MaskVec.clear();
3451       bool AnyOutOrder = false;
3452
3453       for (unsigned i = 0; i != 4; ++i) {
3454         SDValue Elt = MaskElts[i];
3455         if (Elt.getOpcode() == ISD::UNDEF) {
3456           MaskVec.push_back(Elt);
3457           InOrder.set(i);
3458         } else {
3459           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3460           if (EltIdx != i)
3461             AnyOutOrder = true;
3462
3463           MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3464
3465           // If this element is in the right place after this shuffle, then
3466           // remember it.
3467           if ((int)(EltIdx / 4) == BestLowQuad)
3468             InOrder.set(i);
3469         }
3470       }
3471       if (AnyOutOrder) {
3472         for (unsigned i = 4; i != 8; ++i)
3473           MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3474         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3475         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3476       }
3477     }
3478
3479     if (BestHighQuad != -1) {
3480       // Sort high half in order using PSHUFHW if possible.
3481       MaskVec.clear();
3482
3483       for (unsigned i = 0; i != 4; ++i)
3484         MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3485
3486       bool AnyOutOrder = false;
3487       for (unsigned i = 4; i != 8; ++i) {
3488         SDValue Elt = MaskElts[i];
3489         if (Elt.getOpcode() == ISD::UNDEF) {
3490           MaskVec.push_back(Elt);
3491           InOrder.set(i);
3492         } else {
3493           unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3494           if (EltIdx != i)
3495             AnyOutOrder = true;
3496
3497           MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3498
3499           // If this element is in the right place after this shuffle, then
3500           // remember it.
3501           if ((int)(EltIdx / 4) == BestHighQuad)
3502             InOrder.set(i);
3503         }
3504       }
3505
3506       if (AnyOutOrder) {
3507         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3508         NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3509       }
3510     }
3511
3512     // The other elements are put in the right place using pextrw and pinsrw.
3513     for (unsigned i = 0; i != 8; ++i) {
3514       if (InOrder[i])
3515         continue;
3516       SDValue Elt = MaskElts[i];
3517       if (Elt.getOpcode() == ISD::UNDEF)
3518         continue;
3519       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3520       SDValue ExtOp = (EltIdx < 8)
3521         ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3522                       DAG.getConstant(EltIdx, PtrVT))
3523         : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3524                       DAG.getConstant(EltIdx - 8, PtrVT));
3525       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3526                          DAG.getConstant(i, PtrVT));
3527     }
3528
3529     return NewV;
3530   }
3531
3532   // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3533   // few as possible. First, let's find out how many elements are already in the
3534   // right order.
3535   unsigned V1InOrder = 0;
3536   unsigned V1FromV1 = 0;
3537   unsigned V2InOrder = 0;
3538   unsigned V2FromV2 = 0;
3539   SmallVector<SDValue, 8> V1Elts;
3540   SmallVector<SDValue, 8> V2Elts;
3541   for (unsigned i = 0; i < 8; ++i) {
3542     SDValue Elt = MaskElts[i];
3543     if (Elt.getOpcode() == ISD::UNDEF) {
3544       V1Elts.push_back(Elt);
3545       V2Elts.push_back(Elt);
3546       ++V1InOrder;
3547       ++V2InOrder;
3548       continue;
3549     }
3550     unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3551     if (EltIdx == i) {
3552       V1Elts.push_back(Elt);
3553       V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3554       ++V1InOrder;
3555     } else if (EltIdx == i+8) {
3556       V1Elts.push_back(Elt);
3557       V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3558       ++V2InOrder;
3559     } else if (EltIdx < 8) {
3560       V1Elts.push_back(Elt);
3561       ++V1FromV1;
3562     } else {
3563       V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3564       ++V2FromV2;
3565     }
3566   }
3567
3568   if (V2InOrder > V1InOrder) {
3569     PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3570     std::swap(V1, V2);
3571     std::swap(V1Elts, V2Elts);
3572     std::swap(V1FromV1, V2FromV2);
3573   }
3574
3575   if ((V1FromV1 + V1InOrder) != 8) {
3576     // Some elements are from V2.
3577     if (V1FromV1) {
3578       // If there are elements that are from V1 but out of place,
3579       // then first sort them in place
3580       SmallVector<SDValue, 8> MaskVec;
3581       for (unsigned i = 0; i < 8; ++i) {
3582         SDValue Elt = V1Elts[i];
3583         if (Elt.getOpcode() == ISD::UNDEF) {
3584           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3585           continue;
3586         }
3587         unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3588         if (EltIdx >= 8)
3589           MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3590         else
3591           MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3592       }
3593       SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3594       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3595     }
3596
3597     NewV = V1;
3598     for (unsigned i = 0; i < 8; ++i) {
3599       SDValue Elt = V1Elts[i];
3600       if (Elt.getOpcode() == ISD::UNDEF)
3601         continue;
3602       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3603       if (EltIdx < 8)
3604         continue;
3605       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3606                                     DAG.getConstant(EltIdx - 8, PtrVT));
3607       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3608                          DAG.getConstant(i, PtrVT));
3609     }
3610     return NewV;
3611   } else {
3612     // All elements are from V1.
3613     NewV = V1;
3614     for (unsigned i = 0; i < 8; ++i) {
3615       SDValue Elt = V1Elts[i];
3616       if (Elt.getOpcode() == ISD::UNDEF)
3617         continue;
3618       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3619       SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3620                                     DAG.getConstant(EltIdx, PtrVT));
3621       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3622                          DAG.getConstant(i, PtrVT));
3623     }
3624     return NewV;
3625   }
3626 }
3627
3628 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3629 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3630 /// done when every pair / quad of shuffle mask elements point to elements in
3631 /// the right sequence. e.g.
3632 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3633 static
3634 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3635                                 MVT VT,
3636                                 SDValue PermMask, SelectionDAG &DAG,
3637                                 TargetLowering &TLI) {
3638   unsigned NumElems = PermMask.getNumOperands();
3639   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3640   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3641   MVT MaskEltVT = MaskVT.getVectorElementType();
3642   MVT NewVT = MaskVT;
3643   switch (VT.getSimpleVT()) {
3644   default: assert(false && "Unexpected!");
3645   case MVT::v4f32: NewVT = MVT::v2f64; break;
3646   case MVT::v4i32: NewVT = MVT::v2i64; break;
3647   case MVT::v8i16: NewVT = MVT::v4i32; break;
3648   case MVT::v16i8: NewVT = MVT::v4i32; break;
3649   }
3650
3651   if (NewWidth == 2) {
3652     if (VT.isInteger())
3653       NewVT = MVT::v2i64;
3654     else
3655       NewVT = MVT::v2f64;
3656   }
3657   unsigned Scale = NumElems / NewWidth;
3658   SmallVector<SDValue, 8> MaskVec;
3659   for (unsigned i = 0; i < NumElems; i += Scale) {
3660     unsigned StartIdx = ~0U;
3661     for (unsigned j = 0; j < Scale; ++j) {
3662       SDValue Elt = PermMask.getOperand(i+j);
3663       if (Elt.getOpcode() == ISD::UNDEF)
3664         continue;
3665       unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3666       if (StartIdx == ~0U)
3667         StartIdx = EltIdx - (EltIdx % Scale);
3668       if (EltIdx != StartIdx + j)
3669         return SDValue();
3670     }
3671     if (StartIdx == ~0U)
3672       MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3673     else
3674       MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3675   }
3676
3677   V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3678   V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3679   return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3680                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3681                                  &MaskVec[0], MaskVec.size()));
3682 }
3683
3684 /// getVZextMovL - Return a zero-extending vector move low node.
3685 ///
3686 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3687                               SDValue SrcOp, SelectionDAG &DAG,
3688                               const X86Subtarget *Subtarget) {
3689   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3690     LoadSDNode *LD = NULL;
3691     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3692       LD = dyn_cast<LoadSDNode>(SrcOp);
3693     if (!LD) {
3694       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3695       // instead.
3696       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3697       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3698           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3699           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3700           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3701         // PR2108
3702         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3703         return DAG.getNode(ISD::BIT_CONVERT, VT,
3704                            DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3705                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3706                                                    SrcOp.getOperand(0)
3707                                                           .getOperand(0))));
3708       }
3709     }
3710   }
3711
3712   return DAG.getNode(ISD::BIT_CONVERT, VT,
3713                      DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3714                                  DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3715 }
3716
3717 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3718 /// shuffles.
3719 static SDValue
3720 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3721                           SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3722   MVT MaskVT = PermMask.getValueType();
3723   MVT MaskEVT = MaskVT.getVectorElementType();
3724   SmallVector<std::pair<int, int>, 8> Locs;
3725   Locs.resize(4);
3726   SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3727   unsigned NumHi = 0;
3728   unsigned NumLo = 0;
3729   for (unsigned i = 0; i != 4; ++i) {
3730     SDValue Elt = PermMask.getOperand(i);
3731     if (Elt.getOpcode() == ISD::UNDEF) {
3732       Locs[i] = std::make_pair(-1, -1);
3733     } else {
3734       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3735       assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3736       if (Val < 4) {
3737         Locs[i] = std::make_pair(0, NumLo);
3738         Mask1[NumLo] = Elt;
3739         NumLo++;
3740       } else {
3741         Locs[i] = std::make_pair(1, NumHi);
3742         if (2+NumHi < 4)
3743           Mask1[2+NumHi] = Elt;
3744         NumHi++;
3745       }
3746     }
3747   }
3748
3749   if (NumLo <= 2 && NumHi <= 2) {
3750     // If no more than two elements come from either vector. This can be
3751     // implemented with two shuffles. First shuffle gather the elements.
3752     // The second shuffle, which takes the first shuffle as both of its
3753     // vector operands, put the elements into the right order.
3754     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3755                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3756                                  &Mask1[0], Mask1.size()));
3757
3758     SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3759     for (unsigned i = 0; i != 4; ++i) {
3760       if (Locs[i].first == -1)
3761         continue;
3762       else {
3763         unsigned Idx = (i < 2) ? 0 : 4;
3764         Idx += Locs[i].first * 2 + Locs[i].second;
3765         Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3766       }
3767     }
3768
3769     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3770                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3771                                    &Mask2[0], Mask2.size()));
3772   } else if (NumLo == 3 || NumHi == 3) {
3773     // Otherwise, we must have three elements from one vector, call it X, and
3774     // one element from the other, call it Y.  First, use a shufps to build an
3775     // intermediate vector with the one element from Y and the element from X
3776     // that will be in the same half in the final destination (the indexes don't
3777     // matter). Then, use a shufps to build the final vector, taking the half
3778     // containing the element from Y from the intermediate, and the other half
3779     // from X.
3780     if (NumHi == 3) {
3781       // Normalize it so the 3 elements come from V1.
3782       PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3783       std::swap(V1, V2);
3784     }
3785
3786     // Find the element from V2.
3787     unsigned HiIndex;
3788     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3789       SDValue Elt = PermMask.getOperand(HiIndex);
3790       if (Elt.getOpcode() == ISD::UNDEF)
3791         continue;
3792       unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3793       if (Val >= 4)
3794         break;
3795     }
3796
3797     Mask1[0] = PermMask.getOperand(HiIndex);
3798     Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3799     Mask1[2] = PermMask.getOperand(HiIndex^1);
3800     Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3801     V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3802                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3803
3804     if (HiIndex >= 2) {
3805       Mask1[0] = PermMask.getOperand(0);
3806       Mask1[1] = PermMask.getOperand(1);
3807       Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3808       Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3809       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3810                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3811     } else {
3812       Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3813       Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3814       Mask1[2] = PermMask.getOperand(2);
3815       Mask1[3] = PermMask.getOperand(3);
3816       if (Mask1[2].getOpcode() != ISD::UNDEF)
3817         Mask1[2] =
3818           DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3819                           MaskEVT);
3820       if (Mask1[3].getOpcode() != ISD::UNDEF)
3821         Mask1[3] =
3822           DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3823                           MaskEVT);
3824       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3825                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3826     }
3827   }
3828
3829   // Break it into (shuffle shuffle_hi, shuffle_lo).
3830   Locs.clear();
3831   SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3832   SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3833   SmallVector<SDValue,8> *MaskPtr = &LoMask;
3834   unsigned MaskIdx = 0;
3835   unsigned LoIdx = 0;
3836   unsigned HiIdx = 2;
3837   for (unsigned i = 0; i != 4; ++i) {
3838     if (i == 2) {
3839       MaskPtr = &HiMask;
3840       MaskIdx = 1;
3841       LoIdx = 0;
3842       HiIdx = 2;
3843     }
3844     SDValue Elt = PermMask.getOperand(i);
3845     if (Elt.getOpcode() == ISD::UNDEF) {
3846       Locs[i] = std::make_pair(-1, -1);
3847     } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3848       Locs[i] = std::make_pair(MaskIdx, LoIdx);
3849       (*MaskPtr)[LoIdx] = Elt;
3850       LoIdx++;
3851     } else {
3852       Locs[i] = std::make_pair(MaskIdx, HiIdx);
3853       (*MaskPtr)[HiIdx] = Elt;
3854       HiIdx++;
3855     }
3856   }
3857
3858   SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3859                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3860                                                 &LoMask[0], LoMask.size()));
3861   SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3862                                     DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3863                                                 &HiMask[0], HiMask.size()));
3864   SmallVector<SDValue, 8> MaskOps;
3865   for (unsigned i = 0; i != 4; ++i) {
3866     if (Locs[i].first == -1) {
3867       MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3868     } else {
3869       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3870       MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3871     }
3872   }
3873   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3874                      DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3875                                  &MaskOps[0], MaskOps.size()));
3876 }
3877
3878 SDValue
3879 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3880   SDValue V1 = Op.getOperand(0);
3881   SDValue V2 = Op.getOperand(1);
3882   SDValue PermMask = Op.getOperand(2);
3883   MVT VT = Op.getValueType();
3884   unsigned NumElems = PermMask.getNumOperands();
3885   bool isMMX = VT.getSizeInBits() == 64;
3886   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3887   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3888   bool V1IsSplat = false;
3889   bool V2IsSplat = false;
3890
3891   if (isUndefShuffle(Op.getNode()))
3892     return DAG.getNode(ISD::UNDEF, VT);
3893
3894   if (isZeroShuffle(Op.getNode()))
3895     return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3896
3897   if (isIdentityMask(PermMask.getNode()))
3898     return V1;
3899   else if (isIdentityMask(PermMask.getNode(), true))
3900     return V2;
3901
3902   if (isSplatMask(PermMask.getNode())) {
3903     if (isMMX || NumElems < 4) return Op;
3904     // Promote it to a v4{if}32 splat.
3905     return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3906   }
3907
3908   // If the shuffle can be profitably rewritten as a narrower shuffle, then
3909   // do it!
3910   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3911     SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3912     if (NewOp.getNode())
3913       return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3914   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3915     // FIXME: Figure out a cleaner way to do this.
3916     // Try to make use of movq to zero out the top part.
3917     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3918       SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3919                                                  DAG, *this);
3920       if (NewOp.getNode()) {
3921         SDValue NewV1 = NewOp.getOperand(0);
3922         SDValue NewV2 = NewOp.getOperand(1);
3923         SDValue NewMask = NewOp.getOperand(2);
3924         if (isCommutedMOVL(NewMask.getNode(), true, false)) {
3925           NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3926           return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
3927         }
3928       }
3929     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3930       SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
3931                                                 DAG, *this);
3932       if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
3933         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3934                              DAG, Subtarget);
3935     }
3936   }
3937
3938   // Check if this can be converted into a logical shift.
3939   bool isLeft = false;
3940   unsigned ShAmt = 0;
3941   SDValue ShVal;
3942   bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
3943   if (isShift && ShVal.hasOneUse()) {
3944     // If the shifted value has multiple uses, it may be cheaper to use 
3945     // v_set0 + movlhps or movhlps, etc.
3946     MVT EVT = VT.getVectorElementType();
3947     ShAmt *= EVT.getSizeInBits();
3948     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3949   }
3950
3951   if (X86::isMOVLMask(PermMask.getNode())) {
3952     if (V1IsUndef)
3953       return V2;
3954     if (ISD::isBuildVectorAllZeros(V1.getNode()))
3955       return getVZextMovL(VT, VT, V2, DAG, Subtarget);
3956     if (!isMMX)
3957       return Op;
3958   }
3959
3960   if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
3961                  X86::isMOVSLDUPMask(PermMask.getNode()) ||
3962                  X86::isMOVHLPSMask(PermMask.getNode()) ||
3963                  X86::isMOVHPMask(PermMask.getNode()) ||
3964                  X86::isMOVLPMask(PermMask.getNode())))
3965     return Op;
3966
3967   if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
3968       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
3969     return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3970
3971   if (isShift) {
3972     // No better options. Use a vshl / vsrl.
3973     MVT EVT = VT.getVectorElementType();
3974     ShAmt *= EVT.getSizeInBits();
3975     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
3976   }
3977
3978   bool Commuted = false;
3979   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
3980   // 1,1,1,1 -> v8i16 though.
3981   V1IsSplat = isSplatVector(V1.getNode());
3982   V2IsSplat = isSplatVector(V2.getNode());
3983   
3984   // Canonicalize the splat or undef, if present, to be on the RHS.
3985   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3986     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3987     std::swap(V1IsSplat, V2IsSplat);
3988     std::swap(V1IsUndef, V2IsUndef);
3989     Commuted = true;
3990   }
3991
3992   // FIXME: Figure out a cleaner way to do this.
3993   if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
3994     if (V2IsUndef) return V1;
3995     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3996     if (V2IsSplat) {
3997       // V2 is a splat, so the mask may be malformed. That is, it may point
3998       // to any V2 element. The instruction selectior won't like this. Get
3999       // a corrected mask and commute to form a proper MOVS{S|D}.
4000       SDValue NewMask = getMOVLMask(NumElems, DAG);
4001       if (NewMask.getNode() != PermMask.getNode())
4002         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4003     }
4004     return Op;
4005   }
4006
4007   if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4008       X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4009       X86::isUNPCKLMask(PermMask.getNode()) ||
4010       X86::isUNPCKHMask(PermMask.getNode()))
4011     return Op;
4012
4013   if (V2IsSplat) {
4014     // Normalize mask so all entries that point to V2 points to its first
4015     // element then try to match unpck{h|l} again. If match, return a
4016     // new vector_shuffle with the corrected mask.
4017     SDValue NewMask = NormalizeMask(PermMask, DAG);
4018     if (NewMask.getNode() != PermMask.getNode()) {
4019       if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4020         SDValue NewMask = getUnpacklMask(NumElems, DAG);
4021         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4022       } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4023         SDValue NewMask = getUnpackhMask(NumElems, DAG);
4024         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4025       }
4026     }
4027   }
4028
4029   // Normalize the node to match x86 shuffle ops if needed
4030   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4031       Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4032
4033   if (Commuted) {
4034     // Commute is back and try unpck* again.
4035     Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4036     if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4037         X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4038         X86::isUNPCKLMask(PermMask.getNode()) ||
4039         X86::isUNPCKHMask(PermMask.getNode()))
4040       return Op;
4041   }
4042
4043   // Try PSHUF* first, then SHUFP*.
4044   // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4045   // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4046   if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4047     if (V2.getOpcode() != ISD::UNDEF)
4048       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4049                          DAG.getNode(ISD::UNDEF, VT), PermMask);
4050     return Op;
4051   }
4052
4053   if (!isMMX) {
4054     if (Subtarget->hasSSE2() &&
4055         (X86::isPSHUFDMask(PermMask.getNode()) ||
4056          X86::isPSHUFHWMask(PermMask.getNode()) ||
4057          X86::isPSHUFLWMask(PermMask.getNode()))) {
4058       MVT RVT = VT;
4059       if (VT == MVT::v4f32) {
4060         RVT = MVT::v4i32;
4061         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4062                          DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4063                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4064       } else if (V2.getOpcode() != ISD::UNDEF)
4065         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4066                          DAG.getNode(ISD::UNDEF, RVT), PermMask);
4067       if (RVT != VT)
4068         Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4069       return Op;
4070     }
4071
4072     // Binary or unary shufps.
4073     if (X86::isSHUFPMask(PermMask.getNode()) ||
4074         (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4075       return Op;
4076   }
4077
4078   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4079   if (VT == MVT::v8i16) {
4080     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4081     if (NewOp.getNode())
4082       return NewOp;
4083   }
4084
4085   // Handle all 4 wide cases with a number of shuffles except for MMX.
4086   if (NumElems == 4 && !isMMX)
4087     return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4088
4089   return SDValue();
4090 }
4091
4092 SDValue
4093 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4094                                                 SelectionDAG &DAG) {
4095   MVT VT = Op.getValueType();
4096   if (VT.getSizeInBits() == 8) {
4097     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4098                                     Op.getOperand(0), Op.getOperand(1));
4099     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4100                                     DAG.getValueType(VT));
4101     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4102   } else if (VT.getSizeInBits() == 16) {
4103     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4104                                     Op.getOperand(0), Op.getOperand(1));
4105     SDValue Assert  = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4106                                     DAG.getValueType(VT));
4107     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4108   } else if (VT == MVT::f32) {
4109     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4110     // the result back to FR32 register. It's only worth matching if the
4111     // result has a single use which is a store or a bitcast to i32.
4112     if (!Op.hasOneUse())
4113       return SDValue();
4114     SDNode *User = *Op.getNode()->use_begin();
4115     if (User->getOpcode() != ISD::STORE &&
4116         (User->getOpcode() != ISD::BIT_CONVERT ||
4117          User->getValueType(0) != MVT::i32))
4118       return SDValue();
4119     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4120                     DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4121                                     Op.getOperand(1));
4122     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4123   }
4124   return SDValue();
4125 }
4126
4127
4128 SDValue
4129 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4130   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4131     return SDValue();
4132
4133   if (Subtarget->hasSSE41()) {
4134     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4135     if (Res.getNode())
4136       return Res;
4137   }
4138
4139   MVT VT = Op.getValueType();
4140   // TODO: handle v16i8.
4141   if (VT.getSizeInBits() == 16) {
4142     SDValue Vec = Op.getOperand(0);
4143     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4144     if (Idx == 0)
4145       return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4146                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4147                                  DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4148                                      Op.getOperand(1)));
4149     // Transform it so it match pextrw which produces a 32-bit result.
4150     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4151     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4152                                     Op.getOperand(0), Op.getOperand(1));
4153     SDValue Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
4154                                     DAG.getValueType(VT));
4155     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4156   } else if (VT.getSizeInBits() == 32) {
4157     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4158     if (Idx == 0)
4159       return Op;
4160     // SHUFPS the element to the lowest double word, then movss.
4161     MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4162     SmallVector<SDValue, 8> IdxVec;
4163     IdxVec.
4164       push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4165     IdxVec.
4166       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4167     IdxVec.
4168       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4169     IdxVec.
4170       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4171     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4172                                  &IdxVec[0], IdxVec.size());
4173     SDValue Vec = Op.getOperand(0);
4174     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4175                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4176     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4177                        DAG.getIntPtrConstant(0));
4178   } else if (VT.getSizeInBits() == 64) {
4179     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4180     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4181     //        to match extract_elt for f64.
4182     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4183     if (Idx == 0)
4184       return Op;
4185
4186     // UNPCKHPD the element to the lowest double word, then movsd.
4187     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4188     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4189     MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4190     SmallVector<SDValue, 8> IdxVec;
4191     IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4192     IdxVec.
4193       push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4194     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4195                                  &IdxVec[0], IdxVec.size());
4196     SDValue Vec = Op.getOperand(0);
4197     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4198                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4199     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4200                        DAG.getIntPtrConstant(0));
4201   }
4202
4203   return SDValue();
4204 }
4205
4206 SDValue
4207 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4208   MVT VT = Op.getValueType();
4209   MVT EVT = VT.getVectorElementType();
4210
4211   SDValue N0 = Op.getOperand(0);
4212   SDValue N1 = Op.getOperand(1);
4213   SDValue N2 = Op.getOperand(2);
4214
4215   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4216       isa<ConstantSDNode>(N2)) {
4217     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4218                                                   : X86ISD::PINSRW;
4219     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4220     // argument.
4221     if (N1.getValueType() != MVT::i32)
4222       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4223     if (N2.getValueType() != MVT::i32)
4224       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4225     return DAG.getNode(Opc, VT, N0, N1, N2);
4226   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4227     // Bits [7:6] of the constant are the source select.  This will always be
4228     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4229     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4230     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4231     // Bits [5:4] of the constant are the destination select.  This is the 
4232     //  value of the incoming immediate.
4233     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may 
4234     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4235     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4236     return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4237   }
4238   return SDValue();
4239 }
4240
4241 SDValue
4242 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4243   MVT VT = Op.getValueType();
4244   MVT EVT = VT.getVectorElementType();
4245
4246   if (Subtarget->hasSSE41())
4247     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4248
4249   if (EVT == MVT::i8)
4250     return SDValue();
4251
4252   SDValue N0 = Op.getOperand(0);
4253   SDValue N1 = Op.getOperand(1);
4254   SDValue N2 = Op.getOperand(2);
4255
4256   if (EVT.getSizeInBits() == 16) {
4257     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4258     // as its second argument.
4259     if (N1.getValueType() != MVT::i32)
4260       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4261     if (N2.getValueType() != MVT::i32)
4262       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4263     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4264   }
4265   return SDValue();
4266 }
4267
4268 SDValue
4269 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4270   if (Op.getValueType() == MVT::v2f32)
4271     return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4272                        DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4273                                    DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4274                                                Op.getOperand(0))));
4275
4276   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4277   MVT VT = MVT::v2i32;
4278   switch (Op.getValueType().getSimpleVT()) {
4279   default: break;
4280   case MVT::v16i8:
4281   case MVT::v8i16:
4282     VT = MVT::v4i32;
4283     break;
4284   }
4285   return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4286                      DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4287 }
4288
4289 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4290 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4291 // one of the above mentioned nodes. It has to be wrapped because otherwise
4292 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4293 // be used to form addressing mode. These wrapped nodes will be selected
4294 // 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.getTargetExternalSymbol("___tls_get_addr",
4366                                                   PtrVT),
4367                       DAG.getRegister(X86::EAX, PtrVT),
4368                       DAG.getRegister(X86::EBX, PtrVT),
4369                       InFlag };
4370   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4371   InFlag = Chain.getValue(1);
4372
4373   return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4374 }
4375
4376 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4377 static SDValue
4378 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4379                                 const MVT PtrVT) {
4380   SDValue InFlag, Chain;
4381
4382   // emit leaq symbol@TLSGD(%rip), %rdi
4383   SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4384   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4385                                              GA->getValueType(0),
4386                                              GA->getOffset());
4387   SDValue Ops[]  = { DAG.getEntryNode(), TGA};
4388   SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4389   Chain  = Result.getValue(1);
4390   InFlag = Result.getValue(2);
4391
4392   // call __tls_get_addr. This function receives its argument in
4393   // the register RDI.
4394   Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4395   InFlag = Chain.getValue(1);
4396
4397   NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4398   SDValue Ops1[] = { Chain,
4399                       DAG.getTargetExternalSymbol("__tls_get_addr",
4400                                                   PtrVT),
4401                       DAG.getRegister(X86::RDI, PtrVT),
4402                       InFlag };
4403   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4404   InFlag = Chain.getValue(1);
4405
4406   return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4407 }
4408
4409 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4410 // "local exec" model.
4411 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4412                                      const MVT PtrVT) {
4413   // Get the Thread Pointer
4414   SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4415   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4416   // exec)
4417   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4418                                              GA->getValueType(0),
4419                                              GA->getOffset());
4420   SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4421
4422   if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4423     Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4424                          PseudoSourceValue::getGOT(), 0);
4425
4426   // The address of the thread local variable is the add of the thread
4427   // pointer with the offset of the variable.
4428   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4429 }
4430
4431 SDValue
4432 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4433   // TODO: implement the "local dynamic" model
4434   // TODO: implement the "initial exec"model for pic executables
4435   assert(Subtarget->isTargetELF() &&
4436          "TLS not implemented for non-ELF targets");
4437   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4438   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4439   // otherwise use the "Local Exec"TLS Model
4440   if (Subtarget->is64Bit()) {
4441     return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4442   } else {
4443     if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4444       return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4445     else
4446       return LowerToTLSExecModel(GA, DAG, getPointerTy());
4447   }
4448 }
4449
4450 SDValue
4451 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4452   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4453   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4454   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4455   // With PIC, the address is actually $g + Offset.
4456   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4457       !Subtarget->isPICStyleRIPRel()) {
4458     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4459                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4460                          Result);
4461   }
4462
4463   return Result;
4464 }
4465
4466 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4467   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4468   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4469   Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4470   // With PIC, the address is actually $g + Offset.
4471   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4472       !Subtarget->isPICStyleRIPRel()) {
4473     Result = DAG.getNode(ISD::ADD, getPointerTy(),
4474                          DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4475                          Result);
4476   }
4477
4478   return Result;
4479 }
4480
4481 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4482 /// take a 2 x i32 value to shift plus a shift amount. 
4483 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4484   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4485   MVT VT = Op.getValueType();
4486   unsigned VTBits = VT.getSizeInBits();
4487   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4488   SDValue ShOpLo = Op.getOperand(0);
4489   SDValue ShOpHi = Op.getOperand(1);
4490   SDValue ShAmt  = Op.getOperand(2);
4491   SDValue Tmp1 = isSRA ?
4492     DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4493     DAG.getConstant(0, VT);
4494
4495   SDValue Tmp2, Tmp3;
4496   if (Op.getOpcode() == ISD::SHL_PARTS) {
4497     Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4498     Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4499   } else {
4500     Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4501     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4502   }
4503
4504   SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4505                                   DAG.getConstant(VTBits, MVT::i8));
4506   SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4507                                AndNode, DAG.getConstant(0, MVT::i8));
4508
4509   SDValue Hi, Lo;
4510   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4511   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4512   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4513
4514   if (Op.getOpcode() == ISD::SHL_PARTS) {
4515     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4516     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4517   } else {
4518     Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4519     Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4520   }
4521
4522   SDValue Ops[2] = { Lo, Hi };
4523   return DAG.getMergeValues(Ops, 2);
4524 }
4525
4526 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4527   MVT SrcVT = Op.getOperand(0).getValueType();
4528   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4529          "Unknown SINT_TO_FP to lower!");
4530   
4531   // These are really Legal; caller falls through into that case.
4532   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4533     return SDValue();
4534   if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 && 
4535       Subtarget->is64Bit())
4536     return SDValue();
4537   
4538   unsigned Size = SrcVT.getSizeInBits()/8;
4539   MachineFunction &MF = DAG.getMachineFunction();
4540   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4541   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4542   SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4543                                  StackSlot,
4544                                  PseudoSourceValue::getFixedStack(SSFI), 0);
4545
4546   // Build the FILD
4547   SDVTList Tys;
4548   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4549   if (useSSE)
4550     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4551   else
4552     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4553   SmallVector<SDValue, 8> Ops;
4554   Ops.push_back(Chain);
4555   Ops.push_back(StackSlot);
4556   Ops.push_back(DAG.getValueType(SrcVT));
4557   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4558                                  Tys, &Ops[0], Ops.size());
4559
4560   if (useSSE) {
4561     Chain = Result.getValue(1);
4562     SDValue InFlag = Result.getValue(2);
4563
4564     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4565     // shouldn't be necessary except that RFP cannot be live across
4566     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4567     MachineFunction &MF = DAG.getMachineFunction();
4568     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4569     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4570     Tys = DAG.getVTList(MVT::Other);
4571     SmallVector<SDValue, 8> Ops;
4572     Ops.push_back(Chain);
4573     Ops.push_back(Result);
4574     Ops.push_back(StackSlot);
4575     Ops.push_back(DAG.getValueType(Op.getValueType()));
4576     Ops.push_back(InFlag);
4577     Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4578     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4579                          PseudoSourceValue::getFixedStack(SSFI), 0);
4580   }
4581
4582   return Result;
4583 }
4584
4585 std::pair<SDValue,SDValue> X86TargetLowering::
4586 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4587   assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4588          Op.getValueType().getSimpleVT() >= MVT::i16 &&
4589          "Unknown FP_TO_SINT to lower!");
4590
4591   // These are really Legal.
4592   if (Op.getValueType() == MVT::i32 && 
4593       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4594     return std::make_pair(SDValue(), SDValue());
4595   if (Subtarget->is64Bit() &&
4596       Op.getValueType() == MVT::i64 &&
4597       Op.getOperand(0).getValueType() != MVT::f80)
4598     return std::make_pair(SDValue(), SDValue());
4599
4600   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4601   // stack slot.
4602   MachineFunction &MF = DAG.getMachineFunction();
4603   unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4604   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4605   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4606   unsigned Opc;
4607   switch (Op.getValueType().getSimpleVT()) {
4608   default: assert(0 && "Invalid FP_TO_SINT to lower!");
4609   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4610   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4611   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4612   }
4613
4614   SDValue Chain = DAG.getEntryNode();
4615   SDValue Value = Op.getOperand(0);
4616   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4617     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4618     Chain = DAG.getStore(Chain, Value, StackSlot,
4619                          PseudoSourceValue::getFixedStack(SSFI), 0);
4620     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4621     SDValue Ops[] = {
4622       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4623     };
4624     Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4625     Chain = Value.getValue(1);
4626     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4627     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4628   }
4629
4630   // Build the FP_TO_INT*_IN_MEM
4631   SDValue Ops[] = { Chain, Value, StackSlot };
4632   SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4633
4634   return std::make_pair(FIST, StackSlot);
4635 }
4636
4637 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4638   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4639   SDValue FIST = Vals.first, StackSlot = Vals.second;
4640   if (FIST.getNode() == 0) return SDValue();
4641   
4642   // Load the result.
4643   return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4644 }
4645
4646 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4647   std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4648   SDValue FIST = Vals.first, StackSlot = Vals.second;
4649   if (FIST.getNode() == 0) return 0;
4650
4651   MVT VT = N->getValueType(0);
4652
4653   // Return a load from the stack slot.
4654   SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4655
4656   // Use MERGE_VALUES to drop the chain result value and get a node with one
4657   // result.  This requires turning off getMergeValues simplification, since
4658   // otherwise it will give us Res back.
4659   return DAG.getMergeValues(&Res, 1, false).getNode();
4660 }
4661
4662 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4663   MVT VT = Op.getValueType();
4664   MVT EltVT = VT;
4665   if (VT.isVector())
4666     EltVT = VT.getVectorElementType();
4667   std::vector<Constant*> CV;
4668   if (EltVT == MVT::f64) {
4669     Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4670     CV.push_back(C);
4671     CV.push_back(C);
4672   } else {
4673     Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4674     CV.push_back(C);
4675     CV.push_back(C);
4676     CV.push_back(C);
4677     CV.push_back(C);
4678   }
4679   Constant *C = ConstantVector::get(CV);
4680   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4681   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4682                                PseudoSourceValue::getConstantPool(), 0,
4683                                false, 16);
4684   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4685 }
4686
4687 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4688   MVT VT = Op.getValueType();
4689   MVT EltVT = VT;
4690   unsigned EltNum = 1;
4691   if (VT.isVector()) {
4692     EltVT = VT.getVectorElementType();
4693     EltNum = VT.getVectorNumElements();
4694   }
4695   std::vector<Constant*> CV;
4696   if (EltVT == MVT::f64) {
4697     Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4698     CV.push_back(C);
4699     CV.push_back(C);
4700   } else {
4701     Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4702     CV.push_back(C);
4703     CV.push_back(C);
4704     CV.push_back(C);
4705     CV.push_back(C);
4706   }
4707   Constant *C = ConstantVector::get(CV);
4708   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4709   SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4710                                PseudoSourceValue::getConstantPool(), 0,
4711                                false, 16);
4712   if (VT.isVector()) {
4713     return DAG.getNode(ISD::BIT_CONVERT, VT,
4714                        DAG.getNode(ISD::XOR, MVT::v2i64,
4715                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4716                     DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4717   } else {
4718     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4719   }
4720 }
4721
4722 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4723   SDValue Op0 = Op.getOperand(0);
4724   SDValue Op1 = Op.getOperand(1);
4725   MVT VT = Op.getValueType();
4726   MVT SrcVT = Op1.getValueType();
4727
4728   // If second operand is smaller, extend it first.
4729   if (SrcVT.bitsLT(VT)) {
4730     Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4731     SrcVT = VT;
4732   }
4733   // And if it is bigger, shrink it first.
4734   if (SrcVT.bitsGT(VT)) {
4735     Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4736     SrcVT = VT;
4737   }
4738
4739   // At this point the operands and the result should have the same
4740   // type, and that won't be f80 since that is not custom lowered.
4741
4742   // First get the sign bit of second operand.
4743   std::vector<Constant*> CV;
4744   if (SrcVT == MVT::f64) {
4745     CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4746     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4747   } else {
4748     CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4749     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4750     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4751     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4752   }
4753   Constant *C = ConstantVector::get(CV);
4754   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4755   SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4756                                 PseudoSourceValue::getConstantPool(), 0,
4757                                 false, 16);
4758   SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4759
4760   // Shift sign bit right or left if the two operands have different types.
4761   if (SrcVT.bitsGT(VT)) {
4762     // Op0 is MVT::f32, Op1 is MVT::f64.
4763     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4764     SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4765                           DAG.getConstant(32, MVT::i32));
4766     SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4767     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4768                           DAG.getIntPtrConstant(0));
4769   }
4770
4771   // Clear first operand sign bit.
4772   CV.clear();
4773   if (VT == MVT::f64) {
4774     CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4775     CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4776   } else {
4777     CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4778     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4779     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4780     CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4781   }
4782   C = ConstantVector::get(CV);
4783   CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4784   SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4785                                 PseudoSourceValue::getConstantPool(), 0,
4786                                 false, 16);
4787   SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4788
4789   // Or the value with the sign bit.
4790   return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4791 }
4792
4793 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
4794   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4795   SDValue Cond;
4796   SDValue Op0 = Op.getOperand(0);
4797   SDValue Op1 = Op.getOperand(1);
4798   SDValue CC = Op.getOperand(2);
4799   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4800   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4801   unsigned X86CC;
4802
4803   if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4804                      Op0, Op1, DAG)) {
4805     Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4806     return DAG.getNode(X86ISD::SETCC, MVT::i8,
4807                        DAG.getConstant(X86CC, MVT::i8), Cond);
4808   }
4809
4810   assert(isFP && "Illegal integer SetCC!");
4811
4812   Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4813   switch (SetCCOpcode) {
4814   default: assert(false && "Illegal floating point SetCC!");
4815   case ISD::SETOEQ: {  // !PF & ZF
4816     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4817                                  DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4818     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4819                                  DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4820     return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4821   }
4822   case ISD::SETUNE: {  // PF | !ZF
4823     SDValue Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4824                                  DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4825     SDValue Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4826                                  DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4827     return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4828   }
4829   }
4830 }
4831
4832 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4833   SDValue Cond;
4834   SDValue Op0 = Op.getOperand(0);
4835   SDValue Op1 = Op.getOperand(1);
4836   SDValue CC = Op.getOperand(2);
4837   MVT VT = Op.getValueType();
4838   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4839   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
4840
4841   if (isFP) {
4842     unsigned SSECC = 8;
4843     MVT VT0 = Op0.getValueType();
4844     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
4845     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
4846     bool Swap = false;
4847
4848     switch (SetCCOpcode) {
4849     default: break;
4850     case ISD::SETOEQ:
4851     case ISD::SETEQ:  SSECC = 0; break;
4852     case ISD::SETOGT: 
4853     case ISD::SETGT: Swap = true; // Fallthrough
4854     case ISD::SETLT:
4855     case ISD::SETOLT: SSECC = 1; break;
4856     case ISD::SETOGE:
4857     case ISD::SETGE: Swap = true; // Fallthrough
4858     case ISD::SETLE:
4859     case ISD::SETOLE: SSECC = 2; break;
4860     case ISD::SETUO:  SSECC = 3; break;
4861     case ISD::SETUNE:
4862     case ISD::SETNE:  SSECC = 4; break;
4863     case ISD::SETULE: Swap = true;
4864     case ISD::SETUGE: SSECC = 5; break;
4865     case ISD::SETULT: Swap = true;
4866     case ISD::SETUGT: SSECC = 6; break;
4867     case ISD::SETO:   SSECC = 7; break;
4868     }
4869     if (Swap)
4870       std::swap(Op0, Op1);
4871
4872     // In the two special cases we can't handle, emit two comparisons.
4873     if (SSECC == 8) {
4874       if (SetCCOpcode == ISD::SETUEQ) {
4875         SDValue UNORD, EQ;
4876         UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
4877         EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
4878         return DAG.getNode(ISD::OR, VT, UNORD, EQ);
4879       }
4880       else if (SetCCOpcode == ISD::SETONE) {
4881         SDValue ORD, NEQ;
4882         ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
4883         NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
4884         return DAG.getNode(ISD::AND, VT, ORD, NEQ);
4885       }
4886       assert(0 && "Illegal FP comparison");
4887     }
4888     // Handle all other FP comparisons here.
4889     return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
4890   }
4891   
4892   // We are handling one of the integer comparisons here.  Since SSE only has
4893   // GT and EQ comparisons for integer, swapping operands and multiple
4894   // operations may be required for some comparisons.
4895   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
4896   bool Swap = false, Invert = false, FlipSigns = false;
4897   
4898   switch (VT.getSimpleVT()) {
4899   default: break;
4900   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
4901   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
4902   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
4903   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
4904   }
4905   
4906   switch (SetCCOpcode) {
4907   default: break;
4908   case ISD::SETNE:  Invert = true;
4909   case ISD::SETEQ:  Opc = EQOpc; break;
4910   case ISD::SETLT:  Swap = true;
4911   case ISD::SETGT:  Opc = GTOpc; break;
4912   case ISD::SETGE:  Swap = true;
4913   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
4914   case ISD::SETULT: Swap = true;
4915   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
4916   case ISD::SETUGE: Swap = true;
4917   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
4918   }
4919   if (Swap)
4920     std::swap(Op0, Op1);
4921   
4922   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
4923   // bits of the inputs before performing those operations.
4924   if (FlipSigns) {
4925     MVT EltVT = VT.getVectorElementType();
4926     SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
4927     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
4928     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
4929                                     SignBits.size());
4930     Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
4931     Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
4932   }
4933   
4934   SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
4935
4936   // If the logical-not of the result is required, perform that now.
4937   if (Invert) {
4938     MVT EltVT = VT.getVectorElementType();
4939     SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
4940     std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
4941     SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
4942                                     NegOnes.size());
4943     Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
4944   }
4945   return Result;
4946 }
4947
4948 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
4949   bool addTest = true;
4950   SDValue Cond  = Op.getOperand(0);
4951   SDValue CC;
4952
4953   if (Cond.getOpcode() == ISD::SETCC)
4954     Cond = LowerSETCC(Cond, DAG);
4955
4956   // If condition flag is set by a X86ISD::CMP, then use it as the condition
4957   // setting operand in place of the X86ISD::SETCC.
4958   if (Cond.getOpcode() == X86ISD::SETCC) {
4959     CC = Cond.getOperand(0);
4960
4961     SDValue Cmp = Cond.getOperand(1);
4962     unsigned Opc = Cmp.getOpcode();
4963     MVT VT = Op.getValueType();
4964     
4965     bool IllegalFPCMov = false;
4966     if (VT.isFloatingPoint() && !VT.isVector() &&
4967         !isScalarFPTypeInSSEReg(VT))  // FPStack?
4968       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4969     
4970     if ((Opc == X86ISD::CMP ||
4971          Opc == X86ISD::COMI ||
4972          Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4973       Cond = Cmp;
4974       addTest = false;
4975     }
4976   }
4977
4978   if (addTest) {
4979     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4980     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4981   }
4982
4983   const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4984                                                     MVT::Flag);
4985   SmallVector<SDValue, 4> Ops;
4986   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4987   // condition is true.
4988   Ops.push_back(Op.getOperand(2));
4989   Ops.push_back(Op.getOperand(1));
4990   Ops.push_back(CC);
4991   Ops.push_back(Cond);
4992   return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4993 }
4994
4995 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
4996   bool addTest = true;
4997   SDValue Chain = Op.getOperand(0);
4998   SDValue Cond  = Op.getOperand(1);
4999   SDValue Dest  = Op.getOperand(2);
5000   SDValue CC;
5001
5002   if (Cond.getOpcode() == ISD::SETCC)
5003     Cond = LowerSETCC(Cond, DAG);
5004
5005   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5006   // setting operand in place of the X86ISD::SETCC.
5007   if (Cond.getOpcode() == X86ISD::SETCC) {
5008     CC = Cond.getOperand(0);
5009
5010     SDValue Cmp = Cond.getOperand(1);
5011     unsigned Opc = Cmp.getOpcode();
5012     if (Opc == X86ISD::CMP ||
5013         Opc == X86ISD::COMI ||
5014         Opc == X86ISD::UCOMI) {
5015       Cond = Cmp;
5016       addTest = false;
5017     }
5018   }
5019
5020   if (addTest) {
5021     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5022     Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5023   }
5024   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5025                      Chain, Op.getOperand(2), CC, Cond);
5026 }
5027
5028
5029 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5030 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5031 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5032 // that the guard pages used by the OS virtual memory manager are allocated in
5033 // correct sequence.
5034 SDValue
5035 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5036                                            SelectionDAG &DAG) {
5037   assert(Subtarget->isTargetCygMing() &&
5038          "This should be used only on Cygwin/Mingw targets");
5039
5040   // Get the inputs.
5041   SDValue Chain = Op.getOperand(0);
5042   SDValue Size  = Op.getOperand(1);
5043   // FIXME: Ensure alignment here
5044
5045   SDValue Flag;
5046
5047   MVT IntPtr = getPointerTy();
5048   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5049
5050   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0));
5051
5052   Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5053   Flag = Chain.getValue(1);
5054
5055   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5056   SDValue Ops[] = { Chain,
5057                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
5058                       DAG.getRegister(X86::EAX, IntPtr),
5059                       DAG.getRegister(X86StackPtr, SPTy),
5060                       Flag };
5061   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5062   Flag = Chain.getValue(1);
5063
5064   Chain = DAG.getCALLSEQ_END(Chain,
5065                              DAG.getIntPtrConstant(0),
5066                              DAG.getIntPtrConstant(0),
5067                              Flag);
5068
5069   Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5070
5071   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5072   return DAG.getMergeValues(Ops1, 2);
5073 }
5074
5075 SDValue
5076 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5077                                         SDValue Chain,
5078                                         SDValue Dst, SDValue Src,
5079                                         SDValue Size, unsigned Align,
5080                                         const Value *DstSV, uint64_t DstSVOff) {
5081   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5082
5083   /// If not DWORD aligned or size is more than the threshold, call the library.
5084   /// The libc version is likely to be faster for these cases. It can use the
5085   /// address value and run time information about the CPU.
5086   if ((Align & 3) != 0 ||
5087       !ConstantSize ||
5088       ConstantSize->getZExtValue() >
5089         getSubtarget()->getMaxInlineSizeThreshold()) {
5090     SDValue InFlag(0, 0);
5091
5092     // Check to see if there is a specialized entry-point for memory zeroing.
5093     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5094     if (const char *bzeroEntry = 
5095           V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5096       MVT IntPtr = getPointerTy();
5097       const Type *IntPtrTy = TD->getIntPtrType();
5098       TargetLowering::ArgListTy Args; 
5099       TargetLowering::ArgListEntry Entry;
5100       Entry.Node = Dst;
5101       Entry.Ty = IntPtrTy;
5102       Args.push_back(Entry);
5103       Entry.Node = Size;
5104       Args.push_back(Entry);
5105       std::pair<SDValue,SDValue> CallResult =
5106         LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
5107                     false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
5108                     Args, DAG);
5109       return CallResult.second;
5110     }
5111
5112     // Otherwise have the target-independent code call memset.
5113     return SDValue();
5114   }
5115
5116   uint64_t SizeVal = ConstantSize->getZExtValue();
5117   SDValue InFlag(0, 0);
5118   MVT AVT;
5119   SDValue Count;
5120   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5121   unsigned BytesLeft = 0;
5122   bool TwoRepStos = false;
5123   if (ValC) {
5124     unsigned ValReg;
5125     uint64_t Val = ValC->getZExtValue() & 255;
5126
5127     // If the value is a constant, then we can potentially use larger sets.
5128     switch (Align & 3) {
5129     case 2:   // WORD aligned
5130       AVT = MVT::i16;
5131       ValReg = X86::AX;
5132       Val = (Val << 8) | Val;
5133       break;
5134     case 0:  // DWORD aligned
5135       AVT = MVT::i32;
5136       ValReg = X86::EAX;
5137       Val = (Val << 8)  | Val;
5138       Val = (Val << 16) | Val;
5139       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5140         AVT = MVT::i64;
5141         ValReg = X86::RAX;
5142         Val = (Val << 32) | Val;
5143       }
5144       break;
5145     default:  // Byte aligned
5146       AVT = MVT::i8;
5147       ValReg = X86::AL;
5148       Count = DAG.getIntPtrConstant(SizeVal);
5149       break;
5150     }
5151
5152     if (AVT.bitsGT(MVT::i8)) {
5153       unsigned UBytes = AVT.getSizeInBits() / 8;
5154       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5155       BytesLeft = SizeVal % UBytes;
5156     }
5157
5158     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5159                               InFlag);
5160     InFlag = Chain.getValue(1);
5161   } else {
5162     AVT = MVT::i8;
5163     Count  = DAG.getIntPtrConstant(SizeVal);
5164     Chain  = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5165     InFlag = Chain.getValue(1);
5166   }
5167
5168   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5169                             Count, InFlag);
5170   InFlag = Chain.getValue(1);
5171   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5172                             Dst, InFlag);
5173   InFlag = Chain.getValue(1);
5174
5175   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5176   SmallVector<SDValue, 8> Ops;
5177   Ops.push_back(Chain);
5178   Ops.push_back(DAG.getValueType(AVT));
5179   Ops.push_back(InFlag);
5180   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5181
5182   if (TwoRepStos) {
5183     InFlag = Chain.getValue(1);
5184     Count  = Size;
5185     MVT CVT = Count.getValueType();
5186     SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5187                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5188     Chain  = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5189                               Left, InFlag);
5190     InFlag = Chain.getValue(1);
5191     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5192     Ops.clear();
5193     Ops.push_back(Chain);
5194     Ops.push_back(DAG.getValueType(MVT::i8));
5195     Ops.push_back(InFlag);
5196     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5197   } else if (BytesLeft) {
5198     // Handle the last 1 - 7 bytes.
5199     unsigned Offset = SizeVal - BytesLeft;
5200     MVT AddrVT = Dst.getValueType();
5201     MVT SizeVT = Size.getValueType();
5202
5203     Chain = DAG.getMemset(Chain,
5204                           DAG.getNode(ISD::ADD, AddrVT, Dst,
5205                                       DAG.getConstant(Offset, AddrVT)),
5206                           Src,
5207                           DAG.getConstant(BytesLeft, SizeVT),
5208                           Align, DstSV, DstSVOff + Offset);
5209   }
5210
5211   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5212   return Chain;
5213 }
5214
5215 SDValue
5216 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5217                                       SDValue Chain, SDValue Dst, SDValue Src,
5218                                       SDValue Size, unsigned Align,
5219                                       bool AlwaysInline,
5220                                       const Value *DstSV, uint64_t DstSVOff,
5221                                       const Value *SrcSV, uint64_t SrcSVOff) {  
5222   // This requires the copy size to be a constant, preferrably
5223   // within a subtarget-specific limit.
5224   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5225   if (!ConstantSize)
5226     return SDValue();
5227   uint64_t SizeVal = ConstantSize->getZExtValue();
5228   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5229     return SDValue();
5230
5231   /// If not DWORD aligned, call the library.
5232   if ((Align & 3) != 0)
5233     return SDValue();
5234
5235   // DWORD aligned
5236   MVT AVT = MVT::i32;
5237   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5238     AVT = MVT::i64;
5239
5240   unsigned UBytes = AVT.getSizeInBits() / 8;
5241   unsigned CountVal = SizeVal / UBytes;
5242   SDValue Count = DAG.getIntPtrConstant(CountVal);
5243   unsigned BytesLeft = SizeVal % UBytes;
5244
5245   SDValue InFlag(0, 0);
5246   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5247                             Count, InFlag);
5248   InFlag = Chain.getValue(1);
5249   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5250                             Dst, InFlag);
5251   InFlag = Chain.getValue(1);
5252   Chain  = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5253                             Src, InFlag);
5254   InFlag = Chain.getValue(1);
5255
5256   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5257   SmallVector<SDValue, 8> Ops;
5258   Ops.push_back(Chain);
5259   Ops.push_back(DAG.getValueType(AVT));
5260   Ops.push_back(InFlag);
5261   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5262
5263   SmallVector<SDValue, 4> Results;
5264   Results.push_back(RepMovs);
5265   if (BytesLeft) {
5266     // Handle the last 1 - 7 bytes.
5267     unsigned Offset = SizeVal - BytesLeft;
5268     MVT DstVT = Dst.getValueType();
5269     MVT SrcVT = Src.getValueType();
5270     MVT SizeVT = Size.getValueType();
5271     Results.push_back(DAG.getMemcpy(Chain,
5272                                     DAG.getNode(ISD::ADD, DstVT, Dst,
5273                                                 DAG.getConstant(Offset, DstVT)),
5274                                     DAG.getNode(ISD::ADD, SrcVT, Src,
5275                                                 DAG.getConstant(Offset, SrcVT)),
5276                                     DAG.getConstant(BytesLeft, SizeVT),
5277                                     Align, AlwaysInline,
5278                                     DstSV, DstSVOff + Offset,
5279                                     SrcSV, SrcSVOff + Offset));
5280   }
5281
5282   return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5283 }
5284
5285 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5286 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5287   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5288   SDValue TheChain = N->getOperand(0);
5289   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5290   if (Subtarget->is64Bit()) {
5291     SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5292     SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5293                                        MVT::i64, rax.getValue(2));
5294     SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5295                                 DAG.getConstant(32, MVT::i8));
5296     SDValue Ops[] = {
5297       DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5298     };
5299     
5300     return DAG.getMergeValues(Ops, 2).getNode();
5301   }
5302   
5303   SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5304   SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5305                                        MVT::i32, eax.getValue(2));
5306   // Use a buildpair to merge the two 32-bit values into a 64-bit one. 
5307   SDValue Ops[] = { eax, edx };
5308   Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5309
5310   // Use a MERGE_VALUES to return the value and chain.
5311   Ops[1] = edx.getValue(1);
5312   return DAG.getMergeValues(Ops, 2).getNode();
5313 }
5314
5315 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5316   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5317
5318   if (!Subtarget->is64Bit()) {
5319     // vastart just stores the address of the VarArgsFrameIndex slot into the
5320     // memory location argument.
5321     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5322     return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5323   }
5324
5325   // __va_list_tag:
5326   //   gp_offset         (0 - 6 * 8)
5327   //   fp_offset         (48 - 48 + 8 * 16)
5328   //   overflow_arg_area (point to parameters coming in memory).
5329   //   reg_save_area
5330   SmallVector<SDValue, 8> MemOps;
5331   SDValue FIN = Op.getOperand(1);
5332   // Store gp_offset
5333   SDValue Store = DAG.getStore(Op.getOperand(0),
5334                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
5335                                  FIN, SV, 0);
5336   MemOps.push_back(Store);
5337
5338   // Store fp_offset
5339   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5340   Store = DAG.getStore(Op.getOperand(0),
5341                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
5342                        FIN, SV, 0);
5343   MemOps.push_back(Store);
5344
5345   // Store ptr to overflow_arg_area
5346   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5347   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5348   Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5349   MemOps.push_back(Store);
5350
5351   // Store ptr to reg_save_area.
5352   FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5353   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5354   Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5355   MemOps.push_back(Store);
5356   return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5357 }
5358
5359 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5360   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5361   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5362   SDValue Chain = Op.getOperand(0);
5363   SDValue SrcPtr = Op.getOperand(1);
5364   SDValue SrcSV = Op.getOperand(2);
5365
5366   assert(0 && "VAArgInst is not yet implemented for x86-64!");
5367   abort();
5368   return SDValue();
5369 }
5370
5371 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5372   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5373   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5374   SDValue Chain = Op.getOperand(0);
5375   SDValue DstPtr = Op.getOperand(1);
5376   SDValue SrcPtr = Op.getOperand(2);
5377   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5378   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5379
5380   return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5381                        DAG.getIntPtrConstant(24), 8, false,
5382                        DstSV, 0, SrcSV, 0);
5383 }
5384
5385 SDValue
5386 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5387   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5388   switch (IntNo) {
5389   default: return SDValue();    // Don't custom lower most intrinsics.
5390   // Comparison intrinsics.
5391   case Intrinsic::x86_sse_comieq_ss:
5392   case Intrinsic::x86_sse_comilt_ss:
5393   case Intrinsic::x86_sse_comile_ss:
5394   case Intrinsic::x86_sse_comigt_ss:
5395   case Intrinsic::x86_sse_comige_ss:
5396   case Intrinsic::x86_sse_comineq_ss:
5397   case Intrinsic::x86_sse_ucomieq_ss:
5398   case Intrinsic::x86_sse_ucomilt_ss:
5399   case Intrinsic::x86_sse_ucomile_ss:
5400   case Intrinsic::x86_sse_ucomigt_ss:
5401   case Intrinsic::x86_sse_ucomige_ss:
5402   case Intrinsic::x86_sse_ucomineq_ss:
5403   case Intrinsic::x86_sse2_comieq_sd:
5404   case Intrinsic::x86_sse2_comilt_sd:
5405   case Intrinsic::x86_sse2_comile_sd:
5406   case Intrinsic::x86_sse2_comigt_sd:
5407   case Intrinsic::x86_sse2_comige_sd:
5408   case Intrinsic::x86_sse2_comineq_sd:
5409   case Intrinsic::x86_sse2_ucomieq_sd:
5410   case Intrinsic::x86_sse2_ucomilt_sd:
5411   case Intrinsic::x86_sse2_ucomile_sd:
5412   case Intrinsic::x86_sse2_ucomigt_sd:
5413   case Intrinsic::x86_sse2_ucomige_sd:
5414   case Intrinsic::x86_sse2_ucomineq_sd: {
5415     unsigned Opc = 0;
5416     ISD::CondCode CC = ISD::SETCC_INVALID;
5417     switch (IntNo) {
5418     default: break;
5419     case Intrinsic::x86_sse_comieq_ss:
5420     case Intrinsic::x86_sse2_comieq_sd:
5421       Opc = X86ISD::COMI;
5422       CC = ISD::SETEQ;
5423       break;
5424     case Intrinsic::x86_sse_comilt_ss:
5425     case Intrinsic::x86_sse2_comilt_sd:
5426       Opc = X86ISD::COMI;
5427       CC = ISD::SETLT;
5428       break;
5429     case Intrinsic::x86_sse_comile_ss:
5430     case Intrinsic::x86_sse2_comile_sd:
5431       Opc = X86ISD::COMI;
5432       CC = ISD::SETLE;
5433       break;
5434     case Intrinsic::x86_sse_comigt_ss:
5435     case Intrinsic::x86_sse2_comigt_sd:
5436       Opc = X86ISD::COMI;
5437       CC = ISD::SETGT;
5438       break;
5439     case Intrinsic::x86_sse_comige_ss:
5440     case Intrinsic::x86_sse2_comige_sd:
5441       Opc = X86ISD::COMI;
5442       CC = ISD::SETGE;
5443       break;
5444     case Intrinsic::x86_sse_comineq_ss:
5445     case Intrinsic::x86_sse2_comineq_sd:
5446       Opc = X86ISD::COMI;
5447       CC = ISD::SETNE;
5448       break;
5449     case Intrinsic::x86_sse_ucomieq_ss:
5450     case Intrinsic::x86_sse2_ucomieq_sd:
5451       Opc = X86ISD::UCOMI;
5452       CC = ISD::SETEQ;
5453       break;
5454     case Intrinsic::x86_sse_ucomilt_ss:
5455     case Intrinsic::x86_sse2_ucomilt_sd:
5456       Opc = X86ISD::UCOMI;
5457       CC = ISD::SETLT;
5458       break;
5459     case Intrinsic::x86_sse_ucomile_ss:
5460     case Intrinsic::x86_sse2_ucomile_sd:
5461       Opc = X86ISD::UCOMI;
5462       CC = ISD::SETLE;
5463       break;
5464     case Intrinsic::x86_sse_ucomigt_ss:
5465     case Intrinsic::x86_sse2_ucomigt_sd:
5466       Opc = X86ISD::UCOMI;
5467       CC = ISD::SETGT;
5468       break;
5469     case Intrinsic::x86_sse_ucomige_ss:
5470     case Intrinsic::x86_sse2_ucomige_sd:
5471       Opc = X86ISD::UCOMI;
5472       CC = ISD::SETGE;
5473       break;
5474     case Intrinsic::x86_sse_ucomineq_ss:
5475     case Intrinsic::x86_sse2_ucomineq_sd:
5476       Opc = X86ISD::UCOMI;
5477       CC = ISD::SETNE;
5478       break;
5479     }
5480
5481     unsigned X86CC;
5482     SDValue LHS = Op.getOperand(1);
5483     SDValue RHS = Op.getOperand(2);
5484     translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5485
5486     SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5487     SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5488                                 DAG.getConstant(X86CC, MVT::i8), Cond);
5489     return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5490   }
5491
5492   // Fix vector shift instructions where the last operand is a non-immediate
5493   // i32 value.
5494   case Intrinsic::x86_sse2_pslli_w:
5495   case Intrinsic::x86_sse2_pslli_d:
5496   case Intrinsic::x86_sse2_pslli_q:
5497   case Intrinsic::x86_sse2_psrli_w:
5498   case Intrinsic::x86_sse2_psrli_d:
5499   case Intrinsic::x86_sse2_psrli_q:
5500   case Intrinsic::x86_sse2_psrai_w:
5501   case Intrinsic::x86_sse2_psrai_d:
5502   case Intrinsic::x86_mmx_pslli_w:
5503   case Intrinsic::x86_mmx_pslli_d:
5504   case Intrinsic::x86_mmx_pslli_q:
5505   case Intrinsic::x86_mmx_psrli_w:
5506   case Intrinsic::x86_mmx_psrli_d:
5507   case Intrinsic::x86_mmx_psrli_q:
5508   case Intrinsic::x86_mmx_psrai_w:
5509   case Intrinsic::x86_mmx_psrai_d: {
5510     SDValue ShAmt = Op.getOperand(2);
5511     if (isa<ConstantSDNode>(ShAmt))
5512       return SDValue();
5513
5514     unsigned NewIntNo = 0;
5515     MVT ShAmtVT = MVT::v4i32;
5516     switch (IntNo) {
5517     case Intrinsic::x86_sse2_pslli_w:
5518       NewIntNo = Intrinsic::x86_sse2_psll_w;
5519       break;
5520     case Intrinsic::x86_sse2_pslli_d:
5521       NewIntNo = Intrinsic::x86_sse2_psll_d;
5522       break;
5523     case Intrinsic::x86_sse2_pslli_q:
5524       NewIntNo = Intrinsic::x86_sse2_psll_q;
5525       break;
5526     case Intrinsic::x86_sse2_psrli_w:
5527       NewIntNo = Intrinsic::x86_sse2_psrl_w;
5528       break;
5529     case Intrinsic::x86_sse2_psrli_d:
5530       NewIntNo = Intrinsic::x86_sse2_psrl_d;
5531       break;
5532     case Intrinsic::x86_sse2_psrli_q:
5533       NewIntNo = Intrinsic::x86_sse2_psrl_q;
5534       break;
5535     case Intrinsic::x86_sse2_psrai_w:
5536       NewIntNo = Intrinsic::x86_sse2_psra_w;
5537       break;
5538     case Intrinsic::x86_sse2_psrai_d:
5539       NewIntNo = Intrinsic::x86_sse2_psra_d;
5540       break;
5541     default: {
5542       ShAmtVT = MVT::v2i32;
5543       switch (IntNo) {
5544       case Intrinsic::x86_mmx_pslli_w:
5545         NewIntNo = Intrinsic::x86_mmx_psll_w;
5546         break;
5547       case Intrinsic::x86_mmx_pslli_d:
5548         NewIntNo = Intrinsic::x86_mmx_psll_d;
5549         break;
5550       case Intrinsic::x86_mmx_pslli_q:
5551         NewIntNo = Intrinsic::x86_mmx_psll_q;
5552         break;
5553       case Intrinsic::x86_mmx_psrli_w:
5554         NewIntNo = Intrinsic::x86_mmx_psrl_w;
5555         break;
5556       case Intrinsic::x86_mmx_psrli_d:
5557         NewIntNo = Intrinsic::x86_mmx_psrl_d;
5558         break;
5559       case Intrinsic::x86_mmx_psrli_q:
5560         NewIntNo = Intrinsic::x86_mmx_psrl_q;
5561         break;
5562       case Intrinsic::x86_mmx_psrai_w:
5563         NewIntNo = Intrinsic::x86_mmx_psra_w;
5564         break;
5565       case Intrinsic::x86_mmx_psrai_d:
5566         NewIntNo = Intrinsic::x86_mmx_psra_d;
5567         break;
5568       default: abort();  // Can't reach here.
5569       }
5570       break;
5571     }
5572     }
5573     MVT VT = Op.getValueType();
5574     ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5575                         DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5576     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5577                        DAG.getConstant(NewIntNo, MVT::i32),
5578                        Op.getOperand(1), ShAmt);
5579   }
5580   }
5581 }
5582
5583 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5584   // Depths > 0 not supported yet!
5585   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5586     return SDValue();
5587   
5588   // Just load the return address
5589   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5590   return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5591 }
5592
5593 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5594   // Depths > 0 not supported yet!
5595   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5596     return SDValue();
5597
5598   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5599   return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5600                      DAG.getIntPtrConstant(TD->getPointerSize()));
5601 }
5602
5603 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5604                                                      SelectionDAG &DAG) {
5605   return DAG.getIntPtrConstant(2*TD->getPointerSize());
5606 }
5607
5608 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5609 {
5610   MachineFunction &MF = DAG.getMachineFunction();
5611   SDValue Chain     = Op.getOperand(0);
5612   SDValue Offset    = Op.getOperand(1);
5613   SDValue Handler   = Op.getOperand(2);
5614
5615   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5616                                   getPointerTy());
5617   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5618
5619   SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5620                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
5621   StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5622   Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5623   Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5624   MF.getRegInfo().addLiveOut(StoreAddrReg);
5625
5626   return DAG.getNode(X86ISD::EH_RETURN,
5627                      MVT::Other,
5628                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5629 }
5630
5631 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5632                                              SelectionDAG &DAG) {
5633   SDValue Root = Op.getOperand(0);
5634   SDValue Trmp = Op.getOperand(1); // trampoline
5635   SDValue FPtr = Op.getOperand(2); // nested function
5636   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5637
5638   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5639
5640   const X86InstrInfo *TII =
5641     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5642
5643   if (Subtarget->is64Bit()) {
5644     SDValue OutChains[6];
5645
5646     // Large code-model.
5647
5648     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
5649     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5650
5651     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5652     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5653
5654     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5655
5656     // Load the pointer to the nested function into R11.
5657     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5658     SDValue Addr = Trmp;
5659     OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5660                                 TrmpAddr, 0);
5661
5662     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5663     OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5664
5665     // Load the 'nest' parameter value into R10.
5666     // R10 is specified in X86CallingConv.td
5667     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5668     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5669     OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5670                                 TrmpAddr, 10);
5671
5672     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5673     OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5674
5675     // Jump to the nested function.
5676     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5677     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5678     OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5679                                 TrmpAddr, 20);
5680
5681     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5682     Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5683     OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5684                                 TrmpAddr, 22);
5685
5686     SDValue Ops[] =
5687       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5688     return DAG.getMergeValues(Ops, 2);
5689   } else {
5690     const Function *Func =
5691       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5692     unsigned CC = Func->getCallingConv();
5693     unsigned NestReg;
5694
5695     switch (CC) {
5696     default:
5697       assert(0 && "Unsupported calling convention");
5698     case CallingConv::C:
5699     case CallingConv::X86_StdCall: {
5700       // Pass 'nest' parameter in ECX.
5701       // Must be kept in sync with X86CallingConv.td
5702       NestReg = X86::ECX;
5703
5704       // Check that ECX wasn't needed by an 'inreg' parameter.
5705       const FunctionType *FTy = Func->getFunctionType();
5706       const PAListPtr &Attrs = Func->getParamAttrs();
5707
5708       if (!Attrs.isEmpty() && !Func->isVarArg()) {
5709         unsigned InRegCount = 0;
5710         unsigned Idx = 1;
5711
5712         for (FunctionType::param_iterator I = FTy->param_begin(),
5713              E = FTy->param_end(); I != E; ++I, ++Idx)
5714           if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5715             // FIXME: should only count parameters that are lowered to integers.
5716             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5717
5718         if (InRegCount > 2) {
5719           cerr << "Nest register in use - reduce number of inreg parameters!\n";
5720           abort();
5721         }
5722       }
5723       break;
5724     }
5725     case CallingConv::X86_FastCall:
5726     case CallingConv::Fast:
5727       // Pass 'nest' parameter in EAX.
5728       // Must be kept in sync with X86CallingConv.td
5729       NestReg = X86::EAX;
5730       break;
5731     }
5732
5733     SDValue OutChains[4];
5734     SDValue Addr, Disp;
5735
5736     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5737     Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5738
5739     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5740     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5741     OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5742                                 Trmp, TrmpAddr, 0);
5743
5744     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5745     OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5746
5747     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5748     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5749     OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5750                                 TrmpAddr, 5, false, 1);
5751
5752     Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5753     OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5754
5755     SDValue Ops[] =
5756       { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5757     return DAG.getMergeValues(Ops, 2);
5758   }
5759 }
5760
5761 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
5762   /*
5763    The rounding mode is in bits 11:10 of FPSR, and has the following
5764    settings:
5765      00 Round to nearest
5766      01 Round to -inf
5767      10 Round to +inf
5768      11 Round to 0
5769
5770   FLT_ROUNDS, on the other hand, expects the following:
5771     -1 Undefined
5772      0 Round to 0
5773      1 Round to nearest
5774      2 Round to +inf
5775      3 Round to -inf
5776
5777   To perform the conversion, we do:
5778     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5779   */
5780
5781   MachineFunction &MF = DAG.getMachineFunction();
5782   const TargetMachine &TM = MF.getTarget();
5783   const TargetFrameInfo &TFI = *TM.getFrameInfo();
5784   unsigned StackAlignment = TFI.getStackAlignment();
5785   MVT VT = Op.getValueType();
5786
5787   // Save FP Control Word to stack slot
5788   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5789   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5790
5791   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5792                                 DAG.getEntryNode(), StackSlot);
5793
5794   // Load FP Control Word from stack slot
5795   SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5796
5797   // Transform as necessary
5798   SDValue CWD1 =
5799     DAG.getNode(ISD::SRL, MVT::i16,
5800                 DAG.getNode(ISD::AND, MVT::i16,
5801                             CWD, DAG.getConstant(0x800, MVT::i16)),
5802                 DAG.getConstant(11, MVT::i8));
5803   SDValue CWD2 =
5804     DAG.getNode(ISD::SRL, MVT::i16,
5805                 DAG.getNode(ISD::AND, MVT::i16,
5806                             CWD, DAG.getConstant(0x400, MVT::i16)),
5807                 DAG.getConstant(9, MVT::i8));
5808
5809   SDValue RetVal =
5810     DAG.getNode(ISD::AND, MVT::i16,
5811                 DAG.getNode(ISD::ADD, MVT::i16,
5812                             DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5813                             DAG.getConstant(1, MVT::i16)),
5814                 DAG.getConstant(3, MVT::i16));
5815
5816
5817   return DAG.getNode((VT.getSizeInBits() < 16 ?
5818                       ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5819 }
5820
5821 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
5822   MVT VT = Op.getValueType();
5823   MVT OpVT = VT;
5824   unsigned NumBits = VT.getSizeInBits();
5825
5826   Op = Op.getOperand(0);
5827   if (VT == MVT::i8) {
5828     // Zero extend to i32 since there is not an i8 bsr.
5829     OpVT = MVT::i32;
5830     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5831   }
5832
5833   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5834   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5835   Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5836
5837   // If src is zero (i.e. bsr sets ZF), returns NumBits.
5838   SmallVector<SDValue, 4> Ops;
5839   Ops.push_back(Op);
5840   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5841   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5842   Ops.push_back(Op.getValue(1));
5843   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5844
5845   // Finally xor with NumBits-1.
5846   Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5847
5848   if (VT == MVT::i8)
5849     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5850   return Op;
5851 }
5852
5853 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
5854   MVT VT = Op.getValueType();
5855   MVT OpVT = VT;
5856   unsigned NumBits = VT.getSizeInBits();
5857
5858   Op = Op.getOperand(0);
5859   if (VT == MVT::i8) {
5860     OpVT = MVT::i32;
5861     Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5862   }
5863
5864   // Issue a bsf (scan bits forward) which also sets EFLAGS.
5865   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5866   Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5867
5868   // If src is zero (i.e. bsf sets ZF), returns NumBits.
5869   SmallVector<SDValue, 4> Ops;
5870   Ops.push_back(Op);
5871   Ops.push_back(DAG.getConstant(NumBits, OpVT));
5872   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5873   Ops.push_back(Op.getValue(1));
5874   Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5875
5876   if (VT == MVT::i8)
5877     Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5878   return Op;
5879 }
5880
5881 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
5882   MVT T = Op.getValueType();
5883   unsigned Reg = 0;
5884   unsigned size = 0;
5885   switch(T.getSimpleVT()) {
5886   default:
5887     assert(false && "Invalid value type!");
5888   case MVT::i8:  Reg = X86::AL;  size = 1; break;
5889   case MVT::i16: Reg = X86::AX;  size = 2; break;
5890   case MVT::i32: Reg = X86::EAX; size = 4; break;
5891   case MVT::i64: 
5892     if (Subtarget->is64Bit()) {
5893       Reg = X86::RAX; size = 8;
5894     } else //Should go away when LowerType stuff lands
5895       return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
5896     break;
5897   };
5898   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5899                                     Op.getOperand(2), SDValue());
5900   SDValue Ops[] = { cpIn.getValue(0),
5901                       Op.getOperand(1),
5902                       Op.getOperand(3),
5903                       DAG.getTargetConstant(size, MVT::i8),
5904                       cpIn.getValue(1) };
5905   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5906   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5907   SDValue cpOut = 
5908     DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5909   return cpOut;
5910 }
5911
5912 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
5913                                                  SelectionDAG &DAG) {
5914   MVT T = Op->getValueType(0);
5915   assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
5916   SDValue cpInL, cpInH;
5917   cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5918                       DAG.getConstant(0, MVT::i32));
5919   cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5920                       DAG.getConstant(1, MVT::i32));
5921   cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5922                            cpInL, SDValue());
5923   cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5924                            cpInH, cpInL.getValue(1));
5925   SDValue swapInL, swapInH;
5926   swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5927                         DAG.getConstant(0, MVT::i32));
5928   swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5929                         DAG.getConstant(1, MVT::i32));
5930   swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5931                              swapInL, cpInH.getValue(1));
5932   swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5933                              swapInH, swapInL.getValue(1));
5934   SDValue Ops[] = { swapInH.getValue(0),
5935                       Op->getOperand(1),
5936                       swapInH.getValue(1)};
5937   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5938   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5939   SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32, 
5940                                         Result.getValue(1));
5941   SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32, 
5942                                         cpOutL.getValue(2));
5943   SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5944   SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5945   SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
5946   return DAG.getMergeValues(Vals, 2).getNode();
5947 }
5948
5949 SDNode* X86TargetLowering::ExpandATOMIC_LOAD_SUB(SDNode* Op,
5950                                                  SelectionDAG &DAG) {
5951   MVT T = Op->getValueType(0);
5952   SDValue negOp = DAG.getNode(ISD::SUB, T,
5953                                 DAG.getConstant(0, T), Op->getOperand(2));
5954   return DAG.getAtomic((T==MVT::i8 ? ISD::ATOMIC_LOAD_ADD_8:
5955                         T==MVT::i16 ? ISD::ATOMIC_LOAD_ADD_16:
5956                         T==MVT::i32 ? ISD::ATOMIC_LOAD_ADD_32:
5957                         T==MVT::i64 ? ISD::ATOMIC_LOAD_ADD_64: 0),
5958                        Op->getOperand(0), Op->getOperand(1), negOp,
5959                        cast<AtomicSDNode>(Op)->getSrcValue(),
5960                        cast<AtomicSDNode>(Op)->getAlignment()).getNode();
5961 }
5962
5963 /// LowerOperation - Provide custom lowering hooks for some operations.
5964 ///
5965 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5966   switch (Op.getOpcode()) {
5967   default: assert(0 && "Should not custom lower this!");
5968   case ISD::ATOMIC_CMP_SWAP_8:  return LowerCMP_SWAP(Op,DAG);
5969   case ISD::ATOMIC_CMP_SWAP_16: return LowerCMP_SWAP(Op,DAG);
5970   case ISD::ATOMIC_CMP_SWAP_32: return LowerCMP_SWAP(Op,DAG);
5971   case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
5972   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
5973   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
5974   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5975   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
5976   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
5977   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
5978   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
5979   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
5980   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
5981   case ISD::SHL_PARTS:
5982   case ISD::SRA_PARTS:
5983   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
5984   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
5985   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
5986   case ISD::FABS:               return LowerFABS(Op, DAG);
5987   case ISD::FNEG:               return LowerFNEG(Op, DAG);
5988   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
5989   case ISD::SETCC:              return LowerSETCC(Op, DAG);
5990   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
5991   case ISD::SELECT:             return LowerSELECT(Op, DAG);
5992   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
5993   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
5994   case ISD::CALL:               return LowerCALL(Op, DAG);
5995   case ISD::RET:                return LowerRET(Op, DAG);
5996   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
5997   case ISD::VASTART:            return LowerVASTART(Op, DAG);
5998   case ISD::VAARG:              return LowerVAARG(Op, DAG);
5999   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6000   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6001   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6002   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6003   case ISD::FRAME_TO_ARGS_OFFSET:
6004                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6005   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6006   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6007   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6008   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6009   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6010   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6011       
6012   // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6013   case ISD::READCYCLECOUNTER:
6014     return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6015   }
6016 }
6017
6018 /// ReplaceNodeResults - Replace a node with an illegal result type
6019 /// with a new node built out of custom code.
6020 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6021   switch (N->getOpcode()) {
6022   default: assert(0 && "Should not custom lower this!");
6023   case ISD::FP_TO_SINT:         return ExpandFP_TO_SINT(N, DAG);
6024   case ISD::READCYCLECOUNTER:   return ExpandREADCYCLECOUNTER(N, DAG);
6025   case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6026   case ISD::ATOMIC_LOAD_SUB_8:  return ExpandATOMIC_LOAD_SUB(N,DAG);
6027   case ISD::ATOMIC_LOAD_SUB_16: return ExpandATOMIC_LOAD_SUB(N,DAG);
6028   case ISD::ATOMIC_LOAD_SUB_32: return ExpandATOMIC_LOAD_SUB(N,DAG);
6029   case ISD::ATOMIC_LOAD_SUB_64: return ExpandATOMIC_LOAD_SUB(N,DAG);
6030   }
6031 }
6032
6033 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6034   switch (Opcode) {
6035   default: return NULL;
6036   case X86ISD::BSF:                return "X86ISD::BSF";
6037   case X86ISD::BSR:                return "X86ISD::BSR";
6038   case X86ISD::SHLD:               return "X86ISD::SHLD";
6039   case X86ISD::SHRD:               return "X86ISD::SHRD";
6040   case X86ISD::FAND:               return "X86ISD::FAND";
6041   case X86ISD::FOR:                return "X86ISD::FOR";
6042   case X86ISD::FXOR:               return "X86ISD::FXOR";
6043   case X86ISD::FSRL:               return "X86ISD::FSRL";
6044   case X86ISD::FILD:               return "X86ISD::FILD";
6045   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6046   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6047   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6048   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6049   case X86ISD::FLD:                return "X86ISD::FLD";
6050   case X86ISD::FST:                return "X86ISD::FST";
6051   case X86ISD::CALL:               return "X86ISD::CALL";
6052   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6053   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6054   case X86ISD::CMP:                return "X86ISD::CMP";
6055   case X86ISD::COMI:               return "X86ISD::COMI";
6056   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6057   case X86ISD::SETCC:              return "X86ISD::SETCC";
6058   case X86ISD::CMOV:               return "X86ISD::CMOV";
6059   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
6060   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
6061   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
6062   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
6063   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
6064   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
6065   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
6066   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
6067   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
6068   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
6069   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
6070   case X86ISD::FMAX:               return "X86ISD::FMAX";
6071   case X86ISD::FMIN:               return "X86ISD::FMIN";
6072   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
6073   case X86ISD::FRCP:               return "X86ISD::FRCP";
6074   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
6075   case X86ISD::THREAD_POINTER:     return "X86ISD::THREAD_POINTER";
6076   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
6077   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
6078   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
6079   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
6080   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
6081   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
6082   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
6083   case X86ISD::VSHL:               return "X86ISD::VSHL";
6084   case X86ISD::VSRL:               return "X86ISD::VSRL";
6085   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
6086   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
6087   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
6088   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
6089   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
6090   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
6091   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
6092   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
6093   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
6094   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
6095   }
6096 }
6097
6098 // isLegalAddressingMode - Return true if the addressing mode represented
6099 // by AM is legal for this target, for a load/store of the specified type.
6100 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM, 
6101                                               const Type *Ty) const {
6102   // X86 supports extremely general addressing modes.
6103   
6104   // X86 allows a sign-extended 32-bit immediate field as a displacement.
6105   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6106     return false;
6107   
6108   if (AM.BaseGV) {
6109     // We can only fold this if we don't need an extra load.
6110     if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6111       return false;
6112
6113     // X86-64 only supports addr of globals in small code model.
6114     if (Subtarget->is64Bit()) {
6115       if (getTargetMachine().getCodeModel() != CodeModel::Small)
6116         return false;
6117       // If lower 4G is not available, then we must use rip-relative addressing.
6118       if (AM.BaseOffs || AM.Scale > 1)
6119         return false;
6120     }
6121   }
6122   
6123   switch (AM.Scale) {
6124   case 0:
6125   case 1:
6126   case 2:
6127   case 4:
6128   case 8:
6129     // These scales always work.
6130     break;
6131   case 3:
6132   case 5:
6133   case 9:
6134     // These scales are formed with basereg+scalereg.  Only accept if there is
6135     // no basereg yet.
6136     if (AM.HasBaseReg)
6137       return false;
6138     break;
6139   default:  // Other stuff never works.
6140     return false;
6141   }
6142   
6143   return true;
6144 }
6145
6146
6147 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6148   if (!Ty1->isInteger() || !Ty2->isInteger())
6149     return false;
6150   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6151   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6152   if (NumBits1 <= NumBits2)
6153     return false;
6154   return Subtarget->is64Bit() || NumBits1 < 64;
6155 }
6156
6157 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6158   if (!VT1.isInteger() || !VT2.isInteger())
6159     return false;
6160   unsigned NumBits1 = VT1.getSizeInBits();
6161   unsigned NumBits2 = VT2.getSizeInBits();
6162   if (NumBits1 <= NumBits2)
6163     return false;
6164   return Subtarget->is64Bit() || NumBits1 < 64;
6165 }
6166
6167 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6168 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6169 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6170 /// are assumed to be legal.
6171 bool
6172 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6173   // Only do shuffles on 128-bit vector types for now.
6174   if (VT.getSizeInBits() == 64) return false;
6175   return (Mask.getNode()->getNumOperands() <= 4 ||
6176           isIdentityMask(Mask.getNode()) ||
6177           isIdentityMask(Mask.getNode(), true) ||
6178           isSplatMask(Mask.getNode())  ||
6179           isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6180           X86::isUNPCKLMask(Mask.getNode()) ||
6181           X86::isUNPCKHMask(Mask.getNode()) ||
6182           X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6183           X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6184 }
6185
6186 bool
6187 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6188                                           MVT EVT, SelectionDAG &DAG) const {
6189   unsigned NumElts = BVOps.size();
6190   // Only do shuffles on 128-bit vector types for now.
6191   if (EVT.getSizeInBits() * NumElts == 64) return false;
6192   if (NumElts == 2) return true;
6193   if (NumElts == 4) {
6194     return (isMOVLMask(&BVOps[0], 4)  ||
6195             isCommutedMOVL(&BVOps[0], 4, true) ||
6196             isSHUFPMask(&BVOps[0], 4) || 
6197             isCommutedSHUFP(&BVOps[0], 4));
6198   }
6199   return false;
6200 }
6201
6202 //===----------------------------------------------------------------------===//
6203 //                           X86 Scheduler Hooks
6204 //===----------------------------------------------------------------------===//
6205
6206 // private utility function
6207 MachineBasicBlock *
6208 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6209                                                        MachineBasicBlock *MBB,
6210                                                        unsigned regOpc,
6211                                                        unsigned immOpc,
6212                                                        unsigned LoadOpc,
6213                                                        unsigned CXchgOpc,
6214                                                        unsigned copyOpc,
6215                                                        unsigned notOpc,
6216                                                        unsigned EAXreg,
6217                                                        TargetRegisterClass *RC,
6218                                                        bool invSrc) {
6219   // For the atomic bitwise operator, we generate
6220   //   thisMBB:
6221   //   newMBB:
6222   //     ld  t1 = [bitinstr.addr]
6223   //     op  t2 = t1, [bitinstr.val]
6224   //     mov EAX = t1
6225   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
6226   //     bz  newMBB
6227   //     fallthrough -->nextMBB
6228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6229   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6230   MachineFunction::iterator MBBIter = MBB;
6231   ++MBBIter;
6232   
6233   /// First build the CFG
6234   MachineFunction *F = MBB->getParent();
6235   MachineBasicBlock *thisMBB = MBB;
6236   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6237   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6238   F->insert(MBBIter, newMBB);
6239   F->insert(MBBIter, nextMBB);
6240   
6241   // Move all successors to thisMBB to nextMBB
6242   nextMBB->transferSuccessors(thisMBB);
6243     
6244   // Update thisMBB to fall through to newMBB
6245   thisMBB->addSuccessor(newMBB);
6246   
6247   // newMBB jumps to itself and fall through to nextMBB
6248   newMBB->addSuccessor(nextMBB);
6249   newMBB->addSuccessor(newMBB);
6250   
6251   // Insert instructions into newMBB based on incoming instruction
6252   assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6253   MachineOperand& destOper = bInstr->getOperand(0);
6254   MachineOperand* argOpers[6];
6255   int numArgs = bInstr->getNumOperands() - 1;
6256   for (int i=0; i < numArgs; ++i)
6257     argOpers[i] = &bInstr->getOperand(i+1);
6258
6259   // x86 address has 4 operands: base, index, scale, and displacement
6260   int lastAddrIndx = 3; // [0,3]
6261   int valArgIndx = 4;
6262   
6263   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6264   MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6265   for (int i=0; i <= lastAddrIndx; ++i)
6266     (*MIB).addOperand(*argOpers[i]);
6267
6268   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6269   if (invSrc) {
6270     MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6271   }
6272   else 
6273     tt = t1;
6274
6275   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6276   assert(   (argOpers[valArgIndx]->isReg() || argOpers[valArgIndx]->isImm())
6277          && "invalid operand");
6278   if (argOpers[valArgIndx]->isReg())
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]->isReg() || argOpers[valArgIndx]->isImm())
6364          && "invalid operand");
6365   
6366   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);  
6367   if (argOpers[valArgIndx]->isReg())
6368     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6369   else 
6370     MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6371   (*MIB).addOperand(*argOpers[valArgIndx]);
6372
6373   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6374   MIB.addReg(t1);
6375
6376   MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6377   MIB.addReg(t1);
6378   MIB.addReg(t2);
6379
6380   // Generate movc
6381   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6382   MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6383   MIB.addReg(t2);
6384   MIB.addReg(t1);
6385
6386   // Cmp and exchange if none has modified the memory location
6387   MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6388   for (int i=0; i <= lastAddrIndx; ++i)
6389     (*MIB).addOperand(*argOpers[i]);
6390   MIB.addReg(t3);
6391   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6392   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6393   
6394   MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6395   MIB.addReg(X86::EAX);
6396   
6397   // insert branch
6398   BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6399
6400   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
6401   return nextMBB;
6402 }
6403
6404
6405 MachineBasicBlock *
6406 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6407                                                MachineBasicBlock *BB) {
6408   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6409   switch (MI->getOpcode()) {
6410   default: assert(false && "Unexpected instr type to insert");
6411   case X86::CMOV_FR32:
6412   case X86::CMOV_FR64:
6413   case X86::CMOV_V4F32:
6414   case X86::CMOV_V2F64:
6415   case X86::CMOV_V2I64: {
6416     // To "insert" a SELECT_CC instruction, we actually have to insert the
6417     // diamond control-flow pattern.  The incoming instruction knows the
6418     // destination vreg to set, the condition code register to branch on, the
6419     // true/false values to select between, and a branch opcode to use.
6420     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6421     MachineFunction::iterator It = BB;
6422     ++It;
6423
6424     //  thisMBB:
6425     //  ...
6426     //   TrueVal = ...
6427     //   cmpTY ccX, r1, r2
6428     //   bCC copy1MBB
6429     //   fallthrough --> copy0MBB
6430     MachineBasicBlock *thisMBB = BB;
6431     MachineFunction *F = BB->getParent();
6432     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6433     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6434     unsigned Opc =
6435       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6436     BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6437     F->insert(It, copy0MBB);
6438     F->insert(It, sinkMBB);
6439     // Update machine-CFG edges by transferring all successors of the current
6440     // block to the new block which will contain the Phi node for the select.
6441     sinkMBB->transferSuccessors(BB);
6442
6443     // Add the true and fallthrough blocks as its successors.
6444     BB->addSuccessor(copy0MBB);
6445     BB->addSuccessor(sinkMBB);
6446
6447     //  copy0MBB:
6448     //   %FalseValue = ...
6449     //   # fallthrough to sinkMBB
6450     BB = copy0MBB;
6451
6452     // Update machine-CFG edges
6453     BB->addSuccessor(sinkMBB);
6454
6455     //  sinkMBB:
6456     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6457     //  ...
6458     BB = sinkMBB;
6459     BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6460       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6461       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6462
6463     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6464     return BB;
6465   }
6466
6467   case X86::FP32_TO_INT16_IN_MEM:
6468   case X86::FP32_TO_INT32_IN_MEM:
6469   case X86::FP32_TO_INT64_IN_MEM:
6470   case X86::FP64_TO_INT16_IN_MEM:
6471   case X86::FP64_TO_INT32_IN_MEM:
6472   case X86::FP64_TO_INT64_IN_MEM:
6473   case X86::FP80_TO_INT16_IN_MEM:
6474   case X86::FP80_TO_INT32_IN_MEM:
6475   case X86::FP80_TO_INT64_IN_MEM: {
6476     // Change the floating point control register to use "round towards zero"
6477     // mode when truncating to an integer value.
6478     MachineFunction *F = BB->getParent();
6479     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6480     addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6481
6482     // Load the old value of the high byte of the control word...
6483     unsigned OldCW =
6484       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6485     addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6486
6487     // Set the high part to be round to zero...
6488     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6489       .addImm(0xC7F);
6490
6491     // Reload the modified control word now...
6492     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6493
6494     // Restore the memory image of control word to original value
6495     addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6496       .addReg(OldCW);
6497
6498     // Get the X86 opcode to use.
6499     unsigned Opc;
6500     switch (MI->getOpcode()) {
6501     default: assert(0 && "illegal opcode!");
6502     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6503     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6504     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6505     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6506     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6507     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6508     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6509     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6510     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6511     }
6512
6513     X86AddressMode AM;
6514     MachineOperand &Op = MI->getOperand(0);
6515     if (Op.isRegister()) {
6516       AM.BaseType = X86AddressMode::RegBase;
6517       AM.Base.Reg = Op.getReg();
6518     } else {
6519       AM.BaseType = X86AddressMode::FrameIndexBase;
6520       AM.Base.FrameIndex = Op.getIndex();
6521     }
6522     Op = MI->getOperand(1);
6523     if (Op.isImmediate())
6524       AM.Scale = Op.getImm();
6525     Op = MI->getOperand(2);
6526     if (Op.isImmediate())
6527       AM.IndexReg = Op.getImm();
6528     Op = MI->getOperand(3);
6529     if (Op.isGlobalAddress()) {
6530       AM.GV = Op.getGlobal();
6531     } else {
6532       AM.Disp = Op.getImm();
6533     }
6534     addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6535                       .addReg(MI->getOperand(4).getReg());
6536
6537     // Reload the original control word now.
6538     addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6539
6540     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
6541     return BB;
6542   }
6543   case X86::ATOMAND32:
6544     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6545                                                X86::AND32ri, X86::MOV32rm, 
6546                                                X86::LCMPXCHG32, X86::MOV32rr,
6547                                                X86::NOT32r, X86::EAX,
6548                                                X86::GR32RegisterClass);
6549   case X86::ATOMOR32:
6550     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr, 
6551                                                X86::OR32ri, X86::MOV32rm, 
6552                                                X86::LCMPXCHG32, X86::MOV32rr,
6553                                                X86::NOT32r, X86::EAX,
6554                                                X86::GR32RegisterClass);
6555   case X86::ATOMXOR32:
6556     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
6557                                                X86::XOR32ri, X86::MOV32rm, 
6558                                                X86::LCMPXCHG32, X86::MOV32rr,
6559                                                X86::NOT32r, X86::EAX,
6560                                                X86::GR32RegisterClass);
6561   case X86::ATOMNAND32:
6562     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
6563                                                X86::AND32ri, X86::MOV32rm,
6564                                                X86::LCMPXCHG32, X86::MOV32rr,
6565                                                X86::NOT32r, X86::EAX,
6566                                                X86::GR32RegisterClass, true);
6567   case X86::ATOMMIN32:
6568     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
6569   case X86::ATOMMAX32:
6570     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
6571   case X86::ATOMUMIN32:
6572     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
6573   case X86::ATOMUMAX32:
6574     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
6575
6576   case X86::ATOMAND16:
6577     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6578                                                X86::AND16ri, X86::MOV16rm,
6579                                                X86::LCMPXCHG16, X86::MOV16rr,
6580                                                X86::NOT16r, X86::AX,
6581                                                X86::GR16RegisterClass);
6582   case X86::ATOMOR16:
6583     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr, 
6584                                                X86::OR16ri, X86::MOV16rm,
6585                                                X86::LCMPXCHG16, X86::MOV16rr,
6586                                                X86::NOT16r, X86::AX,
6587                                                X86::GR16RegisterClass);
6588   case X86::ATOMXOR16:
6589     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
6590                                                X86::XOR16ri, X86::MOV16rm,
6591                                                X86::LCMPXCHG16, X86::MOV16rr,
6592                                                X86::NOT16r, X86::AX,
6593                                                X86::GR16RegisterClass);
6594   case X86::ATOMNAND16:
6595     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
6596                                                X86::AND16ri, X86::MOV16rm,
6597                                                X86::LCMPXCHG16, X86::MOV16rr,
6598                                                X86::NOT16r, X86::AX,
6599                                                X86::GR16RegisterClass, true);
6600   case X86::ATOMMIN16:
6601     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
6602   case X86::ATOMMAX16:
6603     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
6604   case X86::ATOMUMIN16:
6605     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
6606   case X86::ATOMUMAX16:
6607     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
6608
6609   case X86::ATOMAND8:
6610     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6611                                                X86::AND8ri, X86::MOV8rm,
6612                                                X86::LCMPXCHG8, X86::MOV8rr,
6613                                                X86::NOT8r, X86::AL,
6614                                                X86::GR8RegisterClass);
6615   case X86::ATOMOR8:
6616     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr, 
6617                                                X86::OR8ri, X86::MOV8rm,
6618                                                X86::LCMPXCHG8, X86::MOV8rr,
6619                                                X86::NOT8r, X86::AL,
6620                                                X86::GR8RegisterClass);
6621   case X86::ATOMXOR8:
6622     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
6623                                                X86::XOR8ri, X86::MOV8rm,
6624                                                X86::LCMPXCHG8, X86::MOV8rr,
6625                                                X86::NOT8r, X86::AL,
6626                                                X86::GR8RegisterClass);
6627   case X86::ATOMNAND8:
6628     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
6629                                                X86::AND8ri, X86::MOV8rm,
6630                                                X86::LCMPXCHG8, X86::MOV8rr,
6631                                                X86::NOT8r, X86::AL,
6632                                                X86::GR8RegisterClass, true);
6633   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
6634   case X86::ATOMAND64:
6635     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6636                                                X86::AND64ri32, X86::MOV64rm, 
6637                                                X86::LCMPXCHG64, X86::MOV64rr,
6638                                                X86::NOT64r, X86::RAX,
6639                                                X86::GR64RegisterClass);
6640   case X86::ATOMOR64:
6641     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr, 
6642                                                X86::OR64ri32, X86::MOV64rm, 
6643                                                X86::LCMPXCHG64, X86::MOV64rr,
6644                                                X86::NOT64r, X86::RAX,
6645                                                X86::GR64RegisterClass);
6646   case X86::ATOMXOR64:
6647     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
6648                                                X86::XOR64ri32, X86::MOV64rm, 
6649                                                X86::LCMPXCHG64, X86::MOV64rr,
6650                                                X86::NOT64r, X86::RAX,
6651                                                X86::GR64RegisterClass);
6652   case X86::ATOMNAND64:
6653     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
6654                                                X86::AND64ri32, X86::MOV64rm,
6655                                                X86::LCMPXCHG64, X86::MOV64rr,
6656                                                X86::NOT64r, X86::RAX,
6657                                                X86::GR64RegisterClass, true);
6658   case X86::ATOMMIN64:
6659     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
6660   case X86::ATOMMAX64:
6661     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
6662   case X86::ATOMUMIN64:
6663     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
6664   case X86::ATOMUMAX64:
6665     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
6666   }
6667 }
6668
6669 //===----------------------------------------------------------------------===//
6670 //                           X86 Optimization Hooks
6671 //===----------------------------------------------------------------------===//
6672
6673 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6674                                                        const APInt &Mask,
6675                                                        APInt &KnownZero,
6676                                                        APInt &KnownOne,
6677                                                        const SelectionDAG &DAG,
6678                                                        unsigned Depth) const {
6679   unsigned Opc = Op.getOpcode();
6680   assert((Opc >= ISD::BUILTIN_OP_END ||
6681           Opc == ISD::INTRINSIC_WO_CHAIN ||
6682           Opc == ISD::INTRINSIC_W_CHAIN ||
6683           Opc == ISD::INTRINSIC_VOID) &&
6684          "Should use MaskedValueIsZero if you don't know whether Op"
6685          " is a target node!");
6686
6687   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
6688   switch (Opc) {
6689   default: break;
6690   case X86ISD::SETCC:
6691     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
6692                                        Mask.getBitWidth() - 1);
6693     break;
6694   }
6695 }
6696
6697 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
6698 /// node is a GlobalAddress + offset.
6699 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
6700                                        GlobalValue* &GA, int64_t &Offset) const{
6701   if (N->getOpcode() == X86ISD::Wrapper) {
6702     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
6703       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
6704       return true;
6705     }
6706   }
6707   return TargetLowering::isGAPlusOffset(N, GA, Offset);
6708 }
6709
6710 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
6711                                const TargetLowering &TLI) {
6712   GlobalValue *GV;
6713   int64_t Offset = 0;
6714   if (TLI.isGAPlusOffset(Base, GV, Offset))
6715     return (GV->getAlignment() >= N && (Offset % N) == 0);
6716   // DAG combine handles the stack object case.
6717   return false;
6718 }
6719
6720 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
6721                                      unsigned NumElems, MVT EVT,
6722                                      SDNode *&Base,
6723                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
6724                                      const TargetLowering &TLI) {
6725   Base = NULL;
6726   for (unsigned i = 0; i < NumElems; ++i) {
6727     SDValue Idx = PermMask.getOperand(i);
6728     if (Idx.getOpcode() == ISD::UNDEF) {
6729       if (!Base)
6730         return false;
6731       continue;
6732     }
6733
6734     SDValue Elt = DAG.getShuffleScalarElt(N, i);
6735     if (!Elt.getNode() ||
6736         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
6737       return false;
6738     if (!Base) {
6739       Base = Elt.getNode();
6740       if (Base->getOpcode() == ISD::UNDEF)
6741         return false;
6742       continue;
6743     }
6744     if (Elt.getOpcode() == ISD::UNDEF)
6745       continue;
6746
6747     if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
6748                                EVT.getSizeInBits()/8, i, MFI))
6749       return false;
6750   }
6751   return true;
6752 }
6753
6754 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
6755 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
6756 /// if the load addresses are consecutive, non-overlapping, and in the right
6757 /// order.
6758 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
6759                                        const TargetLowering &TLI) {
6760   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6761   MVT VT = N->getValueType(0);
6762   MVT EVT = VT.getVectorElementType();
6763   SDValue PermMask = N->getOperand(2);
6764   unsigned NumElems = PermMask.getNumOperands();
6765   SDNode *Base = NULL;
6766   if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
6767                                 DAG, MFI, TLI))
6768     return SDValue();
6769
6770   LoadSDNode *LD = cast<LoadSDNode>(Base);
6771   if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
6772     return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6773                        LD->getSrcValueOffset(), LD->isVolatile());
6774   return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6775                      LD->getSrcValueOffset(), LD->isVolatile(),
6776                      LD->getAlignment());
6777 }
6778
6779 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
6780 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
6781                                            const X86Subtarget *Subtarget,
6782                                            const TargetLowering &TLI) {
6783   unsigned NumOps = N->getNumOperands();
6784
6785   // Ignore single operand BUILD_VECTOR.
6786   if (NumOps == 1)
6787     return SDValue();
6788
6789   MVT VT = N->getValueType(0);
6790   MVT EVT = VT.getVectorElementType();
6791   if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
6792     // We are looking for load i64 and zero extend. We want to transform
6793     // it before legalizer has a chance to expand it. Also look for i64
6794     // BUILD_PAIR bit casted to f64.
6795     return SDValue();
6796   // This must be an insertion into a zero vector.
6797   SDValue HighElt = N->getOperand(1);
6798   if (!isZeroNode(HighElt))
6799     return SDValue();
6800
6801   // Value must be a load.
6802   SDNode *Base = N->getOperand(0).getNode();
6803   if (!isa<LoadSDNode>(Base)) {
6804     if (Base->getOpcode() != ISD::BIT_CONVERT)
6805       return SDValue();
6806     Base = Base->getOperand(0).getNode();
6807     if (!isa<LoadSDNode>(Base))
6808       return SDValue();
6809   }
6810
6811   // Transform it into VZEXT_LOAD addr.
6812   LoadSDNode *LD = cast<LoadSDNode>(Base);
6813   
6814   // Load must not be an extload.
6815   if (LD->getExtensionType() != ISD::NON_EXTLOAD)
6816     return SDValue();
6817   
6818   return DAG.getNode(X86ISD::VZEXT_LOAD, VT, LD->getChain(), LD->getBasePtr());
6819 }                                           
6820
6821 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6822 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6823                                       const X86Subtarget *Subtarget) {
6824   SDValue Cond = N->getOperand(0);
6825
6826   // If we have SSE[12] support, try to form min/max nodes.
6827   if (Subtarget->hasSSE2() &&
6828       (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6829     if (Cond.getOpcode() == ISD::SETCC) {
6830       // Get the LHS/RHS of the select.
6831       SDValue LHS = N->getOperand(1);
6832       SDValue RHS = N->getOperand(2);
6833       ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6834
6835       unsigned Opcode = 0;
6836       if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6837         switch (CC) {
6838         default: break;
6839         case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6840         case ISD::SETULE:
6841         case ISD::SETLE:
6842           if (!UnsafeFPMath) break;
6843           // FALL THROUGH.
6844         case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
6845         case ISD::SETLT:
6846           Opcode = X86ISD::FMIN;
6847           break;
6848
6849         case ISD::SETOGT: // (X > Y) ? X : Y -> max
6850         case ISD::SETUGT:
6851         case ISD::SETGT:
6852           if (!UnsafeFPMath) break;
6853           // FALL THROUGH.
6854         case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
6855         case ISD::SETGE:
6856           Opcode = X86ISD::FMAX;
6857           break;
6858         }
6859       } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6860         switch (CC) {
6861         default: break;
6862         case ISD::SETOGT: // (X > Y) ? Y : X -> min
6863         case ISD::SETUGT:
6864         case ISD::SETGT:
6865           if (!UnsafeFPMath) break;
6866           // FALL THROUGH.
6867         case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
6868         case ISD::SETGE:
6869           Opcode = X86ISD::FMIN;
6870           break;
6871
6872         case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
6873         case ISD::SETULE:
6874         case ISD::SETLE:
6875           if (!UnsafeFPMath) break;
6876           // FALL THROUGH.
6877         case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
6878         case ISD::SETLT:
6879           Opcode = X86ISD::FMAX;
6880           break;
6881         }
6882       }
6883
6884       if (Opcode)
6885         return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6886     }
6887
6888   }
6889
6890   return SDValue();
6891 }
6892
6893 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6894 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
6895                                      const X86Subtarget *Subtarget) {
6896   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
6897   // the FP state in cases where an emms may be missing.
6898   // A preferable solution to the general problem is to figure out the right
6899   // places to insert EMMS.  This qualifies as a quick hack.
6900   StoreSDNode *St = cast<StoreSDNode>(N);
6901   if (St->getValue().getValueType().isVector() &&
6902       St->getValue().getValueType().getSizeInBits() == 64 &&
6903       isa<LoadSDNode>(St->getValue()) &&
6904       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6905       St->getChain().hasOneUse() && !St->isVolatile()) {
6906     SDNode* LdVal = St->getValue().getNode();
6907     LoadSDNode *Ld = 0;
6908     int TokenFactorIndex = -1;
6909     SmallVector<SDValue, 8> Ops;
6910     SDNode* ChainVal = St->getChain().getNode();
6911     // Must be a store of a load.  We currently handle two cases:  the load
6912     // is a direct child, and it's under an intervening TokenFactor.  It is
6913     // possible to dig deeper under nested TokenFactors.
6914     if (ChainVal == LdVal)
6915       Ld = cast<LoadSDNode>(St->getChain());
6916     else if (St->getValue().hasOneUse() &&
6917              ChainVal->getOpcode() == ISD::TokenFactor) {
6918       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6919         if (ChainVal->getOperand(i).getNode() == LdVal) {
6920           TokenFactorIndex = i;
6921           Ld = cast<LoadSDNode>(St->getValue());
6922         } else
6923           Ops.push_back(ChainVal->getOperand(i));
6924       }
6925     }
6926     if (Ld) {
6927       // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6928       if (Subtarget->is64Bit()) {
6929         SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(), 
6930                                       Ld->getBasePtr(), Ld->getSrcValue(), 
6931                                       Ld->getSrcValueOffset(), Ld->isVolatile(),
6932                                       Ld->getAlignment());
6933         SDValue NewChain = NewLd.getValue(1);
6934         if (TokenFactorIndex != -1) {
6935           Ops.push_back(NewChain);
6936           NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6937                                  Ops.size());
6938         }
6939         return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6940                             St->getSrcValue(), St->getSrcValueOffset(),
6941                             St->isVolatile(), St->getAlignment());
6942       }
6943
6944       // Otherwise, lower to two 32-bit copies.
6945       SDValue LoAddr = Ld->getBasePtr();
6946       SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6947                                      DAG.getConstant(4, MVT::i32));
6948
6949       SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6950                                    Ld->getSrcValue(), Ld->getSrcValueOffset(),
6951                                    Ld->isVolatile(), Ld->getAlignment());
6952       SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6953                                    Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6954                                    Ld->isVolatile(), 
6955                                    MinAlign(Ld->getAlignment(), 4));
6956
6957       SDValue NewChain = LoLd.getValue(1);
6958       if (TokenFactorIndex != -1) {
6959         Ops.push_back(LoLd);
6960         Ops.push_back(HiLd);
6961         NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], 
6962                                Ops.size());
6963       }
6964
6965       LoAddr = St->getBasePtr();
6966       HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6967                            DAG.getConstant(4, MVT::i32));
6968
6969       SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6970                           St->getSrcValue(), St->getSrcValueOffset(),
6971                           St->isVolatile(), St->getAlignment());
6972       SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6973                                     St->getSrcValue(),
6974                                     St->getSrcValueOffset() + 4,
6975                                     St->isVolatile(), 
6976                                     MinAlign(St->getAlignment(), 4));
6977       return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6978     }
6979   }
6980   return SDValue();
6981 }
6982
6983 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6984 /// X86ISD::FXOR nodes.
6985 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6986   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6987   // F[X]OR(0.0, x) -> x
6988   // F[X]OR(x, 0.0) -> x
6989   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6990     if (C->getValueAPF().isPosZero())
6991       return N->getOperand(1);
6992   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6993     if (C->getValueAPF().isPosZero())
6994       return N->getOperand(0);
6995   return SDValue();
6996 }
6997
6998 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6999 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7000   // FAND(0.0, x) -> 0.0
7001   // FAND(x, 0.0) -> 0.0
7002   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7003     if (C->getValueAPF().isPosZero())
7004       return N->getOperand(0);
7005   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7006     if (C->getValueAPF().isPosZero())
7007       return N->getOperand(1);
7008   return SDValue();
7009 }
7010
7011
7012 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7013                                                DAGCombinerInfo &DCI) const {
7014   SelectionDAG &DAG = DCI.DAG;
7015   switch (N->getOpcode()) {
7016   default: break;
7017   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7018   case ISD::BUILD_VECTOR:
7019     return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7020   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
7021   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
7022   case X86ISD::FXOR:
7023   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
7024   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
7025   }
7026
7027   return SDValue();
7028 }
7029
7030 //===----------------------------------------------------------------------===//
7031 //                           X86 Inline Assembly Support
7032 //===----------------------------------------------------------------------===//
7033
7034 /// getConstraintType - Given a constraint letter, return the type of
7035 /// constraint it is for this target.
7036 X86TargetLowering::ConstraintType
7037 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7038   if (Constraint.size() == 1) {
7039     switch (Constraint[0]) {
7040     case 'A':
7041     case 'f':
7042     case 'r':
7043     case 'R':
7044     case 'l':
7045     case 'q':
7046     case 'Q':
7047     case 'x':
7048     case 'y':
7049     case 'Y':
7050       return C_RegisterClass;
7051     default:
7052       break;
7053     }
7054   }
7055   return TargetLowering::getConstraintType(Constraint);
7056 }
7057
7058 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7059 /// with another that has more specific requirements based on the type of the
7060 /// corresponding operand.
7061 const char *X86TargetLowering::
7062 LowerXConstraint(MVT ConstraintVT) const {
7063   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7064   // 'f' like normal targets.
7065   if (ConstraintVT.isFloatingPoint()) {
7066     if (Subtarget->hasSSE2())
7067       return "Y";
7068     if (Subtarget->hasSSE1())
7069       return "x";
7070   }
7071   
7072   return TargetLowering::LowerXConstraint(ConstraintVT);
7073 }
7074
7075 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7076 /// vector.  If it is invalid, don't add anything to Ops.
7077 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7078                                                      char Constraint,
7079                                                      std::vector<SDValue>&Ops,
7080                                                      SelectionDAG &DAG) const {
7081   SDValue Result(0, 0);
7082   
7083   switch (Constraint) {
7084   default: break;
7085   case 'I':
7086     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7087       if (C->getZExtValue() <= 31) {
7088         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7089         break;
7090       }
7091     }
7092     return;
7093   case 'N':
7094     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7095       if (C->getZExtValue() <= 255) {
7096         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7097         break;
7098       }
7099     }
7100     return;
7101   case 'i': {
7102     // Literal immediates are always ok.
7103     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7104       Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7105       break;
7106     }
7107
7108     // If we are in non-pic codegen mode, we allow the address of a global (with
7109     // an optional displacement) to be used with 'i'.
7110     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7111     int64_t Offset = 0;
7112     
7113     // Match either (GA) or (GA+C)
7114     if (GA) {
7115       Offset = GA->getOffset();
7116     } else if (Op.getOpcode() == ISD::ADD) {
7117       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7118       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7119       if (C && GA) {
7120         Offset = GA->getOffset()+C->getZExtValue();
7121       } else {
7122         C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7123         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7124         if (C && GA)
7125           Offset = GA->getOffset()+C->getZExtValue();
7126         else
7127           C = 0, GA = 0;
7128       }
7129     }
7130     
7131     if (GA) {
7132       // If addressing this global requires a load (e.g. in PIC mode), we can't
7133       // match.
7134       if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
7135                                          false))
7136         return;
7137
7138       Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7139                                       Offset);
7140       Result = Op;
7141       break;
7142     }
7143
7144     // Otherwise, not valid for this mode.
7145     return;
7146   }
7147   }
7148   
7149   if (Result.getNode()) {
7150     Ops.push_back(Result);
7151     return;
7152   }
7153   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7154 }
7155
7156 std::vector<unsigned> X86TargetLowering::
7157 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7158                                   MVT VT) const {
7159   if (Constraint.size() == 1) {
7160     // FIXME: not handling fp-stack yet!
7161     switch (Constraint[0]) {      // GCC X86 Constraint Letters
7162     default: break;  // Unknown constraint letter
7163     case 'A':   // EAX/EDX
7164       if (VT == MVT::i32 || VT == MVT::i64)
7165         return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7166       break;
7167     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
7168     case 'Q':   // Q_REGS
7169       if (VT == MVT::i32)
7170         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7171       else if (VT == MVT::i16)
7172         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7173       else if (VT == MVT::i8)
7174         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7175       else if (VT == MVT::i64)
7176         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7177       break;
7178     }
7179   }
7180
7181   return std::vector<unsigned>();
7182 }
7183
7184 std::pair<unsigned, const TargetRegisterClass*>
7185 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7186                                                 MVT VT) const {
7187   // First, see if this is a constraint that directly corresponds to an LLVM
7188   // register class.
7189   if (Constraint.size() == 1) {
7190     // GCC Constraint Letters
7191     switch (Constraint[0]) {
7192     default: break;
7193     case 'r':   // GENERAL_REGS
7194     case 'R':   // LEGACY_REGS
7195     case 'l':   // INDEX_REGS
7196       if (VT == MVT::i64 && Subtarget->is64Bit())
7197         return std::make_pair(0U, X86::GR64RegisterClass);
7198       if (VT == MVT::i32)
7199         return std::make_pair(0U, X86::GR32RegisterClass);
7200       else if (VT == MVT::i16)
7201         return std::make_pair(0U, X86::GR16RegisterClass);
7202       else if (VT == MVT::i8)
7203         return std::make_pair(0U, X86::GR8RegisterClass);
7204       break;
7205     case 'f':  // FP Stack registers.
7206       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7207       // value to the correct fpstack register class.
7208       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7209         return std::make_pair(0U, X86::RFP32RegisterClass);
7210       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7211         return std::make_pair(0U, X86::RFP64RegisterClass);
7212       return std::make_pair(0U, X86::RFP80RegisterClass);
7213     case 'y':   // MMX_REGS if MMX allowed.
7214       if (!Subtarget->hasMMX()) break;
7215       return std::make_pair(0U, X86::VR64RegisterClass);
7216       break;
7217     case 'Y':   // SSE_REGS if SSE2 allowed
7218       if (!Subtarget->hasSSE2()) break;
7219       // FALL THROUGH.
7220     case 'x':   // SSE_REGS if SSE1 allowed
7221       if (!Subtarget->hasSSE1()) break;
7222
7223       switch (VT.getSimpleVT()) {
7224       default: break;
7225       // Scalar SSE types.
7226       case MVT::f32:
7227       case MVT::i32:
7228         return std::make_pair(0U, X86::FR32RegisterClass);
7229       case MVT::f64:
7230       case MVT::i64:
7231         return std::make_pair(0U, X86::FR64RegisterClass);
7232       // Vector types.
7233       case MVT::v16i8:
7234       case MVT::v8i16:
7235       case MVT::v4i32:
7236       case MVT::v2i64:
7237       case MVT::v4f32:
7238       case MVT::v2f64:
7239         return std::make_pair(0U, X86::VR128RegisterClass);
7240       }
7241       break;
7242     }
7243   }
7244   
7245   // Use the default implementation in TargetLowering to convert the register
7246   // constraint into a member of a register class.
7247   std::pair<unsigned, const TargetRegisterClass*> Res;
7248   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7249
7250   // Not found as a standard register?
7251   if (Res.second == 0) {
7252     // GCC calls "st(0)" just plain "st".
7253     if (StringsEqualNoCase("{st}", Constraint)) {
7254       Res.first = X86::ST0;
7255       Res.second = X86::RFP80RegisterClass;
7256     }
7257
7258     return Res;
7259   }
7260
7261   // Otherwise, check to see if this is a register class of the wrong value
7262   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7263   // turn into {ax},{dx}.
7264   if (Res.second->hasType(VT))
7265     return Res;   // Correct type already, nothing to do.
7266
7267   // All of the single-register GCC register classes map their values onto
7268   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
7269   // really want an 8-bit or 32-bit register, map to the appropriate register
7270   // class and return the appropriate register.
7271   if (Res.second == X86::GR16RegisterClass) {
7272     if (VT == MVT::i8) {
7273       unsigned DestReg = 0;
7274       switch (Res.first) {
7275       default: break;
7276       case X86::AX: DestReg = X86::AL; break;
7277       case X86::DX: DestReg = X86::DL; break;
7278       case X86::CX: DestReg = X86::CL; break;
7279       case X86::BX: DestReg = X86::BL; break;
7280       }
7281       if (DestReg) {
7282         Res.first = DestReg;
7283         Res.second = Res.second = X86::GR8RegisterClass;
7284       }
7285     } else if (VT == MVT::i32) {
7286       unsigned DestReg = 0;
7287       switch (Res.first) {
7288       default: break;
7289       case X86::AX: DestReg = X86::EAX; break;
7290       case X86::DX: DestReg = X86::EDX; break;
7291       case X86::CX: DestReg = X86::ECX; break;
7292       case X86::BX: DestReg = X86::EBX; break;
7293       case X86::SI: DestReg = X86::ESI; break;
7294       case X86::DI: DestReg = X86::EDI; break;
7295       case X86::BP: DestReg = X86::EBP; break;
7296       case X86::SP: DestReg = X86::ESP; break;
7297       }
7298       if (DestReg) {
7299         Res.first = DestReg;
7300         Res.second = Res.second = X86::GR32RegisterClass;
7301       }
7302     } else if (VT == MVT::i64) {
7303       unsigned DestReg = 0;
7304       switch (Res.first) {
7305       default: break;
7306       case X86::AX: DestReg = X86::RAX; break;
7307       case X86::DX: DestReg = X86::RDX; break;
7308       case X86::CX: DestReg = X86::RCX; break;
7309       case X86::BX: DestReg = X86::RBX; break;
7310       case X86::SI: DestReg = X86::RSI; break;
7311       case X86::DI: DestReg = X86::RDI; break;
7312       case X86::BP: DestReg = X86::RBP; break;
7313       case X86::SP: DestReg = X86::RSP; break;
7314       }
7315       if (DestReg) {
7316         Res.first = DestReg;
7317         Res.second = Res.second = X86::GR64RegisterClass;
7318       }
7319     }
7320   } else if (Res.second == X86::FR32RegisterClass ||
7321              Res.second == X86::FR64RegisterClass ||
7322              Res.second == X86::VR128RegisterClass) {
7323     // Handle references to XMM physical registers that got mapped into the
7324     // wrong class.  This can happen with constraints like {xmm0} where the
7325     // target independent register mapper will just pick the first match it can
7326     // find, ignoring the required type.
7327     if (VT == MVT::f32)
7328       Res.second = X86::FR32RegisterClass;
7329     else if (VT == MVT::f64)
7330       Res.second = X86::FR64RegisterClass;
7331     else if (X86::VR128RegisterClass->hasType(VT))
7332       Res.second = X86::VR128RegisterClass;
7333   }
7334
7335   return Res;
7336 }