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