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