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