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