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