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