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