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