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