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