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