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