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