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