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