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