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