Reorg. No functionality change.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/VectorExtras.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/SSARegMap.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetOptions.h"
34 using namespace llvm;
35
36 // FIXME: temporary.
37 #include "llvm/Support/CommandLine.h"
38 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
39                                   cl::desc("Enable fastcc on X86"));
40
41 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
42   : TargetLowering(TM) {
43   Subtarget = &TM.getSubtarget<X86Subtarget>();
44   X86ScalarSSE = Subtarget->hasSSE2();
45
46   // Set up the TargetLowering object.
47
48   // X86 is weird, it always uses i8 for shift amounts and setcc results.
49   setShiftAmountType(MVT::i8);
50   setSetCCResultType(MVT::i8);
51   setSetCCResultContents(ZeroOrOneSetCCResult);
52   setSchedulingPreference(SchedulingForRegPressure);
53   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
54   setStackPointerRegisterToSaveRestore(X86::ESP);
55
56   if (!Subtarget->isTargetDarwin())
57     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
58     setUseUnderscoreSetJmpLongJmp(true);
59     
60   // Add legal addressing mode scale values.
61   addLegalAddressScale(8);
62   addLegalAddressScale(4);
63   addLegalAddressScale(2);
64   // Enter the ones which require both scale + index last. These are more
65   // expensive.
66   addLegalAddressScale(9);
67   addLegalAddressScale(5);
68   addLegalAddressScale(3);
69   
70   // Set up the register classes.
71   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
72   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
73   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
74
75   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
76   // operation.
77   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
78   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
79   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
80
81   if (X86ScalarSSE)
82     // No SSE i64 SINT_TO_FP, so expand i32 UINT_TO_FP instead.
83     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
84   else
85     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
86
87   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
88   // this operation.
89   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
90   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
91   // SSE has no i16 to fp conversion, only i32
92   if (X86ScalarSSE)
93     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
94   else {
95     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
96     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
97   }
98
99   // We can handle SINT_TO_FP and FP_TO_SINT from/to i64 even though i64
100   // isn't legal.
101   setOperationAction(ISD::SINT_TO_FP       , MVT::i64  , Custom);
102   setOperationAction(ISD::FP_TO_SINT       , MVT::i64  , Custom);
103
104   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
105   // this operation.
106   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
107   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
108
109   if (X86ScalarSSE) {
110     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
111   } else {
112     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
113     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
114   }
115
116   // Handle FP_TO_UINT by promoting the destination to a larger signed
117   // conversion.
118   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
119   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
120   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
121
122   if (X86ScalarSSE && !Subtarget->hasSSE3())
123     // Expand FP_TO_UINT into a select.
124     // FIXME: We would like to use a Custom expander here eventually to do
125     // the optimal thing for SSE vs. the default expansion in the legalizer.
126     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Expand);
127   else
128     // With SSE3 we can use fisttpll to convert to a signed i64.
129     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
130
131   setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
132   setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
133
134   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
135   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
136   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
137   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
138   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
141   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
142   setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
143   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
144   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
145   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
146   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
147   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
148   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
149   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
150   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
151   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
152   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
153   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
154   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
155
156   // These should be promoted to a larger select which is supported.
157   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
158   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
159
160   // X86 wants to expand cmov itself.
161   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
162   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
163   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
164   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
165   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
166   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
167   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
168   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
169   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
170   // X86 ret instruction may pop stack.
171   setOperationAction(ISD::RET             , MVT::Other, Custom);
172   // Darwin ABI issue.
173   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
174   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
175   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
176   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
177   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
178   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
179   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
180   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
181   // X86 wants to expand memset / memcpy itself.
182   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
183   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
184
185   // We don't have line number support yet.
186   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
187   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
188   // FIXME - use subtarget debug flags
189   if (!Subtarget->isTargetDarwin())
190     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
191
192   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
193   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
194   
195   // Use the default implementation.
196   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
197   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
198   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
199   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
200   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
201   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
202
203   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
204   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
205
206   if (X86ScalarSSE) {
207     // Set up the FP register classes.
208     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
209     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
210
211     // Use ANDPD to simulate FABS.
212     setOperationAction(ISD::FABS , MVT::f64, Custom);
213     setOperationAction(ISD::FABS , MVT::f32, Custom);
214
215     // Use XORP to simulate FNEG.
216     setOperationAction(ISD::FNEG , MVT::f64, Custom);
217     setOperationAction(ISD::FNEG , MVT::f32, Custom);
218
219     // We don't support sin/cos/fmod
220     setOperationAction(ISD::FSIN , MVT::f64, Expand);
221     setOperationAction(ISD::FCOS , MVT::f64, Expand);
222     setOperationAction(ISD::FREM , MVT::f64, Expand);
223     setOperationAction(ISD::FSIN , MVT::f32, Expand);
224     setOperationAction(ISD::FCOS , MVT::f32, Expand);
225     setOperationAction(ISD::FREM , MVT::f32, Expand);
226
227     // Expand FP immediates into loads from the stack, except for the special
228     // cases we handle.
229     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
230     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
231     addLegalFPImmediate(+0.0); // xorps / xorpd
232   } else {
233     // Set up the FP register classes.
234     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
235     
236     setOperationAction(ISD::UNDEF, MVT::f64, Expand);
237     
238     if (!UnsafeFPMath) {
239       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
240       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
241     }
242
243     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
244     addLegalFPImmediate(+0.0); // FLD0
245     addLegalFPImmediate(+1.0); // FLD1
246     addLegalFPImmediate(-0.0); // FLD0/FCHS
247     addLegalFPImmediate(-1.0); // FLD1/FCHS
248   }
249
250   // First set operation action for all vector types to expand. Then we
251   // will selectively turn on ones that can be effectively codegen'd.
252   for (unsigned VT = (unsigned)MVT::Vector + 1;
253        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
254     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
255     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
256     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
257     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
258     setOperationAction(ISD::VECTOR_SHUFFLE,     (MVT::ValueType)VT, Expand);
259     setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
260     setOperationAction(ISD::INSERT_VECTOR_ELT,  (MVT::ValueType)VT, Expand);
261   }
262
263   if (Subtarget->hasMMX()) {
264     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
265     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
266     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
267
268     // FIXME: add MMX packed arithmetics
269     setOperationAction(ISD::BUILD_VECTOR,     MVT::v8i8,  Expand);
270     setOperationAction(ISD::BUILD_VECTOR,     MVT::v4i16, Expand);
271     setOperationAction(ISD::BUILD_VECTOR,     MVT::v2i32, Expand);
272   }
273
274   if (Subtarget->hasSSE1()) {
275     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
276
277     setOperationAction(ISD::AND,                MVT::v4f32, Legal);
278     setOperationAction(ISD::OR,                 MVT::v4f32, Legal);
279     setOperationAction(ISD::XOR,                MVT::v4f32, Legal);
280     setOperationAction(ISD::ADD,                MVT::v4f32, Legal);
281     setOperationAction(ISD::SUB,                MVT::v4f32, Legal);
282     setOperationAction(ISD::MUL,                MVT::v4f32, Legal);
283     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
284     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
285     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
286     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
287     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
288   }
289
290   if (Subtarget->hasSSE2()) {
291     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
292     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
293     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
294     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
295     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
296
297     setOperationAction(ISD::ADD,                MVT::v2f64, Legal);
298     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
299     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
300     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
301     setOperationAction(ISD::SUB,                MVT::v2f64, Legal);
302     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
303     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
304     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
305     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
306     setOperationAction(ISD::MUL,                MVT::v2f64, Legal);
307
308     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
309     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
310     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
311     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
312     // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
313     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
314
315     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
316     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
317       setOperationAction(ISD::BUILD_VECTOR,        (MVT::ValueType)VT, Custom);
318       setOperationAction(ISD::VECTOR_SHUFFLE,      (MVT::ValueType)VT, Custom);
319       setOperationAction(ISD::EXTRACT_VECTOR_ELT,  (MVT::ValueType)VT, Custom);
320     }
321     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
322     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
323     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
324     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
326     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
327
328     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64. 
329     for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
330       setOperationAction(ISD::AND,    (MVT::ValueType)VT, Promote);
331       AddPromotedToType (ISD::AND,    (MVT::ValueType)VT, MVT::v2i64);
332       setOperationAction(ISD::OR,     (MVT::ValueType)VT, Promote);
333       AddPromotedToType (ISD::OR,     (MVT::ValueType)VT, MVT::v2i64);
334       setOperationAction(ISD::XOR,    (MVT::ValueType)VT, Promote);
335       AddPromotedToType (ISD::XOR,    (MVT::ValueType)VT, MVT::v2i64);
336       setOperationAction(ISD::LOAD,   (MVT::ValueType)VT, Promote);
337       AddPromotedToType (ISD::LOAD,   (MVT::ValueType)VT, MVT::v2i64);
338       setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
339       AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
340     }
341
342     // Custom lower v2i64 and v2f64 selects.
343     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
344     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
345     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
346     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
347   }
348
349   // We want to custom lower some of our intrinsics.
350   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
351
352   computeRegisterProperties();
353
354   // FIXME: These should be based on subtarget info. Plus, the values should
355   // be smaller when we are in optimizing for size mode.
356   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
357   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
358   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
359   allowUnalignedMemoryAccesses = true; // x86 supports it!
360 }
361
362 //===----------------------------------------------------------------------===//
363 //                    C Calling Convention implementation
364 //===----------------------------------------------------------------------===//
365
366 /// AddLiveIn - This helper function adds the specified physical register to the
367 /// MachineFunction as a live in value.  It also creates a corresponding virtual
368 /// register for it.
369 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
370                           TargetRegisterClass *RC) {
371   assert(RC->contains(PReg) && "Not the correct regclass!");
372   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
373   MF.addLiveIn(PReg, VReg);
374   return VReg;
375 }
376
377 /// HowToPassCCCArgument - Returns how an formal argument of the specified type
378 /// should be passed. If it is through stack, returns the size of the stack
379 /// slot; if it is through XMM register, returns the number of XMM registers
380 /// are needed.
381 static void
382 HowToPassCCCArgument(MVT::ValueType ObjectVT, unsigned NumXMMRegs,
383                      unsigned &ObjSize, unsigned &ObjXMMRegs) {
384   ObjXMMRegs = 0;
385
386   switch (ObjectVT) {
387   default: assert(0 && "Unhandled argument type!");
388   case MVT::i8:  ObjSize = 1; break;
389   case MVT::i16: ObjSize = 2; break;
390   case MVT::i32: ObjSize = 4; break;
391   case MVT::i64: ObjSize = 8; break;
392   case MVT::f32: ObjSize = 4; break;
393   case MVT::f64: ObjSize = 8; break;
394   case MVT::v16i8:
395   case MVT::v8i16:
396   case MVT::v4i32:
397   case MVT::v2i64:
398   case MVT::v4f32:
399   case MVT::v2f64:
400     if (NumXMMRegs < 4)
401       ObjXMMRegs = 1;
402     else
403       ObjSize = 16;
404     break;
405   }
406 }
407
408 SDOperand X86TargetLowering::LowerCCCArguments(SDOperand Op, SelectionDAG &DAG) {
409   unsigned NumArgs = Op.Val->getNumValues() - 1;
410   MachineFunction &MF = DAG.getMachineFunction();
411   MachineFrameInfo *MFI = MF.getFrameInfo();
412   SDOperand Root = Op.getOperand(0);
413   std::vector<SDOperand> ArgValues;
414
415   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
416   // the stack frame looks like this:
417   //
418   // [ESP] -- return address
419   // [ESP + 4] -- first argument (leftmost lexically)
420   // [ESP + 8] -- second argument, if first argument is <= 4 bytes in size
421   //    ...
422   //
423   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
424   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
425   static const unsigned XMMArgRegs[] = {
426     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
427   };
428   for (unsigned i = 0; i < NumArgs; ++i) {
429     MVT::ValueType ObjectVT = Op.getValue(i).getValueType();
430     unsigned ArgIncrement = 4;
431     unsigned ObjSize = 0;
432     unsigned ObjXMMRegs = 0;
433     HowToPassCCCArgument(ObjectVT, NumXMMRegs, ObjSize, ObjXMMRegs);
434     if (ObjSize > 4)
435       ArgIncrement = ObjSize;
436
437     SDOperand ArgValue;
438     if (ObjXMMRegs) {
439       // Passed in a XMM register.
440       unsigned Reg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
441                                  X86::VR128RegisterClass);
442       ArgValue= DAG.getCopyFromReg(Root, Reg, ObjectVT);
443       ArgValues.push_back(ArgValue);
444       NumXMMRegs += ObjXMMRegs;
445     } else {
446       // XMM arguments have to be aligned on 16-byte boundary.
447       if (ObjSize == 16)
448         ArgOffset = ((ArgOffset + 15) / 16) * 16;
449       // Create the frame index object for this incoming parameter...
450       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
451       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
452       ArgValue = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
453                              DAG.getSrcValue(NULL));
454       ArgValues.push_back(ArgValue);
455       ArgOffset += ArgIncrement;   // Move on to the next argument...
456     }
457   }
458
459   ArgValues.push_back(Root);
460
461   // If the function takes variable number of arguments, make a frame index for
462   // the start of the first vararg value... for expansion of llvm.va_start.
463   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
464   if (isVarArg)
465     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
466   ReturnAddrIndex = 0;     // No return address slot generated yet.
467   BytesToPopOnReturn = 0;  // Callee pops nothing.
468   BytesCallerReserves = ArgOffset;
469
470   // If this is a struct return on Darwin/X86, the callee pops the hidden struct
471   // pointer.
472   if (MF.getFunction()->getCallingConv() == CallingConv::CSRet &&
473       Subtarget->isTargetDarwin())
474     BytesToPopOnReturn = 4;
475
476   // Return the new list of results.
477   std::vector<MVT::ValueType> RetVTs(Op.Val->value_begin(),
478                                      Op.Val->value_end());
479   return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues);
480 }
481
482
483 SDOperand X86TargetLowering::LowerCCCCallTo(SDOperand Op, SelectionDAG &DAG) {
484   SDOperand Chain     = Op.getOperand(0);
485   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
486   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
487   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
488   SDOperand Callee    = Op.getOperand(4);
489   MVT::ValueType RetVT= Op.Val->getValueType(0);
490   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
491
492   // Keep track of the number of XMM regs passed so far.
493   unsigned NumXMMRegs = 0;
494   static const unsigned XMMArgRegs[] = {
495     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
496   };
497
498   // Count how many bytes are to be pushed on the stack.
499   unsigned NumBytes = 0;
500   for (unsigned i = 0; i != NumOps; ++i) {
501     SDOperand Arg = Op.getOperand(5+2*i);
502
503     switch (Arg.getValueType()) {
504     default: assert(0 && "Unexpected ValueType for argument!");
505     case MVT::i8:
506     case MVT::i16:
507     case MVT::i32:
508     case MVT::f32:
509       NumBytes += 4;
510       break;
511     case MVT::i64:
512     case MVT::f64:
513       NumBytes += 8;
514       break;
515     case MVT::v16i8:
516     case MVT::v8i16:
517     case MVT::v4i32:
518     case MVT::v2i64:
519     case MVT::v4f32:
520     case MVT::v2f64:
521       if (NumXMMRegs < 4)
522         ++NumXMMRegs;
523       else {
524         // XMM arguments have to be aligned on 16-byte boundary.
525         NumBytes = ((NumBytes + 15) / 16) * 16;
526         NumBytes += 16;
527       }
528       break;
529     }
530   }
531
532   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
533
534   // Arguments go on the stack in reverse order, as specified by the ABI.
535   unsigned ArgOffset = 0;
536   NumXMMRegs = 0;
537   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
538   std::vector<SDOperand> MemOpChains;
539   SDOperand StackPtr = DAG.getRegister(X86::ESP, getPointerTy());
540   for (unsigned i = 0; i != NumOps; ++i) {
541     SDOperand Arg = Op.getOperand(5+2*i);
542
543     switch (Arg.getValueType()) {
544     default: assert(0 && "Unexpected ValueType for argument!");
545     case MVT::i8:
546     case MVT::i16: {
547       // Promote the integer to 32 bits.  If the input type is signed use a
548       // sign extend, otherwise use a zero extend.
549       unsigned ExtOp =
550         dyn_cast<ConstantSDNode>(Op.getOperand(5+2*i+1))->getValue() ?
551         ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
552       Arg = DAG.getNode(ExtOp, MVT::i32, Arg);
553     }
554     // Fallthrough
555
556     case MVT::i32:
557     case MVT::f32: {
558       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
559       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
560       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
561                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
562       ArgOffset += 4;
563       break;
564     }
565     case MVT::i64:
566     case MVT::f64: {
567       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
568       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
569       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
570                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
571       ArgOffset += 8;
572       break;
573     }
574     case MVT::v16i8:
575     case MVT::v8i16:
576     case MVT::v4i32:
577     case MVT::v2i64:
578     case MVT::v4f32:
579     case MVT::v2f64:
580       if (NumXMMRegs < 4) {
581         RegsToPass.push_back(std::make_pair(XMMArgRegs[NumXMMRegs], Arg));
582         NumXMMRegs++;
583       } else {
584         // XMM arguments have to be aligned on 16-byte boundary.
585         ArgOffset = ((ArgOffset + 15) / 16) * 16;
586         SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
587         PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
588         MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
589                                           Arg, PtrOff, DAG.getSrcValue(NULL)));
590         ArgOffset += 16;
591       }
592     }
593   }
594
595   if (!MemOpChains.empty())
596     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains);
597
598   // Build a sequence of copy-to-reg nodes chained together with token chain
599   // and flag operands which copy the outgoing args into registers.
600   SDOperand InFlag;
601   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
602     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
603                              InFlag);
604     InFlag = Chain.getValue(1);
605   }
606
607   // If the callee is a GlobalAddress node (quite common, every direct call is)
608   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
610     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
611   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
612     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
613
614   std::vector<MVT::ValueType> NodeTys;
615   NodeTys.push_back(MVT::Other);   // Returns a chain
616   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
617   std::vector<SDOperand> Ops;
618   Ops.push_back(Chain);
619   Ops.push_back(Callee);
620
621   // Add argument registers to the end of the list so that they are known live
622   // into the call.
623   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
624     Ops.push_back(DAG.getRegister(RegsToPass[i].first, 
625                                   RegsToPass[i].second.getValueType()));
626
627   if (InFlag.Val)
628     Ops.push_back(InFlag);
629
630   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
631                       NodeTys, Ops);
632   InFlag = Chain.getValue(1);
633
634   // Create the CALLSEQ_END node.
635   unsigned NumBytesForCalleeToPush = 0;
636
637   // If this is is a call to a struct-return function on Darwin/X86, the callee
638   // pops the hidden struct pointer, so we have to push it back.
639   if (CallingConv == CallingConv::CSRet && Subtarget->isTargetDarwin())
640     NumBytesForCalleeToPush = 4;
641   
642   NodeTys.clear();
643   NodeTys.push_back(MVT::Other);   // Returns a chain
644   if (RetVT != MVT::Other)
645     NodeTys.push_back(MVT::Flag);  // Returns a flag for retval copy to use.
646   Ops.clear();
647   Ops.push_back(Chain);
648   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
649   Ops.push_back(DAG.getConstant(NumBytesForCalleeToPush, getPointerTy()));
650   Ops.push_back(InFlag);
651   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
652   if (RetVT != MVT::Other)
653     InFlag = Chain.getValue(1);
654   
655   std::vector<SDOperand> ResultVals;
656   NodeTys.clear();
657   switch (RetVT) {
658   default: assert(0 && "Unknown value type to return!");
659   case MVT::Other: break;
660   case MVT::i8:
661     Chain = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag).getValue(1);
662     ResultVals.push_back(Chain.getValue(0));
663     NodeTys.push_back(MVT::i8);
664     break;
665   case MVT::i16:
666     Chain = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag).getValue(1);
667     ResultVals.push_back(Chain.getValue(0));
668     NodeTys.push_back(MVT::i16);
669     break;
670   case MVT::i32:
671     if (Op.Val->getValueType(1) == MVT::i32) {
672       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
673       ResultVals.push_back(Chain.getValue(0));
674       Chain = DAG.getCopyFromReg(Chain, X86::EDX, MVT::i32,
675                                  Chain.getValue(2)).getValue(1);
676       ResultVals.push_back(Chain.getValue(0));
677       NodeTys.push_back(MVT::i32);
678     } else {
679       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
680       ResultVals.push_back(Chain.getValue(0));
681     }
682     NodeTys.push_back(MVT::i32);
683     break;
684   case MVT::v16i8:
685   case MVT::v8i16:
686   case MVT::v4i32:
687   case MVT::v2i64:
688   case MVT::v4f32:
689   case MVT::v2f64:
690     Chain = DAG.getCopyFromReg(Chain, X86::XMM0, RetVT, InFlag).getValue(1);
691     ResultVals.push_back(Chain.getValue(0));
692     NodeTys.push_back(RetVT);
693     break;
694   case MVT::f32:
695   case MVT::f64: {
696     std::vector<MVT::ValueType> Tys;
697     Tys.push_back(MVT::f64);
698     Tys.push_back(MVT::Other);
699     Tys.push_back(MVT::Flag);
700     std::vector<SDOperand> Ops;
701     Ops.push_back(Chain);
702     Ops.push_back(InFlag);
703     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
704     Chain  = RetVal.getValue(1);
705     InFlag = RetVal.getValue(2);
706     if (X86ScalarSSE) {
707       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
708       // shouldn't be necessary except that RFP cannot be live across
709       // multiple blocks. When stackifier is fixed, they can be uncoupled.
710       MachineFunction &MF = DAG.getMachineFunction();
711       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
712       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
713       Tys.clear();
714       Tys.push_back(MVT::Other);
715       Ops.clear();
716       Ops.push_back(Chain);
717       Ops.push_back(RetVal);
718       Ops.push_back(StackSlot);
719       Ops.push_back(DAG.getValueType(RetVT));
720       Ops.push_back(InFlag);
721       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
722       RetVal = DAG.getLoad(RetVT, Chain, StackSlot,
723                            DAG.getSrcValue(NULL));
724       Chain = RetVal.getValue(1);
725     }
726
727     if (RetVT == MVT::f32 && !X86ScalarSSE)
728       // FIXME: we would really like to remember that this FP_ROUND
729       // operation is okay to eliminate if we allow excess FP precision.
730       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
731     ResultVals.push_back(RetVal);
732     NodeTys.push_back(RetVT);
733     break;
734   }
735   }
736
737   // If the function returns void, just return the chain.
738   if (ResultVals.empty())
739     return Chain;
740   
741   // Otherwise, merge everything together with a MERGE_VALUES node.
742   NodeTys.push_back(MVT::Other);
743   ResultVals.push_back(Chain);
744   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals);
745   return Res.getValue(Op.ResNo);
746 }
747
748 //===----------------------------------------------------------------------===//
749 //                    Fast Calling Convention implementation
750 //===----------------------------------------------------------------------===//
751 //
752 // The X86 'fast' calling convention passes up to two integer arguments in
753 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
754 // and requires that the callee pop its arguments off the stack (allowing proper
755 // tail calls), and has the same return value conventions as C calling convs.
756 //
757 // This calling convention always arranges for the callee pop value to be 8n+4
758 // bytes, which is needed for tail recursion elimination and stack alignment
759 // reasons.
760 //
761 // Note that this can be enhanced in the future to pass fp vals in registers
762 // (when we have a global fp allocator) and do other tricks.
763 //
764
765 /// HowToPassFastCCArgument - Returns how an formal argument of the specified
766 /// type should be passed. If it is through stack, returns the size of the stack
767 /// slot; if it is through integer or XMM register, returns the number of
768 /// integer or XMM registers are needed.
769 static void
770 HowToPassFastCCArgument(MVT::ValueType ObjectVT,
771                         unsigned NumIntRegs, unsigned NumXMMRegs,
772                         unsigned &ObjSize, unsigned &ObjIntRegs,
773                         unsigned &ObjXMMRegs) {
774   ObjSize = 0;
775   ObjIntRegs = 0;
776   ObjXMMRegs = 0;
777
778   switch (ObjectVT) {
779   default: assert(0 && "Unhandled argument type!");
780   case MVT::i8:
781 #if FASTCC_NUM_INT_ARGS_INREGS > 0
782     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
783       ObjIntRegs = 1;
784     else
785 #endif
786       ObjSize = 1;
787     break;
788   case MVT::i16:
789 #if FASTCC_NUM_INT_ARGS_INREGS > 0
790     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
791       ObjIntRegs = 1;
792     else
793 #endif
794       ObjSize = 2;
795     break;
796   case MVT::i32:
797 #if FASTCC_NUM_INT_ARGS_INREGS > 0
798     if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS)
799       ObjIntRegs = 1;
800     else
801 #endif
802       ObjSize = 4;
803     break;
804   case MVT::i64:
805 #if FASTCC_NUM_INT_ARGS_INREGS > 0
806     if (NumIntRegs+2 <= FASTCC_NUM_INT_ARGS_INREGS) {
807       ObjIntRegs = 2;
808     } else if (NumIntRegs+1 <= FASTCC_NUM_INT_ARGS_INREGS) {
809       ObjIntRegs = 1;
810       ObjSize = 4;
811     } else
812 #endif
813       ObjSize = 8;
814   case MVT::f32:
815     ObjSize = 4;
816     break;
817   case MVT::f64:
818     ObjSize = 8;
819     break;
820   case MVT::v16i8:
821   case MVT::v8i16:
822   case MVT::v4i32:
823   case MVT::v2i64:
824   case MVT::v4f32:
825   case MVT::v2f64:
826     if (NumXMMRegs < 4)
827       ObjXMMRegs = 1;
828     else
829       ObjSize = 16;
830     break;
831   }
832 }
833
834 SDOperand
835 X86TargetLowering::LowerFastCCArguments(SDOperand Op, SelectionDAG &DAG) {
836   unsigned NumArgs = Op.Val->getNumValues()-1;
837   MachineFunction &MF = DAG.getMachineFunction();
838   MachineFrameInfo *MFI = MF.getFrameInfo();
839   SDOperand Root = Op.getOperand(0);
840   std::vector<SDOperand> ArgValues;
841
842   // Add DAG nodes to load the arguments...  On entry to a function the stack
843   // frame looks like this:
844   //
845   // [ESP] -- return address
846   // [ESP + 4] -- first nonreg argument (leftmost lexically)
847   // [ESP + 8] -- second nonreg argument, if 1st argument is <= 4 bytes in size
848   //    ...
849   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
850
851   // Keep track of the number of integer regs passed so far.  This can be either
852   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
853   // used).
854   unsigned NumIntRegs = 0;
855   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
856
857   static const unsigned XMMArgRegs[] = {
858     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
859   };
860   
861   for (unsigned i = 0; i < NumArgs; ++i) {
862     MVT::ValueType ObjectVT = Op.getValue(i).getValueType();
863     unsigned ArgIncrement = 4;
864     unsigned ObjSize = 0;
865     unsigned ObjIntRegs = 0;
866     unsigned ObjXMMRegs = 0;
867
868     HowToPassFastCCArgument(ObjectVT, NumIntRegs, NumXMMRegs,
869                             ObjSize, ObjIntRegs, ObjXMMRegs);
870     if (ObjSize > 4)
871       ArgIncrement = ObjSize;
872
873     unsigned Reg = 0;
874     SDOperand ArgValue;
875     if (ObjIntRegs || ObjXMMRegs) {
876       switch (ObjectVT) {
877       default: assert(0 && "Unhandled argument type!");
878       case MVT::i8:
879         Reg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
880                         X86::GR8RegisterClass);
881         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i8);
882         break;
883       case MVT::i16:
884         Reg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
885                         X86::GR16RegisterClass);
886         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i16);
887         break;
888       case MVT::i32:
889         Reg = AddLiveIn(MF, NumIntRegs ? X86::EDX : X86::EAX,
890                         X86::GR32RegisterClass);
891         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i32);
892         break;
893       case MVT::i64:
894         Reg = AddLiveIn(MF, NumIntRegs ? X86::EDX : X86::EAX,
895                         X86::GR32RegisterClass);
896         ArgValue = DAG.getCopyFromReg(Root, Reg, MVT::i32);
897         if (ObjIntRegs == 2) {
898           Reg = AddLiveIn(MF, X86::EDX, X86::GR32RegisterClass);
899           SDOperand ArgValue2 = DAG.getCopyFromReg(Root, Reg, MVT::i32);
900           ArgValue= DAG.getNode(ISD::BUILD_PAIR, MVT::i64, ArgValue, ArgValue2);
901         }
902         break;
903       case MVT::v16i8:
904       case MVT::v8i16:
905       case MVT::v4i32:
906       case MVT::v2i64:
907       case MVT::v4f32:
908       case MVT::v2f64:
909         Reg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs], X86::VR128RegisterClass);
910         ArgValue = DAG.getCopyFromReg(Root, Reg, ObjectVT);
911         break;
912       }
913       NumIntRegs += ObjIntRegs;
914       NumXMMRegs += ObjXMMRegs;
915     }
916
917     if (ObjSize) {
918       // XMM arguments have to be aligned on 16-byte boundary.
919       if (ObjSize == 16)
920         ArgOffset = ((ArgOffset + 15) / 16) * 16;
921       // Create the SelectionDAG nodes corresponding to a load from this
922       // parameter.
923       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
924       SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
925       if (ObjectVT == MVT::i64 && ObjIntRegs) {
926         SDOperand ArgValue2 = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
927                                           DAG.getSrcValue(NULL));
928         ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, ArgValue, ArgValue2);
929       } else
930         ArgValue = DAG.getLoad(Op.Val->getValueType(i), Root, FIN,
931                                DAG.getSrcValue(NULL));
932       ArgOffset += ArgIncrement;   // Move on to the next argument.
933     }
934
935     ArgValues.push_back(ArgValue);
936   }
937
938   ArgValues.push_back(Root);
939
940   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
941   // arguments and the arguments after the retaddr has been pushed are aligned.
942   if ((ArgOffset & 7) == 0)
943     ArgOffset += 4;
944
945   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
946   ReturnAddrIndex = 0;             // No return address slot generated yet.
947   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
948   BytesCallerReserves = 0;
949
950   // Finally, inform the code generator which regs we return values in.
951   switch (getValueType(MF.getFunction()->getReturnType())) {
952   default: assert(0 && "Unknown type!");
953   case MVT::isVoid: break;
954   case MVT::i8:
955   case MVT::i16:
956   case MVT::i32:
957     MF.addLiveOut(X86::EAX);
958     break;
959   case MVT::i64:
960     MF.addLiveOut(X86::EAX);
961     MF.addLiveOut(X86::EDX);
962     break;
963   case MVT::f32:
964   case MVT::f64:
965     MF.addLiveOut(X86::ST0);
966     break;
967   case MVT::v16i8:
968   case MVT::v8i16:
969   case MVT::v4i32:
970   case MVT::v2i64:
971   case MVT::v4f32:
972   case MVT::v2f64:
973     MF.addLiveOut(X86::XMM0);
974     break;
975   }
976
977   // Return the new list of results.
978   std::vector<MVT::ValueType> RetVTs(Op.Val->value_begin(),
979                                      Op.Val->value_end());
980   return DAG.getNode(ISD::MERGE_VALUES, RetVTs, ArgValues);
981 }
982
983 SDOperand X86TargetLowering::LowerFastCCCallTo(SDOperand Op, SelectionDAG &DAG) {
984   SDOperand Chain     = Op.getOperand(0);
985   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
986   bool isVarArg       = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
987   bool isTailCall     = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
988   SDOperand Callee    = Op.getOperand(4);
989   MVT::ValueType RetVT= Op.Val->getValueType(0);
990   unsigned NumOps     = (Op.getNumOperands() - 5) / 2;
991
992   // Count how many bytes are to be pushed on the stack.
993   unsigned NumBytes = 0;
994
995   // Keep track of the number of integer regs passed so far.  This can be either
996   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
997   // used).
998   unsigned NumIntRegs = 0;
999   unsigned NumXMMRegs = 0;  // XMM regs used for parameter passing.
1000
1001   static const unsigned GPRArgRegs[][2] = {
1002     { X86::AL,  X86::DL },
1003     { X86::AX,  X86::DX },
1004     { X86::EAX, X86::EDX }
1005   };
1006   static const unsigned XMMArgRegs[] = {
1007     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1008   };
1009
1010   for (unsigned i = 0; i != NumOps; ++i) {
1011     SDOperand Arg = Op.getOperand(5+2*i);
1012
1013     switch (Arg.getValueType()) {
1014     default: assert(0 && "Unknown value type!");
1015     case MVT::i8:
1016     case MVT::i16:
1017     case MVT::i32:
1018 #if FASTCC_NUM_INT_ARGS_INREGS > 0
1019       if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS) {
1020         ++NumIntRegs;
1021         break;
1022       }
1023 #endif
1024       // Fall through
1025     case MVT::f32:
1026       NumBytes += 4;
1027       break;
1028     case MVT::f64:
1029       NumBytes += 8;
1030       break;
1031     case MVT::v16i8:
1032     case MVT::v8i16:
1033     case MVT::v4i32:
1034     case MVT::v2i64:
1035     case MVT::v4f32:
1036     case MVT::v2f64:
1037       if (NumXMMRegs < 4)
1038         NumXMMRegs++;
1039       else {
1040         // XMM arguments have to be aligned on 16-byte boundary.
1041         NumBytes = ((NumBytes + 15) / 16) * 16;
1042         NumBytes += 16;
1043       }
1044       break;
1045     }
1046   }
1047
1048   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1049   // arguments and the arguments after the retaddr has been pushed are aligned.
1050   if ((NumBytes & 7) == 0)
1051     NumBytes += 4;
1052
1053   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
1054
1055   // Arguments go on the stack in reverse order, as specified by the ABI.
1056   unsigned ArgOffset = 0;
1057   NumIntRegs = 0;
1058   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
1059   std::vector<SDOperand> MemOpChains;
1060   SDOperand StackPtr = DAG.getRegister(X86::ESP, getPointerTy());
1061   for (unsigned i = 0; i != NumOps; ++i) {
1062     SDOperand Arg = Op.getOperand(5+2*i);
1063
1064     switch (Arg.getValueType()) {
1065     default: assert(0 && "Unexpected ValueType for argument!");
1066     case MVT::i8:
1067     case MVT::i16:
1068     case MVT::i32:
1069 #if FASTCC_NUM_INT_ARGS_INREGS > 0
1070       if (NumIntRegs < FASTCC_NUM_INT_ARGS_INREGS) {
1071         RegsToPass.push_back(
1072               std::make_pair(GPRArgRegs[Arg.getValueType()-MVT::i8][NumIntRegs],
1073                              Arg));
1074         ++NumIntRegs;
1075         break;
1076       }
1077 #endif
1078       // Fall through
1079     case MVT::f32: {
1080       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1081       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1082       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1083                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
1084       ArgOffset += 4;
1085       break;
1086     }
1087     case MVT::f64: {
1088       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1089       PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1090       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1091                                         Arg, PtrOff, DAG.getSrcValue(NULL)));
1092       ArgOffset += 8;
1093       break;
1094     }
1095     case MVT::v16i8:
1096     case MVT::v8i16:
1097     case MVT::v4i32:
1098     case MVT::v2i64:
1099     case MVT::v4f32:
1100     case MVT::v2f64:
1101       if (NumXMMRegs < 4) {
1102         RegsToPass.push_back(std::make_pair(XMMArgRegs[NumXMMRegs], Arg));
1103         NumXMMRegs++;
1104       } else {
1105         // XMM arguments have to be aligned on 16-byte boundary.
1106         ArgOffset = ((ArgOffset + 15) / 16) * 16;
1107         SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
1108         PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1109         MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1110                                           Arg, PtrOff, DAG.getSrcValue(NULL)));
1111         ArgOffset += 16;
1112       }
1113     }
1114   }
1115
1116   if (!MemOpChains.empty())
1117     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOpChains);
1118
1119   // Build a sequence of copy-to-reg nodes chained together with token chain
1120   // and flag operands which copy the outgoing args into registers.
1121   SDOperand InFlag;
1122   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1123     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1124                              InFlag);
1125     InFlag = Chain.getValue(1);
1126   }
1127
1128   // If the callee is a GlobalAddress node (quite common, every direct call is)
1129   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1130   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1131     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1132   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
1133     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1134
1135   std::vector<MVT::ValueType> NodeTys;
1136   NodeTys.push_back(MVT::Other);   // Returns a chain
1137   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
1138   std::vector<SDOperand> Ops;
1139   Ops.push_back(Chain);
1140   Ops.push_back(Callee);
1141
1142   // Add argument registers to the end of the list so that they are known live
1143   // into the call.
1144   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1145     Ops.push_back(DAG.getRegister(RegsToPass[i].first, 
1146                                   RegsToPass[i].second.getValueType()));
1147
1148   if (InFlag.Val)
1149     Ops.push_back(InFlag);
1150
1151   // FIXME: Do not generate X86ISD::TAILCALL for now.
1152   Chain = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
1153                       NodeTys, Ops);
1154   InFlag = Chain.getValue(1);
1155
1156   NodeTys.clear();
1157   NodeTys.push_back(MVT::Other);   // Returns a chain
1158   if (RetVT != MVT::Other)
1159     NodeTys.push_back(MVT::Flag);  // Returns a flag for retval copy to use.
1160   Ops.clear();
1161   Ops.push_back(Chain);
1162   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1163   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
1164   Ops.push_back(InFlag);
1165   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
1166   if (RetVT != MVT::Other)
1167     InFlag = Chain.getValue(1);
1168   
1169   std::vector<SDOperand> ResultVals;
1170   NodeTys.clear();
1171   switch (RetVT) {
1172   default: assert(0 && "Unknown value type to return!");
1173   case MVT::Other: break;
1174   case MVT::i8:
1175     Chain = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag).getValue(1);
1176     ResultVals.push_back(Chain.getValue(0));
1177     NodeTys.push_back(MVT::i8);
1178     break;
1179   case MVT::i16:
1180     Chain = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag).getValue(1);
1181     ResultVals.push_back(Chain.getValue(0));
1182     NodeTys.push_back(MVT::i16);
1183     break;
1184   case MVT::i32:
1185     if (Op.Val->getValueType(1) == MVT::i32) {
1186       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
1187       ResultVals.push_back(Chain.getValue(0));
1188       Chain = DAG.getCopyFromReg(Chain, X86::EDX, MVT::i32,
1189                                  Chain.getValue(2)).getValue(1);
1190       ResultVals.push_back(Chain.getValue(0));
1191       NodeTys.push_back(MVT::i32);
1192     } else {
1193       Chain = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag).getValue(1);
1194       ResultVals.push_back(Chain.getValue(0));
1195     }
1196     NodeTys.push_back(MVT::i32);
1197     break;
1198   case MVT::v16i8:
1199   case MVT::v8i16:
1200   case MVT::v4i32:
1201   case MVT::v2i64:
1202   case MVT::v4f32:
1203   case MVT::v2f64:
1204     Chain = DAG.getCopyFromReg(Chain, X86::XMM0, RetVT, InFlag).getValue(1);
1205     ResultVals.push_back(Chain.getValue(0));
1206     NodeTys.push_back(RetVT);
1207     break;
1208   case MVT::f32:
1209   case MVT::f64: {
1210     std::vector<MVT::ValueType> Tys;
1211     Tys.push_back(MVT::f64);
1212     Tys.push_back(MVT::Other);
1213     Tys.push_back(MVT::Flag);
1214     std::vector<SDOperand> Ops;
1215     Ops.push_back(Chain);
1216     Ops.push_back(InFlag);
1217     SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
1218     Chain  = RetVal.getValue(1);
1219     InFlag = RetVal.getValue(2);
1220     if (X86ScalarSSE) {
1221       // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
1222       // shouldn't be necessary except that RFP cannot be live across
1223       // multiple blocks. When stackifier is fixed, they can be uncoupled.
1224       MachineFunction &MF = DAG.getMachineFunction();
1225       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1226       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1227       Tys.clear();
1228       Tys.push_back(MVT::Other);
1229       Ops.clear();
1230       Ops.push_back(Chain);
1231       Ops.push_back(RetVal);
1232       Ops.push_back(StackSlot);
1233       Ops.push_back(DAG.getValueType(RetVT));
1234       Ops.push_back(InFlag);
1235       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1236       RetVal = DAG.getLoad(RetVT, Chain, StackSlot,
1237                            DAG.getSrcValue(NULL));
1238       Chain = RetVal.getValue(1);
1239     }
1240
1241     if (RetVT == MVT::f32 && !X86ScalarSSE)
1242       // FIXME: we would really like to remember that this FP_ROUND
1243       // operation is okay to eliminate if we allow excess FP precision.
1244       RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
1245     ResultVals.push_back(RetVal);
1246     NodeTys.push_back(RetVT);
1247     break;
1248   }
1249   }
1250
1251
1252   // If the function returns void, just return the chain.
1253   if (ResultVals.empty())
1254     return Chain;
1255   
1256   // Otherwise, merge everything together with a MERGE_VALUES node.
1257   NodeTys.push_back(MVT::Other);
1258   ResultVals.push_back(Chain);
1259   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, ResultVals);
1260   return Res.getValue(Op.ResNo);
1261 }
1262
1263 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1264   if (ReturnAddrIndex == 0) {
1265     // Set up a frame object for the return address.
1266     MachineFunction &MF = DAG.getMachineFunction();
1267     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1268   }
1269
1270   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
1271 }
1272
1273
1274
1275 std::pair<SDOperand, SDOperand> X86TargetLowering::
1276 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
1277                         SelectionDAG &DAG) {
1278   SDOperand Result;
1279   if (Depth)        // Depths > 0 not supported yet!
1280     Result = DAG.getConstant(0, getPointerTy());
1281   else {
1282     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
1283     if (!isFrameAddress)
1284       // Just load the return address
1285       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
1286                            DAG.getSrcValue(NULL));
1287     else
1288       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
1289                            DAG.getConstant(4, MVT::i32));
1290   }
1291   return std::make_pair(Result, Chain);
1292 }
1293
1294 /// getCondBrOpcodeForX86CC - Returns the X86 conditional branch opcode
1295 /// which corresponds to the condition code.
1296 static unsigned getCondBrOpcodeForX86CC(unsigned X86CC) {
1297   switch (X86CC) {
1298   default: assert(0 && "Unknown X86 conditional code!");
1299   case X86ISD::COND_A:  return X86::JA;
1300   case X86ISD::COND_AE: return X86::JAE;
1301   case X86ISD::COND_B:  return X86::JB;
1302   case X86ISD::COND_BE: return X86::JBE;
1303   case X86ISD::COND_E:  return X86::JE;
1304   case X86ISD::COND_G:  return X86::JG;
1305   case X86ISD::COND_GE: return X86::JGE;
1306   case X86ISD::COND_L:  return X86::JL;
1307   case X86ISD::COND_LE: return X86::JLE;
1308   case X86ISD::COND_NE: return X86::JNE;
1309   case X86ISD::COND_NO: return X86::JNO;
1310   case X86ISD::COND_NP: return X86::JNP;
1311   case X86ISD::COND_NS: return X86::JNS;
1312   case X86ISD::COND_O:  return X86::JO;
1313   case X86ISD::COND_P:  return X86::JP;
1314   case X86ISD::COND_S:  return X86::JS;
1315   }
1316 }
1317
1318 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1319 /// specific condition code. It returns a false if it cannot do a direct
1320 /// translation. X86CC is the translated CondCode. Flip is set to true if the
1321 /// the order of comparison operands should be flipped.
1322 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1323                            unsigned &X86CC, bool &Flip) {
1324   Flip = false;
1325   X86CC = X86ISD::COND_INVALID;
1326   if (!isFP) {
1327     switch (SetCCOpcode) {
1328     default: break;
1329     case ISD::SETEQ:  X86CC = X86ISD::COND_E;  break;
1330     case ISD::SETGT:  X86CC = X86ISD::COND_G;  break;
1331     case ISD::SETGE:  X86CC = X86ISD::COND_GE; break;
1332     case ISD::SETLT:  X86CC = X86ISD::COND_L;  break;
1333     case ISD::SETLE:  X86CC = X86ISD::COND_LE; break;
1334     case ISD::SETNE:  X86CC = X86ISD::COND_NE; break;
1335     case ISD::SETULT: X86CC = X86ISD::COND_B;  break;
1336     case ISD::SETUGT: X86CC = X86ISD::COND_A;  break;
1337     case ISD::SETULE: X86CC = X86ISD::COND_BE; break;
1338     case ISD::SETUGE: X86CC = X86ISD::COND_AE; break;
1339     }
1340   } else {
1341     // On a floating point condition, the flags are set as follows:
1342     // ZF  PF  CF   op
1343     //  0 | 0 | 0 | X > Y
1344     //  0 | 0 | 1 | X < Y
1345     //  1 | 0 | 0 | X == Y
1346     //  1 | 1 | 1 | unordered
1347     switch (SetCCOpcode) {
1348     default: break;
1349     case ISD::SETUEQ:
1350     case ISD::SETEQ: X86CC = X86ISD::COND_E;  break;
1351     case ISD::SETOLT: Flip = true; // Fallthrough
1352     case ISD::SETOGT:
1353     case ISD::SETGT: X86CC = X86ISD::COND_A;  break;
1354     case ISD::SETOLE: Flip = true; // Fallthrough
1355     case ISD::SETOGE:
1356     case ISD::SETGE: X86CC = X86ISD::COND_AE; break;
1357     case ISD::SETUGT: Flip = true; // Fallthrough
1358     case ISD::SETULT:
1359     case ISD::SETLT: X86CC = X86ISD::COND_B;  break;
1360     case ISD::SETUGE: Flip = true; // Fallthrough
1361     case ISD::SETULE:
1362     case ISD::SETLE: X86CC = X86ISD::COND_BE; break;
1363     case ISD::SETONE:
1364     case ISD::SETNE: X86CC = X86ISD::COND_NE; break;
1365     case ISD::SETUO: X86CC = X86ISD::COND_P;  break;
1366     case ISD::SETO:  X86CC = X86ISD::COND_NP; break;
1367     }
1368   }
1369
1370   return X86CC != X86ISD::COND_INVALID;
1371 }
1372
1373 static bool translateX86CC(SDOperand CC, bool isFP, unsigned &X86CC,
1374                            bool &Flip) {
1375   return translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC, Flip);
1376 }
1377
1378 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1379 /// code. Current x86 isa includes the following FP cmov instructions:
1380 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1381 static bool hasFPCMov(unsigned X86CC) {
1382   switch (X86CC) {
1383   default:
1384     return false;
1385   case X86ISD::COND_B:
1386   case X86ISD::COND_BE:
1387   case X86ISD::COND_E:
1388   case X86ISD::COND_P:
1389   case X86ISD::COND_A:
1390   case X86ISD::COND_AE:
1391   case X86ISD::COND_NE:
1392   case X86ISD::COND_NP:
1393     return true;
1394   }
1395 }
1396
1397 /// DarwinGVRequiresExtraLoad - true if accessing the GV requires an extra
1398 /// load. For Darwin, external and weak symbols are indirect, loading the value
1399 /// at address GV rather then the value of GV itself. This means that the
1400 /// GlobalAddress must be in the base or index register of the address, not the
1401 /// GV offset field.
1402 static bool DarwinGVRequiresExtraLoad(GlobalValue *GV) {
1403   return (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
1404           (GV->isExternal() && !GV->hasNotBeenReadFromBytecode()));
1405 }
1406
1407 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode.  Return
1408 /// true if Op is undef or if its value falls within the specified range (L, H].
1409 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1410   if (Op.getOpcode() == ISD::UNDEF)
1411     return true;
1412
1413   unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1414   return (Val >= Low && Val < Hi);
1415 }
1416
1417 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode.  Return
1418 /// true if Op is undef or if its value equal to the specified value.
1419 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1420   if (Op.getOpcode() == ISD::UNDEF)
1421     return true;
1422   return cast<ConstantSDNode>(Op)->getValue() == Val;
1423 }
1424
1425 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1426 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1427 bool X86::isPSHUFDMask(SDNode *N) {
1428   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1429
1430   if (N->getNumOperands() != 4)
1431     return false;
1432
1433   // Check if the value doesn't reference the second vector.
1434   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1435     SDOperand Arg = N->getOperand(i);
1436     if (Arg.getOpcode() == ISD::UNDEF) continue;
1437     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1438     if (cast<ConstantSDNode>(Arg)->getValue() >= 4)
1439       return false;
1440   }
1441
1442   return true;
1443 }
1444
1445 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1446 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1447 bool X86::isPSHUFHWMask(SDNode *N) {
1448   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1449
1450   if (N->getNumOperands() != 8)
1451     return false;
1452
1453   // Lower quadword copied in order.
1454   for (unsigned i = 0; i != 4; ++i) {
1455     SDOperand Arg = N->getOperand(i);
1456     if (Arg.getOpcode() == ISD::UNDEF) continue;
1457     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1458     if (cast<ConstantSDNode>(Arg)->getValue() != i)
1459       return false;
1460   }
1461
1462   // Upper quadword shuffled.
1463   for (unsigned i = 4; i != 8; ++i) {
1464     SDOperand Arg = N->getOperand(i);
1465     if (Arg.getOpcode() == ISD::UNDEF) continue;
1466     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1467     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1468     if (Val < 4 || Val > 7)
1469       return false;
1470   }
1471
1472   return true;
1473 }
1474
1475 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
1476 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
1477 bool X86::isPSHUFLWMask(SDNode *N) {
1478   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1479
1480   if (N->getNumOperands() != 8)
1481     return false;
1482
1483   // Upper quadword copied in order.
1484   for (unsigned i = 4; i != 8; ++i)
1485     if (!isUndefOrEqual(N->getOperand(i), i))
1486       return false;
1487
1488   // Lower quadword shuffled.
1489   for (unsigned i = 0; i != 4; ++i)
1490     if (!isUndefOrInRange(N->getOperand(i), 0, 4))
1491       return false;
1492
1493   return true;
1494 }
1495
1496 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
1497 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
1498 static bool isSHUFPMask(std::vector<SDOperand> &N) {
1499   unsigned NumElems = N.size();
1500   if (NumElems != 2 && NumElems != 4) return false;
1501
1502   unsigned Half = NumElems / 2;
1503   for (unsigned i = 0; i < Half; ++i)
1504     if (!isUndefOrInRange(N[i], 0, NumElems))
1505       return false;
1506   for (unsigned i = Half; i < NumElems; ++i)
1507     if (!isUndefOrInRange(N[i], NumElems, NumElems*2))
1508       return false;
1509
1510   return true;
1511 }
1512
1513 bool X86::isSHUFPMask(SDNode *N) {
1514   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1515   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1516   return ::isSHUFPMask(Ops);
1517 }
1518
1519 /// isCommutedSHUFP - Returns true if the shuffle mask is except
1520 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
1521 /// half elements to come from vector 1 (which would equal the dest.) and
1522 /// the upper half to come from vector 2.
1523 static bool isCommutedSHUFP(std::vector<SDOperand> &Ops) {
1524   unsigned NumElems = Ops.size();
1525   if (NumElems != 2 && NumElems != 4) return false;
1526
1527   unsigned Half = NumElems / 2;
1528   for (unsigned i = 0; i < Half; ++i)
1529     if (!isUndefOrInRange(Ops[i], NumElems, NumElems*2))
1530       return false;
1531   for (unsigned i = Half; i < NumElems; ++i)
1532     if (!isUndefOrInRange(Ops[i], 0, NumElems))
1533       return false;
1534   return true;
1535 }
1536
1537 static bool isCommutedSHUFP(SDNode *N) {
1538   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1539   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1540   return isCommutedSHUFP(Ops);
1541 }
1542
1543 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
1544 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
1545 bool X86::isMOVHLPSMask(SDNode *N) {
1546   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1547
1548   if (N->getNumOperands() != 4)
1549     return false;
1550
1551   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
1552   return isUndefOrEqual(N->getOperand(0), 6) &&
1553          isUndefOrEqual(N->getOperand(1), 7) &&
1554          isUndefOrEqual(N->getOperand(2), 2) &&
1555          isUndefOrEqual(N->getOperand(3), 3);
1556 }
1557
1558 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
1559 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
1560 bool X86::isMOVLPMask(SDNode *N) {
1561   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1562
1563   unsigned NumElems = N->getNumOperands();
1564   if (NumElems != 2 && NumElems != 4)
1565     return false;
1566
1567   for (unsigned i = 0; i < NumElems/2; ++i)
1568     if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
1569       return false;
1570
1571   for (unsigned i = NumElems/2; i < NumElems; ++i)
1572     if (!isUndefOrEqual(N->getOperand(i), i))
1573       return false;
1574
1575   return true;
1576 }
1577
1578 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
1579 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
1580 /// and MOVLHPS.
1581 bool X86::isMOVHPMask(SDNode *N) {
1582   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1583
1584   unsigned NumElems = N->getNumOperands();
1585   if (NumElems != 2 && NumElems != 4)
1586     return false;
1587
1588   for (unsigned i = 0; i < NumElems/2; ++i)
1589     if (!isUndefOrEqual(N->getOperand(i), i))
1590       return false;
1591
1592   for (unsigned i = 0; i < NumElems/2; ++i) {
1593     SDOperand Arg = N->getOperand(i + NumElems/2);
1594     if (!isUndefOrEqual(Arg, i + NumElems))
1595       return false;
1596   }
1597
1598   return true;
1599 }
1600
1601 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
1602 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
1603 bool static isUNPCKLMask(std::vector<SDOperand> &N, bool V2IsSplat = false) {
1604   unsigned NumElems = N.size();
1605   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1606     return false;
1607
1608   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1609     SDOperand BitI  = N[i];
1610     SDOperand BitI1 = N[i+1];
1611     if (!isUndefOrEqual(BitI, j))
1612       return false;
1613     if (V2IsSplat) {
1614       if (isUndefOrEqual(BitI1, NumElems))
1615         return false;
1616     } else {
1617       if (!isUndefOrEqual(BitI1, j + NumElems))
1618         return false;
1619     }
1620   }
1621
1622   return true;
1623 }
1624
1625 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
1626   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1627   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1628   return ::isUNPCKLMask(Ops, V2IsSplat);
1629 }
1630
1631 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
1632 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
1633 bool static isUNPCKHMask(std::vector<SDOperand> &N, bool V2IsSplat = false) {
1634   unsigned NumElems = N.size();
1635   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1636     return false;
1637
1638   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1639     SDOperand BitI  = N[i];
1640     SDOperand BitI1 = N[i+1];
1641     if (!isUndefOrEqual(BitI, j + NumElems/2))
1642       return false;
1643     if (V2IsSplat) {
1644       if (isUndefOrEqual(BitI1, NumElems))
1645         return false;
1646     } else {
1647       if (!isUndefOrEqual(BitI1, j + NumElems/2 + NumElems))
1648         return false;
1649     }
1650   }
1651
1652   return true;
1653 }
1654
1655 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
1656   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1657   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1658   return ::isUNPCKHMask(Ops, V2IsSplat);
1659 }
1660
1661 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
1662 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
1663 /// <0, 0, 1, 1>
1664 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
1665   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1666
1667   unsigned NumElems = N->getNumOperands();
1668   if (NumElems != 4 && NumElems != 8 && NumElems != 16)
1669     return false;
1670
1671   for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
1672     SDOperand BitI  = N->getOperand(i);
1673     SDOperand BitI1 = N->getOperand(i+1);
1674
1675     if (!isUndefOrEqual(BitI, j))
1676       return false;
1677     if (!isUndefOrEqual(BitI1, j))
1678       return false;
1679   }
1680
1681   return true;
1682 }
1683
1684 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
1685 /// specifies a shuffle of elements that is suitable for input to MOVSS,
1686 /// MOVSD, and MOVD, i.e. setting the lowest element.
1687 static bool isMOVLMask(std::vector<SDOperand> &N) {
1688   unsigned NumElems = N.size();
1689   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1690     return false;
1691
1692   if (!isUndefOrEqual(N[0], NumElems))
1693     return false;
1694
1695   for (unsigned i = 1; i < NumElems; ++i) {
1696     SDOperand Arg = N[i];
1697     if (!isUndefOrEqual(Arg, i))
1698       return false;
1699   }
1700
1701   return true;
1702 }
1703
1704 bool X86::isMOVLMask(SDNode *N) {
1705   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1706   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1707   return ::isMOVLMask(Ops);
1708 }
1709
1710 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
1711 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
1712 /// element of vector 2 and the other elements to come from vector 1 in order.
1713 static bool isCommutedMOVL(std::vector<SDOperand> &Ops, bool V2IsSplat = false) {
1714   unsigned NumElems = Ops.size();
1715   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
1716     return false;
1717
1718   if (!isUndefOrEqual(Ops[0], 0))
1719     return false;
1720
1721   for (unsigned i = 1; i < NumElems; ++i) {
1722     SDOperand Arg = Ops[i];
1723     if (V2IsSplat) {
1724       if (!isUndefOrEqual(Arg, NumElems))
1725         return false;
1726     } else {
1727       if (!isUndefOrEqual(Arg, i+NumElems))
1728         return false;
1729     }
1730   }
1731
1732   return true;
1733 }
1734
1735 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false) {
1736   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1737   std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
1738   return isCommutedMOVL(Ops, V2IsSplat);
1739 }
1740
1741 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1742 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
1743 bool X86::isMOVSHDUPMask(SDNode *N) {
1744   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1745
1746   if (N->getNumOperands() != 4)
1747     return false;
1748
1749   // Expect 1, 1, 3, 3
1750   for (unsigned i = 0; i < 2; ++i) {
1751     SDOperand Arg = N->getOperand(i);
1752     if (Arg.getOpcode() == ISD::UNDEF) continue;
1753     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1754     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1755     if (Val != 1) return false;
1756   }
1757
1758   bool HasHi = false;
1759   for (unsigned i = 2; i < 4; ++i) {
1760     SDOperand Arg = N->getOperand(i);
1761     if (Arg.getOpcode() == ISD::UNDEF) continue;
1762     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1763     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1764     if (Val != 3) return false;
1765     HasHi = true;
1766   }
1767
1768   // Don't use movshdup if it can be done with a shufps.
1769   return HasHi;
1770 }
1771
1772 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
1773 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
1774 bool X86::isMOVSLDUPMask(SDNode *N) {
1775   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1776
1777   if (N->getNumOperands() != 4)
1778     return false;
1779
1780   // Expect 0, 0, 2, 2
1781   for (unsigned i = 0; i < 2; ++i) {
1782     SDOperand Arg = N->getOperand(i);
1783     if (Arg.getOpcode() == ISD::UNDEF) continue;
1784     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1785     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1786     if (Val != 0) return false;
1787   }
1788
1789   bool HasHi = false;
1790   for (unsigned i = 2; i < 4; ++i) {
1791     SDOperand Arg = N->getOperand(i);
1792     if (Arg.getOpcode() == ISD::UNDEF) continue;
1793     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1794     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1795     if (Val != 2) return false;
1796     HasHi = true;
1797   }
1798
1799   // Don't use movshdup if it can be done with a shufps.
1800   return HasHi;
1801 }
1802
1803 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1804 /// a splat of a single element.
1805 static bool isSplatMask(SDNode *N) {
1806   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1807
1808   // This is a splat operation if each element of the permute is the same, and
1809   // if the value doesn't reference the second vector.
1810   unsigned NumElems = N->getNumOperands();
1811   SDOperand ElementBase;
1812   unsigned i = 0;
1813   for (; i != NumElems; ++i) {
1814     SDOperand Elt = N->getOperand(i);
1815     if (ConstantSDNode *EltV = dyn_cast<ConstantSDNode>(Elt)) {
1816       ElementBase = Elt;
1817       break;
1818     }
1819   }
1820
1821   if (!ElementBase.Val)
1822     return false;
1823
1824   for (; i != NumElems; ++i) {
1825     SDOperand Arg = N->getOperand(i);
1826     if (Arg.getOpcode() == ISD::UNDEF) continue;
1827     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1828     if (Arg != ElementBase) return false;
1829   }
1830
1831   // Make sure it is a splat of the first vector operand.
1832   return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
1833 }
1834
1835 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
1836 /// a splat of a single element and it's a 2 or 4 element mask.
1837 bool X86::isSplatMask(SDNode *N) {
1838   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1839
1840   // We can only splat 64-bit, and 32-bit quantities with a single instruction.
1841   if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
1842     return false;
1843   return ::isSplatMask(N);
1844 }
1845
1846 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
1847 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
1848 /// instructions.
1849 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
1850   unsigned NumOperands = N->getNumOperands();
1851   unsigned Shift = (NumOperands == 4) ? 2 : 1;
1852   unsigned Mask = 0;
1853   for (unsigned i = 0; i < NumOperands; ++i) {
1854     unsigned Val = 0;
1855     SDOperand Arg = N->getOperand(NumOperands-i-1);
1856     if (Arg.getOpcode() != ISD::UNDEF)
1857       Val = cast<ConstantSDNode>(Arg)->getValue();
1858     if (Val >= NumOperands) Val -= NumOperands;
1859     Mask |= Val;
1860     if (i != NumOperands - 1)
1861       Mask <<= Shift;
1862   }
1863
1864   return Mask;
1865 }
1866
1867 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
1868 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
1869 /// instructions.
1870 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
1871   unsigned Mask = 0;
1872   // 8 nodes, but we only care about the last 4.
1873   for (unsigned i = 7; i >= 4; --i) {
1874     unsigned Val = 0;
1875     SDOperand Arg = N->getOperand(i);
1876     if (Arg.getOpcode() != ISD::UNDEF)
1877       Val = cast<ConstantSDNode>(Arg)->getValue();
1878     Mask |= (Val - 4);
1879     if (i != 4)
1880       Mask <<= 2;
1881   }
1882
1883   return Mask;
1884 }
1885
1886 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
1887 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
1888 /// instructions.
1889 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
1890   unsigned Mask = 0;
1891   // 8 nodes, but we only care about the first 4.
1892   for (int i = 3; i >= 0; --i) {
1893     unsigned Val = 0;
1894     SDOperand Arg = N->getOperand(i);
1895     if (Arg.getOpcode() != ISD::UNDEF)
1896       Val = cast<ConstantSDNode>(Arg)->getValue();
1897     Mask |= Val;
1898     if (i != 0)
1899       Mask <<= 2;
1900   }
1901
1902   return Mask;
1903 }
1904
1905 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
1906 /// specifies a 8 element shuffle that can be broken into a pair of
1907 /// PSHUFHW and PSHUFLW.
1908 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
1909   assert(N->getOpcode() == ISD::BUILD_VECTOR);
1910
1911   if (N->getNumOperands() != 8)
1912     return false;
1913
1914   // Lower quadword shuffled.
1915   for (unsigned i = 0; i != 4; ++i) {
1916     SDOperand Arg = N->getOperand(i);
1917     if (Arg.getOpcode() == ISD::UNDEF) continue;
1918     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1919     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1920     if (Val > 4)
1921       return false;
1922   }
1923
1924   // Upper quadword shuffled.
1925   for (unsigned i = 4; i != 8; ++i) {
1926     SDOperand Arg = N->getOperand(i);
1927     if (Arg.getOpcode() == ISD::UNDEF) continue;
1928     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1929     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1930     if (Val < 4 || Val > 7)
1931       return false;
1932   }
1933
1934   return true;
1935 }
1936
1937 /// CommuteVectorShuffle - Swap vector_shuffle operandsas well as
1938 /// values in ther permute mask.
1939 static SDOperand CommuteVectorShuffle(SDOperand Op, SelectionDAG &DAG) {
1940   SDOperand V1 = Op.getOperand(0);
1941   SDOperand V2 = Op.getOperand(1);
1942   SDOperand Mask = Op.getOperand(2);
1943   MVT::ValueType VT = Op.getValueType();
1944   MVT::ValueType MaskVT = Mask.getValueType();
1945   MVT::ValueType EltVT = MVT::getVectorBaseType(MaskVT);
1946   unsigned NumElems = Mask.getNumOperands();
1947   std::vector<SDOperand> MaskVec;
1948
1949   for (unsigned i = 0; i != NumElems; ++i) {
1950     SDOperand Arg = Mask.getOperand(i);
1951     if (Arg.getOpcode() == ISD::UNDEF) {
1952       MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1953       continue;
1954     }
1955     assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1956     unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
1957     if (Val < NumElems)
1958       MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
1959     else
1960       MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
1961   }
1962
1963   Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
1964   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1, Mask);
1965 }
1966
1967 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
1968 /// match movhlps. The lower half elements should come from upper half of
1969 /// V1 (and in order), and the upper half elements should come from the upper
1970 /// half of V2 (and in order). 
1971 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
1972   unsigned NumElems = Mask->getNumOperands();
1973   if (NumElems != 4)
1974     return false;
1975   for (unsigned i = 0, e = 2; i != e; ++i)
1976     if (!isUndefOrEqual(Mask->getOperand(i), i+2))
1977       return false;
1978   for (unsigned i = 2; i != 4; ++i)
1979     if (!isUndefOrEqual(Mask->getOperand(i), i+4))
1980       return false;
1981   return true;
1982 }
1983
1984 /// isScalarLoadToVector - Returns true if the node is a scalar load that
1985 /// is promoted to a vector.
1986 static inline bool isScalarLoadToVector(SDNode *N) {
1987   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
1988     N = N->getOperand(0).Val;
1989     return (N->getOpcode() == ISD::LOAD);
1990   }
1991   return false;
1992 }
1993
1994 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
1995 /// match movlp{s|d}. The lower half elements should come from lower half of
1996 /// V1 (and in order), and the upper half elements should come from the upper
1997 /// half of V2 (and in order). And since V1 will become the source of the
1998 /// MOVLP, it must be either a vector load or a scalar load to vector.
1999 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *Mask) {
2000   if (V1->getOpcode() != ISD::LOAD && !isScalarLoadToVector(V1))
2001     return false;
2002
2003   unsigned NumElems = Mask->getNumOperands();
2004   if (NumElems != 2 && NumElems != 4)
2005     return false;
2006   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2007     if (!isUndefOrEqual(Mask->getOperand(i), i))
2008       return false;
2009   for (unsigned i = NumElems/2; i != NumElems; ++i)
2010     if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2011       return false;
2012   return true;
2013 }
2014
2015 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2016 /// all the same.
2017 static bool isSplatVector(SDNode *N) {
2018   if (N->getOpcode() != ISD::BUILD_VECTOR)
2019     return false;
2020
2021   SDOperand SplatValue = N->getOperand(0);
2022   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2023     if (N->getOperand(i) != SplatValue)
2024       return false;
2025   return true;
2026 }
2027
2028 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2029 /// that point to V2 points to its first element.
2030 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2031   assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2032
2033   bool Changed = false;
2034   std::vector<SDOperand> MaskVec;
2035   unsigned NumElems = Mask.getNumOperands();
2036   for (unsigned i = 0; i != NumElems; ++i) {
2037     SDOperand Arg = Mask.getOperand(i);
2038     if (Arg.getOpcode() != ISD::UNDEF) {
2039       unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2040       if (Val > NumElems) {
2041         Arg = DAG.getConstant(NumElems, Arg.getValueType());
2042         Changed = true;
2043       }
2044     }
2045     MaskVec.push_back(Arg);
2046   }
2047
2048   if (Changed)
2049     Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(), MaskVec);
2050   return Mask;
2051 }
2052
2053 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2054 /// operation of specified width.
2055 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2056   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2057   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2058
2059   std::vector<SDOperand> MaskVec;
2060   MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2061   for (unsigned i = 1; i != NumElems; ++i)
2062     MaskVec.push_back(DAG.getConstant(i, BaseVT));
2063   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2064 }
2065
2066 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2067 /// of specified width.
2068 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2069   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2070   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2071   std::vector<SDOperand> MaskVec;
2072   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2073     MaskVec.push_back(DAG.getConstant(i,            BaseVT));
2074     MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2075   }
2076   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2077 }
2078
2079 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2080 /// of specified width.
2081 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2082   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2083   MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2084   unsigned Half = NumElems/2;
2085   std::vector<SDOperand> MaskVec;
2086   for (unsigned i = 0; i != Half; ++i) {
2087     MaskVec.push_back(DAG.getConstant(i + Half,            BaseVT));
2088     MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2089   }
2090   return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2091 }
2092
2093 /// getZeroVector - Returns a vector of specified type with all zero elements.
2094 ///
2095 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2096   assert(MVT::isVector(VT) && "Expected a vector type");
2097   unsigned NumElems = getVectorNumElements(VT);
2098   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2099   bool isFP = MVT::isFloatingPoint(EVT);
2100   SDOperand Zero = isFP ? DAG.getConstantFP(0.0, EVT) : DAG.getConstant(0, EVT);
2101   std::vector<SDOperand> ZeroVec(NumElems, Zero);
2102   return DAG.getNode(ISD::BUILD_VECTOR, VT, ZeroVec);
2103 }
2104
2105 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2106 ///
2107 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2108   SDOperand V1 = Op.getOperand(0);
2109   SDOperand Mask = Op.getOperand(2);
2110   MVT::ValueType VT = Op.getValueType();
2111   unsigned NumElems = Mask.getNumOperands();
2112   Mask = getUnpacklMask(NumElems, DAG);
2113   while (NumElems != 4) {
2114     V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2115     NumElems >>= 1;
2116   }
2117   V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2118
2119   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2120   Mask = getZeroVector(MaskVT, DAG);
2121   SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2122                                   DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2123   return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2124 }
2125
2126 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2127 /// constant +0.0.
2128 static inline bool isZeroNode(SDOperand Elt) {
2129   return ((isa<ConstantSDNode>(Elt) &&
2130            cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2131           (isa<ConstantFPSDNode>(Elt) &&
2132            cast<ConstantFPSDNode>(Elt)->isExactlyValue(0.0)));
2133 }
2134
2135 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2136 /// vector and zero or undef vector.
2137 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2138                                              unsigned NumElems, unsigned Idx,
2139                                              bool isZero, SelectionDAG &DAG) {
2140   SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2141   MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2142   MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2143   SDOperand Zero = DAG.getConstant(0, EVT);
2144   std::vector<SDOperand> MaskVec(NumElems, Zero);
2145   MaskVec[Idx] = DAG.getConstant(NumElems, EVT);
2146   SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2147   return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2148 }
2149
2150 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2151 ///
2152 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2153                                        unsigned NumNonZero, unsigned NumZero,
2154                                        SelectionDAG &DAG) {
2155   if (NumNonZero > 8)
2156     return SDOperand();
2157
2158   SDOperand V(0, 0);
2159   bool First = true;
2160   for (unsigned i = 0; i < 16; ++i) {
2161     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2162     if (ThisIsNonZero && First) {
2163       if (NumZero)
2164         V = getZeroVector(MVT::v8i16, DAG);
2165       else
2166         V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2167       First = false;
2168     }
2169
2170     if ((i & 1) != 0) {
2171       SDOperand ThisElt(0, 0), LastElt(0, 0);
2172       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2173       if (LastIsNonZero) {
2174         LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2175       }
2176       if (ThisIsNonZero) {
2177         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2178         ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2179                               ThisElt, DAG.getConstant(8, MVT::i8));
2180         if (LastIsNonZero)
2181           ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2182       } else
2183         ThisElt = LastElt;
2184
2185       if (ThisElt.Val)
2186         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2187                         DAG.getConstant(i/2, MVT::i32));
2188     }
2189   }
2190
2191   return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2192 }
2193
2194 /// LowerBuildVectorv16i8 - Custom lower build_vector of v8i16.
2195 ///
2196 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2197                                        unsigned NumNonZero, unsigned NumZero,
2198                                        SelectionDAG &DAG) {
2199   if (NumNonZero > 4)
2200     return SDOperand();
2201
2202   SDOperand V(0, 0);
2203   bool First = true;
2204   for (unsigned i = 0; i < 8; ++i) {
2205     bool isNonZero = (NonZeros & (1 << i)) != 0;
2206     if (isNonZero) {
2207       if (First) {
2208         if (NumZero)
2209           V = getZeroVector(MVT::v8i16, DAG);
2210         else
2211           V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2212         First = false;
2213       }
2214       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2215                       DAG.getConstant(i, MVT::i32));
2216     }
2217   }
2218
2219   return V;
2220 }
2221
2222 SDOperand
2223 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2224   // All zero's are handled with pxor.
2225   if (ISD::isBuildVectorAllZeros(Op.Val))
2226     return Op;
2227
2228   // All one's are handled with pcmpeqd.
2229   if (ISD::isBuildVectorAllOnes(Op.Val))
2230     return Op;
2231
2232   MVT::ValueType VT = Op.getValueType();
2233   MVT::ValueType EVT = MVT::getVectorBaseType(VT);
2234   unsigned EVTBits = MVT::getSizeInBits(EVT);
2235
2236   unsigned NumElems = Op.getNumOperands();
2237   unsigned NumZero  = 0;
2238   unsigned NumNonZero = 0;
2239   unsigned NonZeros = 0;
2240   std::set<SDOperand> Values;
2241   for (unsigned i = 0; i < NumElems; ++i) {
2242     SDOperand Elt = Op.getOperand(i);
2243     if (Elt.getOpcode() != ISD::UNDEF) {
2244       Values.insert(Elt);
2245       if (isZeroNode(Elt))
2246         NumZero++;
2247       else {
2248         NonZeros |= (1 << i);
2249         NumNonZero++;
2250       }
2251     }
2252   }
2253
2254   if (NumNonZero == 0)
2255     // Must be a mix of zero and undef. Return a zero vector.
2256     return getZeroVector(VT, DAG);
2257
2258   // Splat is obviously ok. Let legalizer expand it to a shuffle.
2259   if (Values.size() == 1)
2260     return SDOperand();
2261
2262   // Special case for single non-zero element.
2263   if (NumNonZero == 1) {
2264     unsigned Idx = CountTrailingZeros_32(NonZeros);
2265     SDOperand Item = Op.getOperand(Idx);
2266     Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2267     if (Idx == 0)
2268       // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2269       return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2270                                          NumZero > 0, DAG);
2271
2272     if (EVTBits == 32) {
2273       // Turn it into a shuffle of zero and zero-extended scalar to vector.
2274       Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2275                                          DAG);
2276       MVT::ValueType MaskVT  = MVT::getIntVectorWithNumElements(NumElems);
2277       MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2278       std::vector<SDOperand> MaskVec;
2279       for (unsigned i = 0; i < NumElems; i++)
2280         MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2281       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2282       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2283                          DAG.getNode(ISD::UNDEF, VT), Mask);
2284     }
2285   }
2286
2287   // Let legalizer expand 2-widde build_vector's.
2288   if (EVTBits == 64)
2289     return SDOperand();
2290
2291   // If element VT is < 32 bits, convert it to inserts into a zero vector.
2292   if (EVTBits == 8) {
2293     SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG);
2294     if (V.Val) return V;
2295   }
2296
2297   if (EVTBits == 16) {
2298     SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG);
2299     if (V.Val) return V;
2300   }
2301
2302   // If element VT is == 32 bits, turn it into a number of shuffles.
2303   std::vector<SDOperand> V(NumElems);
2304   if (NumElems == 4 && NumZero > 0) {
2305     for (unsigned i = 0; i < 4; ++i) {
2306       bool isZero = !(NonZeros & (1 << i));
2307       if (isZero)
2308         V[i] = getZeroVector(VT, DAG);
2309       else
2310         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2311     }
2312
2313     for (unsigned i = 0; i < 2; ++i) {
2314       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
2315         default: break;
2316         case 0:
2317           V[i] = V[i*2];  // Must be a zero vector.
2318           break;
2319         case 1:
2320           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
2321                              getMOVLMask(NumElems, DAG));
2322           break;
2323         case 2:
2324           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2325                              getMOVLMask(NumElems, DAG));
2326           break;
2327         case 3:
2328           V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
2329                              getUnpacklMask(NumElems, DAG));
2330           break;
2331       }
2332     }
2333
2334     // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
2335     // clears the upper bits. 
2336     // FIXME: we can do the same for v4f32 case when we know both parts of
2337     // the lower half come from scalar_to_vector (loadf32). We should do
2338     // that in post legalizer dag combiner with target specific hooks.
2339     if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
2340       return V[0];
2341     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2342     MVT::ValueType EVT = MVT::getVectorBaseType(MaskVT);
2343     std::vector<SDOperand> MaskVec;
2344     bool Reverse = (NonZeros & 0x3) == 2;
2345     for (unsigned i = 0; i < 2; ++i)
2346       if (Reverse)
2347         MaskVec.push_back(DAG.getConstant(1-i, EVT));
2348       else
2349         MaskVec.push_back(DAG.getConstant(i, EVT));
2350     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
2351     for (unsigned i = 0; i < 2; ++i)
2352       if (Reverse)
2353         MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
2354       else
2355         MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
2356     SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2357     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
2358   }
2359
2360   if (Values.size() > 2) {
2361     // Expand into a number of unpckl*.
2362     // e.g. for v4f32
2363     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
2364     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
2365     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
2366     SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
2367     for (unsigned i = 0; i < NumElems; ++i)
2368       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
2369     NumElems >>= 1;
2370     while (NumElems != 0) {
2371       for (unsigned i = 0; i < NumElems; ++i)
2372         V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
2373                            UnpckMask);
2374       NumElems >>= 1;
2375     }
2376     return V[0];
2377   }
2378
2379   return SDOperand();
2380 }
2381
2382 SDOperand
2383 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
2384   SDOperand V1 = Op.getOperand(0);
2385   SDOperand V2 = Op.getOperand(1);
2386   SDOperand PermMask = Op.getOperand(2);
2387   MVT::ValueType VT = Op.getValueType();
2388   unsigned NumElems = PermMask.getNumOperands();
2389   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
2390   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
2391
2392   if (isSplatMask(PermMask.Val)) {
2393     if (NumElems <= 4) return Op;
2394     // Promote it to a v4i32 splat.
2395     return PromoteSplat(Op, DAG);
2396   }
2397
2398   if (X86::isMOVLMask(PermMask.Val))
2399     return (V1IsUndef) ? V2 : Op;
2400       
2401   if (X86::isMOVSHDUPMask(PermMask.Val) ||
2402       X86::isMOVSLDUPMask(PermMask.Val) ||
2403       X86::isMOVHLPSMask(PermMask.Val) ||
2404       X86::isMOVHPMask(PermMask.Val) ||
2405       X86::isMOVLPMask(PermMask.Val))
2406     return Op;
2407
2408   if (ShouldXformToMOVHLPS(PermMask.Val) ||
2409       ShouldXformToMOVLP(V1.Val, PermMask.Val))
2410     return CommuteVectorShuffle(Op, DAG);
2411
2412   bool V1IsSplat = isSplatVector(V1.Val) || V1.getOpcode() == ISD::UNDEF;
2413   bool V2IsSplat = isSplatVector(V2.Val) || V2.getOpcode() == ISD::UNDEF;
2414   if (V1IsSplat && !V2IsSplat) {
2415     Op = CommuteVectorShuffle(Op, DAG);
2416     V1 = Op.getOperand(0);
2417     V2 = Op.getOperand(1);
2418     PermMask = Op.getOperand(2);
2419     V2IsSplat = true;
2420   }
2421
2422   if (isCommutedMOVL(PermMask.Val, V2IsSplat)) {
2423     if (V2IsUndef) return V1;
2424     Op = CommuteVectorShuffle(Op, DAG);
2425     V1 = Op.getOperand(0);
2426     V2 = Op.getOperand(1);
2427     PermMask = Op.getOperand(2);
2428     if (V2IsSplat) {
2429       // V2 is a splat, so the mask may be malformed. That is, it may point
2430       // to any V2 element. The instruction selectior won't like this. Get
2431       // a corrected mask and commute to form a proper MOVS{S|D}.
2432       SDOperand NewMask = getMOVLMask(NumElems, DAG);
2433       if (NewMask.Val != PermMask.Val)
2434         Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2435     }
2436     return Op;
2437   }
2438
2439   if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
2440       X86::isUNPCKLMask(PermMask.Val) ||
2441       X86::isUNPCKHMask(PermMask.Val))
2442     return Op;
2443
2444   if (V2IsSplat) {
2445     // Normalize mask so all entries that point to V2 points to its first
2446     // element then try to match unpck{h|l} again. If match, return a 
2447     // new vector_shuffle with the corrected mask.
2448     SDOperand NewMask = NormalizeMask(PermMask, DAG);
2449     if (NewMask.Val != PermMask.Val) {
2450       if (X86::isUNPCKLMask(PermMask.Val, true)) {
2451         SDOperand NewMask = getUnpacklMask(NumElems, DAG);
2452         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2453       } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
2454         SDOperand NewMask = getUnpackhMask(NumElems, DAG);
2455         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
2456       }
2457     }
2458   }
2459
2460   // Normalize the node to match x86 shuffle ops if needed
2461   if (V2.getOpcode() != ISD::UNDEF)
2462     if (isCommutedSHUFP(PermMask.Val)) {
2463       Op = CommuteVectorShuffle(Op, DAG);
2464       V1 = Op.getOperand(0);
2465       V2 = Op.getOperand(1);
2466       PermMask = Op.getOperand(2);
2467     }
2468
2469   // If VT is integer, try PSHUF* first, then SHUFP*.
2470   if (MVT::isInteger(VT)) {
2471     if (X86::isPSHUFDMask(PermMask.Val) ||
2472         X86::isPSHUFHWMask(PermMask.Val) ||
2473         X86::isPSHUFLWMask(PermMask.Val)) {
2474       if (V2.getOpcode() != ISD::UNDEF)
2475         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2476                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2477       return Op;
2478     }
2479
2480     if (X86::isSHUFPMask(PermMask.Val))
2481       return Op;
2482
2483     // Handle v8i16 shuffle high / low shuffle node pair.
2484     if (VT == MVT::v8i16 && isPSHUFHW_PSHUFLWMask(PermMask.Val)) {
2485       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2486       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2487       std::vector<SDOperand> MaskVec;
2488       for (unsigned i = 0; i != 4; ++i)
2489         MaskVec.push_back(PermMask.getOperand(i));
2490       for (unsigned i = 4; i != 8; ++i)
2491         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2492       SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2493       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2494       MaskVec.clear();
2495       for (unsigned i = 0; i != 4; ++i)
2496         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2497       for (unsigned i = 4; i != 8; ++i)
2498         MaskVec.push_back(PermMask.getOperand(i));
2499       Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
2500       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2501     }
2502   } else {
2503     // Floating point cases in the other order.
2504     if (X86::isSHUFPMask(PermMask.Val))
2505       return Op;
2506     if (X86::isPSHUFDMask(PermMask.Val) ||
2507         X86::isPSHUFHWMask(PermMask.Val) ||
2508         X86::isPSHUFLWMask(PermMask.Val)) {
2509       if (V2.getOpcode() != ISD::UNDEF)
2510         return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
2511                            DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
2512       return Op;
2513     }
2514   }
2515
2516   if (NumElems == 4) {
2517     MVT::ValueType MaskVT = PermMask.getValueType();
2518     MVT::ValueType MaskEVT = MVT::getVectorBaseType(MaskVT);
2519     std::vector<std::pair<int, int> > Locs;
2520     Locs.reserve(NumElems);
2521     std::vector<SDOperand> Mask1(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2522     std::vector<SDOperand> Mask2(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2523     unsigned NumHi = 0;
2524     unsigned NumLo = 0;
2525     // If no more than two elements come from either vector. This can be
2526     // implemented with two shuffles. First shuffle gather the elements.
2527     // The second shuffle, which takes the first shuffle as both of its
2528     // vector operands, put the elements into the right order.
2529     for (unsigned i = 0; i != NumElems; ++i) {
2530       SDOperand Elt = PermMask.getOperand(i);
2531       if (Elt.getOpcode() == ISD::UNDEF) {
2532         Locs[i] = std::make_pair(-1, -1);
2533       } else {
2534         unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
2535         if (Val < NumElems) {
2536           Locs[i] = std::make_pair(0, NumLo);
2537           Mask1[NumLo] = Elt;
2538           NumLo++;
2539         } else {
2540           Locs[i] = std::make_pair(1, NumHi);
2541           if (2+NumHi < NumElems)
2542             Mask1[2+NumHi] = Elt;
2543           NumHi++;
2544         }
2545       }
2546     }
2547     if (NumLo <= 2 && NumHi <= 2) {
2548       V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2549                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT, Mask1));
2550       for (unsigned i = 0; i != NumElems; ++i) {
2551         if (Locs[i].first == -1)
2552           continue;
2553         else {
2554           unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
2555           Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
2556           Mask2[i] = DAG.getConstant(Idx, MaskEVT);
2557         }
2558       }
2559
2560       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
2561                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, Mask2));
2562     }
2563
2564     // Break it into (shuffle shuffle_hi, shuffle_lo).
2565     Locs.clear();
2566     std::vector<SDOperand> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2567     std::vector<SDOperand> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
2568     std::vector<SDOperand> *MaskPtr = &LoMask;
2569     unsigned MaskIdx = 0;
2570     unsigned LoIdx = 0;
2571     unsigned HiIdx = NumElems/2;
2572     for (unsigned i = 0; i != NumElems; ++i) {
2573       if (i == NumElems/2) {
2574         MaskPtr = &HiMask;
2575         MaskIdx = 1;
2576         LoIdx = 0;
2577         HiIdx = NumElems/2;
2578       }
2579       SDOperand Elt = PermMask.getOperand(i);
2580       if (Elt.getOpcode() == ISD::UNDEF) {
2581         Locs[i] = std::make_pair(-1, -1);
2582       } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
2583         Locs[i] = std::make_pair(MaskIdx, LoIdx);
2584         (*MaskPtr)[LoIdx] = Elt;
2585         LoIdx++;
2586       } else {
2587         Locs[i] = std::make_pair(MaskIdx, HiIdx);
2588         (*MaskPtr)[HiIdx] = Elt;
2589         HiIdx++;
2590       }
2591     }
2592
2593     SDOperand LoShuffle =
2594       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2595                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT, LoMask));
2596     SDOperand HiShuffle = 
2597       DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
2598                   DAG.getNode(ISD::BUILD_VECTOR, MaskVT, HiMask));
2599     std::vector<SDOperand> MaskOps;
2600     for (unsigned i = 0; i != NumElems; ++i) {
2601       if (Locs[i].first == -1) {
2602         MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
2603       } else {
2604         unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
2605         MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
2606       }
2607     }
2608     return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
2609                        DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskOps));
2610   }
2611
2612   return SDOperand();
2613 }
2614
2615 SDOperand
2616 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2617   if (!isa<ConstantSDNode>(Op.getOperand(1)))
2618     return SDOperand();
2619
2620   MVT::ValueType VT = Op.getValueType();
2621   // TODO: handle v16i8.
2622   if (MVT::getSizeInBits(VT) == 16) {
2623     // Transform it so it match pextrw which produces a 32-bit result.
2624     MVT::ValueType EVT = (MVT::ValueType)(VT+1);
2625     SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
2626                                     Op.getOperand(0), Op.getOperand(1));
2627     SDOperand Assert  = DAG.getNode(ISD::AssertZext, EVT, Extract,
2628                                     DAG.getValueType(VT));
2629     return DAG.getNode(ISD::TRUNCATE, VT, Assert);
2630   } else if (MVT::getSizeInBits(VT) == 32) {
2631     SDOperand Vec = Op.getOperand(0);
2632     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2633     if (Idx == 0)
2634       return Op;
2635     // SHUFPS the element to the lowest double word, then movss.
2636     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2637     std::vector<SDOperand> IdxVec;
2638     IdxVec.push_back(DAG.getConstant(Idx, MVT::getVectorBaseType(MaskVT)));
2639     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2640     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2641     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2642     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, IdxVec);
2643     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2644                       Vec, Vec, Mask);
2645     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2646                        DAG.getConstant(0, getPointerTy()));
2647   } else if (MVT::getSizeInBits(VT) == 64) {
2648     SDOperand Vec = Op.getOperand(0);
2649     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
2650     if (Idx == 0)
2651       return Op;
2652
2653     // UNPCKHPD the element to the lowest double word, then movsd.
2654     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
2655     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
2656     MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2657     std::vector<SDOperand> IdxVec;
2658     IdxVec.push_back(DAG.getConstant(1, MVT::getVectorBaseType(MaskVT)));
2659     IdxVec.push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorBaseType(MaskVT)));
2660     SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, IdxVec);
2661     Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
2662                       Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
2663     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
2664                        DAG.getConstant(0, getPointerTy()));
2665   }
2666
2667   return SDOperand();
2668 }
2669
2670 SDOperand
2671 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
2672   // Transform it so it match pinsrw which expects a 16-bit value in a GR32
2673   // as its second argument.
2674   MVT::ValueType VT = Op.getValueType();
2675   MVT::ValueType BaseVT = MVT::getVectorBaseType(VT);
2676   SDOperand N0 = Op.getOperand(0);
2677   SDOperand N1 = Op.getOperand(1);
2678   SDOperand N2 = Op.getOperand(2);
2679   if (MVT::getSizeInBits(BaseVT) == 16) {
2680     if (N1.getValueType() != MVT::i32)
2681       N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
2682     if (N2.getValueType() != MVT::i32)
2683       N2 = DAG.getConstant(cast<ConstantSDNode>(N2)->getValue(), MVT::i32);
2684     return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
2685   } else if (MVT::getSizeInBits(BaseVT) == 32) {
2686     unsigned Idx = cast<ConstantSDNode>(N2)->getValue();
2687     if (Idx == 0) {
2688       // Use a movss.
2689       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, N1);
2690       MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
2691       MVT::ValueType BaseVT = MVT::getVectorBaseType(MaskVT);
2692       std::vector<SDOperand> MaskVec;
2693       MaskVec.push_back(DAG.getConstant(4, BaseVT));
2694       for (unsigned i = 1; i <= 3; ++i)
2695         MaskVec.push_back(DAG.getConstant(i, BaseVT));
2696       return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, N0, N1,
2697                          DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec));
2698     } else {
2699       // Use two pinsrw instructions to insert a 32 bit value.
2700       Idx <<= 1;
2701       if (MVT::isFloatingPoint(N1.getValueType())) {
2702         if (N1.getOpcode() == ISD::LOAD) {
2703           // Just load directly from f32mem to GR32.
2704           N1 = DAG.getLoad(MVT::i32, N1.getOperand(0), N1.getOperand(1),
2705                            N1.getOperand(2));
2706         } else {
2707           N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4f32, N1);
2708           N1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, N1);
2709           N1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32, N1,
2710                            DAG.getConstant(0, getPointerTy()));
2711         }
2712       }
2713       N0 = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, N0);
2714       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2715                        DAG.getConstant(Idx, getPointerTy()));
2716       N1 = DAG.getNode(ISD::SRL, MVT::i32, N1, DAG.getConstant(16, MVT::i8));
2717       N0 = DAG.getNode(X86ISD::PINSRW, MVT::v8i16, N0, N1,
2718                        DAG.getConstant(Idx+1, getPointerTy()));
2719       return DAG.getNode(ISD::BIT_CONVERT, VT, N0);
2720     }
2721   }
2722
2723   return SDOperand();
2724 }
2725
2726 SDOperand
2727 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2728   SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
2729   return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
2730 }
2731
2732 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 
2733 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
2734 // one of the above mentioned nodes. It has to be wrapped because otherwise
2735 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2736 // be used to form addressing mode. These wrapped nodes will be selected
2737 // into MOV32ri.
2738 SDOperand
2739 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
2740   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2741   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2742                             DAG.getTargetConstantPool(CP->get(), getPointerTy(),
2743                                                       CP->getAlignment()));
2744   if (Subtarget->isTargetDarwin()) {
2745     // With PIC, the address is actually $g + Offset.
2746     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2747       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2748                     DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()), Result);
2749   }
2750
2751   return Result;
2752 }
2753
2754 SDOperand
2755 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
2756   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2757   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2758                                  DAG.getTargetGlobalAddress(GV,
2759                                                             getPointerTy()));
2760   if (Subtarget->isTargetDarwin()) {
2761     // With PIC, the address is actually $g + Offset.
2762     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2763       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2764                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2765                            Result);
2766
2767     // For Darwin, external and weak symbols are indirect, so we want to load
2768     // the value at address GV, not the value of GV itself. This means that
2769     // the GlobalAddress must be in the base or index register of the address,
2770     // not the GV offset field.
2771     if (getTargetMachine().getRelocationModel() != Reloc::Static &&
2772         DarwinGVRequiresExtraLoad(GV))
2773       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(),
2774                            Result, DAG.getSrcValue(NULL));
2775   }
2776
2777   return Result;
2778 }
2779
2780 SDOperand
2781 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
2782   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2783   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2784                                  DAG.getTargetExternalSymbol(Sym,
2785                                                              getPointerTy()));
2786   if (Subtarget->isTargetDarwin()) {
2787     // With PIC, the address is actually $g + Offset.
2788     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2789       Result = DAG.getNode(ISD::ADD, getPointerTy(),
2790                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
2791                            Result);
2792   }
2793
2794   return Result;
2795 }
2796
2797 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
2798     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
2799            "Not an i64 shift!");
2800     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
2801     SDOperand ShOpLo = Op.getOperand(0);
2802     SDOperand ShOpHi = Op.getOperand(1);
2803     SDOperand ShAmt  = Op.getOperand(2);
2804     SDOperand Tmp1 = isSRA ? DAG.getNode(ISD::SRA, MVT::i32, ShOpHi,
2805                                          DAG.getConstant(31, MVT::i8))
2806                            : DAG.getConstant(0, MVT::i32);
2807
2808     SDOperand Tmp2, Tmp3;
2809     if (Op.getOpcode() == ISD::SHL_PARTS) {
2810       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
2811       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
2812     } else {
2813       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
2814       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
2815     }
2816
2817     SDOperand InFlag = DAG.getNode(X86ISD::TEST, MVT::Flag,
2818                                    ShAmt, DAG.getConstant(32, MVT::i8));
2819
2820     SDOperand Hi, Lo;
2821     SDOperand CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
2822
2823     std::vector<MVT::ValueType> Tys;
2824     Tys.push_back(MVT::i32);
2825     Tys.push_back(MVT::Flag);
2826     std::vector<SDOperand> Ops;
2827     if (Op.getOpcode() == ISD::SHL_PARTS) {
2828       Ops.push_back(Tmp2);
2829       Ops.push_back(Tmp3);
2830       Ops.push_back(CC);
2831       Ops.push_back(InFlag);
2832       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2833       InFlag = Hi.getValue(1);
2834
2835       Ops.clear();
2836       Ops.push_back(Tmp3);
2837       Ops.push_back(Tmp1);
2838       Ops.push_back(CC);
2839       Ops.push_back(InFlag);
2840       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2841     } else {
2842       Ops.push_back(Tmp2);
2843       Ops.push_back(Tmp3);
2844       Ops.push_back(CC);
2845       Ops.push_back(InFlag);
2846       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2847       InFlag = Lo.getValue(1);
2848
2849       Ops.clear();
2850       Ops.push_back(Tmp3);
2851       Ops.push_back(Tmp1);
2852       Ops.push_back(CC);
2853       Ops.push_back(InFlag);
2854       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
2855     }
2856
2857     Tys.clear();
2858     Tys.push_back(MVT::i32);
2859     Tys.push_back(MVT::i32);
2860     Ops.clear();
2861     Ops.push_back(Lo);
2862     Ops.push_back(Hi);
2863     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
2864 }
2865
2866 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
2867   assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
2868          Op.getOperand(0).getValueType() >= MVT::i16 &&
2869          "Unknown SINT_TO_FP to lower!");
2870
2871   SDOperand Result;
2872   MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
2873   unsigned Size = MVT::getSizeInBits(SrcVT)/8;
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
2876   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
2877   SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other,
2878                                 DAG.getEntryNode(), Op.getOperand(0),
2879                                 StackSlot, DAG.getSrcValue(NULL));
2880
2881   // Build the FILD
2882   std::vector<MVT::ValueType> Tys;
2883   Tys.push_back(MVT::f64);
2884   Tys.push_back(MVT::Other);
2885   if (X86ScalarSSE) Tys.push_back(MVT::Flag);
2886   std::vector<SDOperand> Ops;
2887   Ops.push_back(Chain);
2888   Ops.push_back(StackSlot);
2889   Ops.push_back(DAG.getValueType(SrcVT));
2890   Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
2891                        Tys, Ops);
2892
2893   if (X86ScalarSSE) {
2894     Chain = Result.getValue(1);
2895     SDOperand InFlag = Result.getValue(2);
2896
2897     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
2898     // shouldn't be necessary except that RFP cannot be live across
2899     // multiple blocks. When stackifier is fixed, they can be uncoupled.
2900     MachineFunction &MF = DAG.getMachineFunction();
2901     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
2902     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
2903     std::vector<MVT::ValueType> Tys;
2904     Tys.push_back(MVT::Other);
2905     std::vector<SDOperand> Ops;
2906     Ops.push_back(Chain);
2907     Ops.push_back(Result);
2908     Ops.push_back(StackSlot);
2909     Ops.push_back(DAG.getValueType(Op.getValueType()));
2910     Ops.push_back(InFlag);
2911     Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
2912     Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
2913                          DAG.getSrcValue(NULL));
2914   }
2915
2916   return Result;
2917 }
2918
2919 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
2920   assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
2921          "Unknown FP_TO_SINT to lower!");
2922   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
2923   // stack slot.
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
2926   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
2927   SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
2928
2929   unsigned Opc;
2930   switch (Op.getValueType()) {
2931     default: assert(0 && "Invalid FP_TO_SINT to lower!");
2932     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
2933     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
2934     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
2935   }
2936
2937   SDOperand Chain = DAG.getEntryNode();
2938   SDOperand Value = Op.getOperand(0);
2939   if (X86ScalarSSE) {
2940     assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
2941     Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, StackSlot, 
2942                         DAG.getSrcValue(0));
2943     std::vector<MVT::ValueType> Tys;
2944     Tys.push_back(MVT::f64);
2945     Tys.push_back(MVT::Other);
2946     std::vector<SDOperand> Ops;
2947     Ops.push_back(Chain);
2948     Ops.push_back(StackSlot);
2949     Ops.push_back(DAG.getValueType(Op.getOperand(0).getValueType()));
2950     Value = DAG.getNode(X86ISD::FLD, Tys, Ops);
2951     Chain = Value.getValue(1);
2952     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
2953     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
2954   }
2955
2956   // Build the FP_TO_INT*_IN_MEM
2957   std::vector<SDOperand> Ops;
2958   Ops.push_back(Chain);
2959   Ops.push_back(Value);
2960   Ops.push_back(StackSlot);
2961   SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
2962
2963   // Load the result.
2964   return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
2965                      DAG.getSrcValue(NULL));
2966 }
2967
2968 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
2969   MVT::ValueType VT = Op.getValueType();
2970   const Type *OpNTy =  MVT::getTypeForValueType(VT);
2971   std::vector<Constant*> CV;
2972   if (VT == MVT::f64) {
2973     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
2974     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2975   } else {
2976     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
2977     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2978     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2979     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2980   }
2981   Constant *CS = ConstantStruct::get(CV);
2982   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
2983   SDOperand Mask 
2984     = DAG.getNode(X86ISD::LOAD_PACK,
2985                   VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
2986   return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
2987 }
2988
2989 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
2990   MVT::ValueType VT = Op.getValueType();
2991   const Type *OpNTy =  MVT::getTypeForValueType(VT);
2992   std::vector<Constant*> CV;
2993   if (VT == MVT::f64) {
2994     CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
2995     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2996   } else {
2997     CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
2998     CV.push_back(ConstantFP::get(OpNTy, 0.0));
2999     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3000     CV.push_back(ConstantFP::get(OpNTy, 0.0));
3001   }
3002   Constant *CS = ConstantStruct::get(CV);
3003   SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
3004   SDOperand Mask  = DAG.getNode(X86ISD::LOAD_PACK,
3005                           VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
3006   return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
3007 }
3008
3009 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
3010   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
3011   SDOperand Cond;
3012   SDOperand CC = Op.getOperand(2);
3013   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3014   bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
3015   bool Flip;
3016   unsigned X86CC;
3017   if (translateX86CC(CC, isFP, X86CC, Flip)) {
3018     if (Flip)
3019       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3020                          Op.getOperand(1), Op.getOperand(0));
3021     else
3022       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3023                          Op.getOperand(0), Op.getOperand(1));
3024     return DAG.getNode(X86ISD::SETCC, MVT::i8, 
3025                        DAG.getConstant(X86CC, MVT::i8), Cond);
3026   } else {
3027     assert(isFP && "Illegal integer SetCC!");
3028
3029     Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
3030                        Op.getOperand(0), Op.getOperand(1));
3031     std::vector<MVT::ValueType> Tys;
3032     std::vector<SDOperand> Ops;
3033     switch (SetCCOpcode) {
3034       default: assert(false && "Illegal floating point SetCC!");
3035       case ISD::SETOEQ: {  // !PF & ZF
3036         Tys.push_back(MVT::i8);
3037         Tys.push_back(MVT::Flag);
3038         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
3039         Ops.push_back(Cond);
3040         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3041         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
3042                                      DAG.getConstant(X86ISD::COND_E, MVT::i8),
3043                                      Tmp1.getValue(1));
3044         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
3045       }
3046       case ISD::SETUNE: {  // PF | !ZF
3047         Tys.push_back(MVT::i8);
3048         Tys.push_back(MVT::Flag);
3049         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
3050         Ops.push_back(Cond);
3051         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3052         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
3053                                      DAG.getConstant(X86ISD::COND_NE, MVT::i8),
3054                                      Tmp1.getValue(1));
3055         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
3056       }
3057     }
3058   }
3059 }
3060
3061 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
3062   MVT::ValueType VT = Op.getValueType();
3063   bool isFPStack = MVT::isFloatingPoint(VT) && !X86ScalarSSE;
3064   bool addTest   = false;
3065   SDOperand Op0 = Op.getOperand(0);
3066   SDOperand Cond, CC;
3067   if (Op0.getOpcode() == ISD::SETCC)
3068     Op0 = LowerOperation(Op0, DAG);
3069
3070   if (Op0.getOpcode() == X86ISD::SETCC) {
3071     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3072     // (since flag operand cannot be shared). If the X86ISD::SETCC does not
3073     // have another use it will be eliminated.
3074     // If the X86ISD::SETCC has more than one use, then it's probably better
3075     // to use a test instead of duplicating the X86ISD::CMP (for register
3076     // pressure reason).
3077     unsigned CmpOpc = Op0.getOperand(1).getOpcode();
3078     if (CmpOpc == X86ISD::CMP || CmpOpc == X86ISD::COMI ||
3079         CmpOpc == X86ISD::UCOMI) {
3080       if (!Op0.hasOneUse()) {
3081         std::vector<MVT::ValueType> Tys;
3082         for (unsigned i = 0; i < Op0.Val->getNumValues(); ++i)
3083           Tys.push_back(Op0.Val->getValueType(i));
3084         std::vector<SDOperand> Ops;
3085         for (unsigned i = 0; i < Op0.getNumOperands(); ++i)
3086           Ops.push_back(Op0.getOperand(i));
3087         Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3088       }
3089
3090       CC   = Op0.getOperand(0);
3091       Cond = Op0.getOperand(1);
3092       // Make a copy as flag result cannot be used by more than one.
3093       Cond = DAG.getNode(CmpOpc, MVT::Flag,
3094                          Cond.getOperand(0), Cond.getOperand(1));
3095       addTest =
3096         isFPStack && !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
3097     } else
3098       addTest = true;
3099   } else
3100     addTest = true;
3101
3102   if (addTest) {
3103     CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
3104     Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Op0, Op0);
3105   }
3106
3107   std::vector<MVT::ValueType> Tys;
3108   Tys.push_back(Op.getValueType());
3109   Tys.push_back(MVT::Flag);
3110   std::vector<SDOperand> Ops;
3111   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
3112   // condition is true.
3113   Ops.push_back(Op.getOperand(2));
3114   Ops.push_back(Op.getOperand(1));
3115   Ops.push_back(CC);
3116   Ops.push_back(Cond);
3117   return DAG.getNode(X86ISD::CMOV, Tys, Ops);
3118 }
3119
3120 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
3121   bool addTest = false;
3122   SDOperand Cond  = Op.getOperand(1);
3123   SDOperand Dest  = Op.getOperand(2);
3124   SDOperand CC;
3125   if (Cond.getOpcode() == ISD::SETCC)
3126     Cond = LowerOperation(Cond, DAG);
3127
3128   if (Cond.getOpcode() == X86ISD::SETCC) {
3129     // If condition flag is set by a X86ISD::CMP, then make a copy of it
3130     // (since flag operand cannot be shared). If the X86ISD::SETCC does not
3131     // have another use it will be eliminated.
3132     // If the X86ISD::SETCC has more than one use, then it's probably better
3133     // to use a test instead of duplicating the X86ISD::CMP (for register
3134     // pressure reason).
3135     unsigned CmpOpc = Cond.getOperand(1).getOpcode();
3136     if (CmpOpc == X86ISD::CMP || CmpOpc == X86ISD::COMI ||
3137         CmpOpc == X86ISD::UCOMI) {
3138       if (!Cond.hasOneUse()) {
3139         std::vector<MVT::ValueType> Tys;
3140         for (unsigned i = 0; i < Cond.Val->getNumValues(); ++i)
3141           Tys.push_back(Cond.Val->getValueType(i));
3142         std::vector<SDOperand> Ops;
3143         for (unsigned i = 0; i < Cond.getNumOperands(); ++i)
3144           Ops.push_back(Cond.getOperand(i));
3145         Cond = DAG.getNode(X86ISD::SETCC, Tys, Ops);
3146       }
3147
3148       CC   = Cond.getOperand(0);
3149       Cond = Cond.getOperand(1);
3150       // Make a copy as flag result cannot be used by more than one.
3151       Cond = DAG.getNode(CmpOpc, MVT::Flag,
3152                          Cond.getOperand(0), Cond.getOperand(1));
3153     } else
3154       addTest = true;
3155   } else
3156     addTest = true;
3157
3158   if (addTest) {
3159     CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
3160     Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Cond, Cond);
3161   }
3162   return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
3163                      Op.getOperand(0), Op.getOperand(2), CC, Cond);
3164 }
3165
3166 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3167   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3168   SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
3169                                  DAG.getTargetJumpTable(JT->getIndex(),
3170                                                         getPointerTy()));
3171   if (Subtarget->isTargetDarwin()) {
3172     // With PIC, the address is actually $g + Offset.
3173     if (getTargetMachine().getRelocationModel() == Reloc::PIC)
3174       Result = DAG.getNode(ISD::ADD, getPointerTy(),
3175                            DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3176                            Result);    
3177   }
3178
3179   return Result;
3180 }
3181
3182 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
3183   unsigned CallingConv= cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3184   if (CallingConv == CallingConv::Fast && EnableFastCC)
3185     return LowerFastCCCallTo(Op, DAG);
3186   else
3187     return LowerCCCCallTo(Op, DAG);
3188 }
3189
3190 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
3191   SDOperand Copy;
3192     
3193   switch(Op.getNumOperands()) {
3194     default:
3195       assert(0 && "Do not know how to return this many arguments!");
3196       abort();
3197     case 1:    // ret void.
3198       return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Op.getOperand(0),
3199                         DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
3200     case 3: {
3201       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
3202       
3203       if (MVT::isVector(ArgVT)) {
3204         // Integer or FP vector result -> XMM0.
3205         if (DAG.getMachineFunction().liveout_empty())
3206           DAG.getMachineFunction().addLiveOut(X86::XMM0);
3207         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::XMM0, Op.getOperand(1),
3208                                 SDOperand());
3209       } else if (MVT::isInteger(ArgVT)) {
3210         // Integer result -> EAX
3211         if (DAG.getMachineFunction().liveout_empty())
3212           DAG.getMachineFunction().addLiveOut(X86::EAX);
3213
3214         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EAX, Op.getOperand(1),
3215                                 SDOperand());
3216       } else if (!X86ScalarSSE) {
3217         // FP return with fp-stack value.
3218         if (DAG.getMachineFunction().liveout_empty())
3219           DAG.getMachineFunction().addLiveOut(X86::ST0);
3220
3221         std::vector<MVT::ValueType> Tys;
3222         Tys.push_back(MVT::Other);
3223         Tys.push_back(MVT::Flag);
3224         std::vector<SDOperand> Ops;
3225         Ops.push_back(Op.getOperand(0));
3226         Ops.push_back(Op.getOperand(1));
3227         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
3228       } else {
3229         // FP return with ScalarSSE (return on fp-stack).
3230         if (DAG.getMachineFunction().liveout_empty())
3231           DAG.getMachineFunction().addLiveOut(X86::ST0);
3232
3233         SDOperand MemLoc;
3234         SDOperand Chain = Op.getOperand(0);
3235         SDOperand Value = Op.getOperand(1);
3236
3237         if (Value.getOpcode() == ISD::LOAD &&
3238             (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
3239           Chain  = Value.getOperand(0);
3240           MemLoc = Value.getOperand(1);
3241         } else {
3242           // Spill the value to memory and reload it into top of stack.
3243           unsigned Size = MVT::getSizeInBits(ArgVT)/8;
3244           MachineFunction &MF = DAG.getMachineFunction();
3245           int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
3246           MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
3247           Chain = DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), 
3248                               Value, MemLoc, DAG.getSrcValue(0));
3249         }
3250         std::vector<MVT::ValueType> Tys;
3251         Tys.push_back(MVT::f64);
3252         Tys.push_back(MVT::Other);
3253         std::vector<SDOperand> Ops;
3254         Ops.push_back(Chain);
3255         Ops.push_back(MemLoc);
3256         Ops.push_back(DAG.getValueType(ArgVT));
3257         Copy = DAG.getNode(X86ISD::FLD, Tys, Ops);
3258         Tys.clear();
3259         Tys.push_back(MVT::Other);
3260         Tys.push_back(MVT::Flag);
3261         Ops.clear();
3262         Ops.push_back(Copy.getValue(1));
3263         Ops.push_back(Copy);
3264         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
3265       }
3266       break;
3267     }
3268     case 5:
3269       if (DAG.getMachineFunction().liveout_empty()) {
3270         DAG.getMachineFunction().addLiveOut(X86::EAX);
3271         DAG.getMachineFunction().addLiveOut(X86::EDX);
3272       }
3273
3274       Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EDX, Op.getOperand(3), 
3275                               SDOperand());
3276       Copy = DAG.getCopyToReg(Copy, X86::EAX,Op.getOperand(1),Copy.getValue(1));
3277       break;
3278   }
3279   return DAG.getNode(X86ISD::RET_FLAG, MVT::Other,
3280                    Copy, DAG.getConstant(getBytesToPopOnReturn(), MVT::i16),
3281                      Copy.getValue(1));
3282 }
3283
3284 SDOperand
3285 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
3286   MachineFunction &MF = DAG.getMachineFunction();
3287   const Function* Fn = MF.getFunction();
3288   if (Fn->hasExternalLinkage() &&
3289       Subtarget->TargetType == X86Subtarget::isCygwin &&
3290       Fn->getName() == "main")
3291     MF.getInfo<X86FunctionInfo>()->setForceFramePointer(true);
3292
3293   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3294   if (CC == CallingConv::Fast && EnableFastCC)
3295     return LowerFastCCArguments(Op, DAG);
3296   else
3297     return LowerCCCArguments(Op, DAG);
3298 }
3299
3300 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
3301   SDOperand InFlag(0, 0);
3302   SDOperand Chain = Op.getOperand(0);
3303   unsigned Align =
3304     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3305   if (Align == 0) Align = 1;
3306
3307   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3308   // If not DWORD aligned, call memset if size is less than the threshold.
3309   // It knows how to align to the right boundary first.
3310   if ((Align & 3) != 0 ||
3311       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3312     MVT::ValueType IntPtr = getPointerTy();
3313     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3314     std::vector<std::pair<SDOperand, const Type*> > Args;
3315     Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
3316     // Extend the ubyte argument to be an int value for the call.
3317     SDOperand Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
3318     Args.push_back(std::make_pair(Val, IntPtrTy));
3319     Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
3320     std::pair<SDOperand,SDOperand> CallResult =
3321       LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
3322                   DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
3323     return CallResult.second;
3324   }
3325
3326   MVT::ValueType AVT;
3327   SDOperand Count;
3328   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3329   unsigned BytesLeft = 0;
3330   bool TwoRepStos = false;
3331   if (ValC) {
3332     unsigned ValReg;
3333     unsigned Val = ValC->getValue() & 255;
3334
3335     // If the value is a constant, then we can potentially use larger sets.
3336     switch (Align & 3) {
3337       case 2:   // WORD aligned
3338         AVT = MVT::i16;
3339         Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
3340         BytesLeft = I->getValue() % 2;
3341         Val    = (Val << 8) | Val;
3342         ValReg = X86::AX;
3343         break;
3344       case 0:   // DWORD aligned
3345         AVT = MVT::i32;
3346         if (I) {
3347           Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
3348           BytesLeft = I->getValue() % 4;
3349         } else {
3350           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
3351                               DAG.getConstant(2, MVT::i8));
3352           TwoRepStos = true;
3353         }
3354         Val = (Val << 8)  | Val;
3355         Val = (Val << 16) | Val;
3356         ValReg = X86::EAX;
3357         break;
3358       default:  // Byte aligned
3359         AVT = MVT::i8;
3360         Count = Op.getOperand(3);
3361         ValReg = X86::AL;
3362         break;
3363     }
3364
3365     Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
3366                               InFlag);
3367     InFlag = Chain.getValue(1);
3368   } else {
3369     AVT = MVT::i8;
3370     Count  = Op.getOperand(3);
3371     Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
3372     InFlag = Chain.getValue(1);
3373   }
3374
3375   Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
3376   InFlag = Chain.getValue(1);
3377   Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
3378   InFlag = Chain.getValue(1);
3379
3380   std::vector<MVT::ValueType> Tys;
3381   Tys.push_back(MVT::Other);
3382   Tys.push_back(MVT::Flag);
3383   std::vector<SDOperand> Ops;
3384   Ops.push_back(Chain);
3385   Ops.push_back(DAG.getValueType(AVT));
3386   Ops.push_back(InFlag);
3387   Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
3388
3389   if (TwoRepStos) {
3390     InFlag = Chain.getValue(1);
3391     Count = Op.getOperand(3);
3392     MVT::ValueType CVT = Count.getValueType();
3393     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3394                                  DAG.getConstant(3, CVT));
3395     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
3396     InFlag = Chain.getValue(1);
3397     Tys.clear();
3398     Tys.push_back(MVT::Other);
3399     Tys.push_back(MVT::Flag);
3400     Ops.clear();
3401     Ops.push_back(Chain);
3402     Ops.push_back(DAG.getValueType(MVT::i8));
3403     Ops.push_back(InFlag);
3404     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
3405   } else if (BytesLeft) {
3406     // Issue stores for the last 1 - 3 bytes.
3407     SDOperand Value;
3408     unsigned Val = ValC->getValue() & 255;
3409     unsigned Offset = I->getValue() - BytesLeft;
3410     SDOperand DstAddr = Op.getOperand(1);
3411     MVT::ValueType AddrVT = DstAddr.getValueType();
3412     if (BytesLeft >= 2) {
3413       Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
3414       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3415                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3416                                       DAG.getConstant(Offset, AddrVT)),
3417                           DAG.getSrcValue(NULL));
3418       BytesLeft -= 2;
3419       Offset += 2;
3420     }
3421
3422     if (BytesLeft == 1) {
3423       Value = DAG.getConstant(Val, MVT::i8);
3424       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3425                           DAG.getNode(ISD::ADD, AddrVT, DstAddr,
3426                                       DAG.getConstant(Offset, AddrVT)),
3427                           DAG.getSrcValue(NULL));
3428     }
3429   }
3430
3431   return Chain;
3432 }
3433
3434 SDOperand X86TargetLowering::LowerMEMCPY(SDOperand Op, SelectionDAG &DAG) {
3435   SDOperand Chain = Op.getOperand(0);
3436   unsigned Align =
3437     (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
3438   if (Align == 0) Align = 1;
3439
3440   ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
3441   // If not DWORD aligned, call memcpy if size is less than the threshold.
3442   // It knows how to align to the right boundary first.
3443   if ((Align & 3) != 0 ||
3444       (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
3445     MVT::ValueType IntPtr = getPointerTy();
3446     const Type *IntPtrTy = getTargetData()->getIntPtrType();
3447     std::vector<std::pair<SDOperand, const Type*> > Args;
3448     Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
3449     Args.push_back(std::make_pair(Op.getOperand(2), IntPtrTy));
3450     Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
3451     std::pair<SDOperand,SDOperand> CallResult =
3452       LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
3453                   DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
3454     return CallResult.second;
3455   }
3456
3457   MVT::ValueType AVT;
3458   SDOperand Count;
3459   unsigned BytesLeft = 0;
3460   bool TwoRepMovs = false;
3461   switch (Align & 3) {
3462     case 2:   // WORD aligned
3463       AVT = MVT::i16;
3464       Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
3465       BytesLeft = I->getValue() % 2;
3466       break;
3467     case 0:   // DWORD aligned
3468       AVT = MVT::i32;
3469       if (I) {
3470         Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
3471         BytesLeft = I->getValue() % 4;
3472       } else {
3473         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
3474                             DAG.getConstant(2, MVT::i8));
3475         TwoRepMovs = true;
3476       }
3477       break;
3478     default:  // Byte aligned
3479       AVT = MVT::i8;
3480       Count = Op.getOperand(3);
3481       break;
3482   }
3483
3484   SDOperand InFlag(0, 0);
3485   Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
3486   InFlag = Chain.getValue(1);
3487   Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
3488   InFlag = Chain.getValue(1);
3489   Chain  = DAG.getCopyToReg(Chain, X86::ESI, Op.getOperand(2), InFlag);
3490   InFlag = Chain.getValue(1);
3491
3492   std::vector<MVT::ValueType> Tys;
3493   Tys.push_back(MVT::Other);
3494   Tys.push_back(MVT::Flag);
3495   std::vector<SDOperand> Ops;
3496   Ops.push_back(Chain);
3497   Ops.push_back(DAG.getValueType(AVT));
3498   Ops.push_back(InFlag);
3499   Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
3500
3501   if (TwoRepMovs) {
3502     InFlag = Chain.getValue(1);
3503     Count = Op.getOperand(3);
3504     MVT::ValueType CVT = Count.getValueType();
3505     SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
3506                                  DAG.getConstant(3, CVT));
3507     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
3508     InFlag = Chain.getValue(1);
3509     Tys.clear();
3510     Tys.push_back(MVT::Other);
3511     Tys.push_back(MVT::Flag);
3512     Ops.clear();
3513     Ops.push_back(Chain);
3514     Ops.push_back(DAG.getValueType(MVT::i8));
3515     Ops.push_back(InFlag);
3516     Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
3517   } else if (BytesLeft) {
3518     // Issue loads and stores for the last 1 - 3 bytes.
3519     unsigned Offset = I->getValue() - BytesLeft;
3520     SDOperand DstAddr = Op.getOperand(1);
3521     MVT::ValueType DstVT = DstAddr.getValueType();
3522     SDOperand SrcAddr = Op.getOperand(2);
3523     MVT::ValueType SrcVT = SrcAddr.getValueType();
3524     SDOperand Value;
3525     if (BytesLeft >= 2) {
3526       Value = DAG.getLoad(MVT::i16, Chain,
3527                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3528                                       DAG.getConstant(Offset, SrcVT)),
3529                           DAG.getSrcValue(NULL));
3530       Chain = Value.getValue(1);
3531       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3532                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
3533                                       DAG.getConstant(Offset, DstVT)),
3534                           DAG.getSrcValue(NULL));
3535       BytesLeft -= 2;
3536       Offset += 2;
3537     }
3538
3539     if (BytesLeft == 1) {
3540       Value = DAG.getLoad(MVT::i8, Chain,
3541                           DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
3542                                       DAG.getConstant(Offset, SrcVT)),
3543                           DAG.getSrcValue(NULL));
3544       Chain = Value.getValue(1);
3545       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
3546                           DAG.getNode(ISD::ADD, DstVT, DstAddr,
3547                                       DAG.getConstant(Offset, DstVT)),
3548                           DAG.getSrcValue(NULL));
3549     }
3550   }
3551
3552   return Chain;
3553 }
3554
3555 SDOperand
3556 X86TargetLowering::LowerREADCYCLCECOUNTER(SDOperand Op, SelectionDAG &DAG) {
3557   std::vector<MVT::ValueType> Tys;
3558   Tys.push_back(MVT::Other);
3559   Tys.push_back(MVT::Flag);
3560   std::vector<SDOperand> Ops;
3561   Ops.push_back(Op.getOperand(0));
3562   SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, Ops);
3563   Ops.clear();
3564   Ops.push_back(DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1)));
3565   Ops.push_back(DAG.getCopyFromReg(Ops[0].getValue(1), X86::EDX, 
3566                                    MVT::i32, Ops[0].getValue(2)));
3567   Ops.push_back(Ops[1].getValue(1));
3568   Tys[0] = Tys[1] = MVT::i32;
3569   Tys.push_back(MVT::Other);
3570   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
3571 }
3572
3573 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
3574   // vastart just stores the address of the VarArgsFrameIndex slot into the
3575   // memory location argument.
3576   // FIXME: Replace MVT::i32 with PointerTy
3577   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
3578   return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
3579                      Op.getOperand(1), Op.getOperand(2));
3580 }
3581
3582 SDOperand
3583 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
3584   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
3585   switch (IntNo) {
3586   default: return SDOperand();    // Don't custom lower most intrinsics.
3587     // Comparison intrinsics.
3588   case Intrinsic::x86_sse_comieq_ss:
3589   case Intrinsic::x86_sse_comilt_ss:
3590   case Intrinsic::x86_sse_comile_ss:
3591   case Intrinsic::x86_sse_comigt_ss:
3592   case Intrinsic::x86_sse_comige_ss:
3593   case Intrinsic::x86_sse_comineq_ss:
3594   case Intrinsic::x86_sse_ucomieq_ss:
3595   case Intrinsic::x86_sse_ucomilt_ss:
3596   case Intrinsic::x86_sse_ucomile_ss:
3597   case Intrinsic::x86_sse_ucomigt_ss:
3598   case Intrinsic::x86_sse_ucomige_ss:
3599   case Intrinsic::x86_sse_ucomineq_ss:
3600   case Intrinsic::x86_sse2_comieq_sd:
3601   case Intrinsic::x86_sse2_comilt_sd:
3602   case Intrinsic::x86_sse2_comile_sd:
3603   case Intrinsic::x86_sse2_comigt_sd:
3604   case Intrinsic::x86_sse2_comige_sd:
3605   case Intrinsic::x86_sse2_comineq_sd:
3606   case Intrinsic::x86_sse2_ucomieq_sd:
3607   case Intrinsic::x86_sse2_ucomilt_sd:
3608   case Intrinsic::x86_sse2_ucomile_sd:
3609   case Intrinsic::x86_sse2_ucomigt_sd:
3610   case Intrinsic::x86_sse2_ucomige_sd:
3611   case Intrinsic::x86_sse2_ucomineq_sd: {
3612     unsigned Opc = 0;
3613     ISD::CondCode CC = ISD::SETCC_INVALID;
3614     switch (IntNo) {
3615     default: break;
3616     case Intrinsic::x86_sse_comieq_ss: 
3617     case Intrinsic::x86_sse2_comieq_sd: 
3618       Opc = X86ISD::COMI;
3619       CC = ISD::SETEQ;
3620       break;
3621     case Intrinsic::x86_sse_comilt_ss:
3622     case Intrinsic::x86_sse2_comilt_sd:
3623       Opc = X86ISD::COMI;
3624       CC = ISD::SETLT;
3625       break;
3626     case Intrinsic::x86_sse_comile_ss:
3627     case Intrinsic::x86_sse2_comile_sd:
3628       Opc = X86ISD::COMI;
3629       CC = ISD::SETLE;
3630       break;
3631     case Intrinsic::x86_sse_comigt_ss:
3632     case Intrinsic::x86_sse2_comigt_sd:
3633       Opc = X86ISD::COMI;
3634       CC = ISD::SETGT;
3635       break;
3636     case Intrinsic::x86_sse_comige_ss:
3637     case Intrinsic::x86_sse2_comige_sd:
3638       Opc = X86ISD::COMI;
3639       CC = ISD::SETGE;
3640       break;
3641     case Intrinsic::x86_sse_comineq_ss:
3642     case Intrinsic::x86_sse2_comineq_sd:
3643       Opc = X86ISD::COMI;
3644       CC = ISD::SETNE;
3645       break;
3646     case Intrinsic::x86_sse_ucomieq_ss:
3647     case Intrinsic::x86_sse2_ucomieq_sd:
3648       Opc = X86ISD::UCOMI;
3649       CC = ISD::SETEQ;
3650       break;
3651     case Intrinsic::x86_sse_ucomilt_ss:
3652     case Intrinsic::x86_sse2_ucomilt_sd:
3653       Opc = X86ISD::UCOMI;
3654       CC = ISD::SETLT;
3655       break;
3656     case Intrinsic::x86_sse_ucomile_ss:
3657     case Intrinsic::x86_sse2_ucomile_sd:
3658       Opc = X86ISD::UCOMI;
3659       CC = ISD::SETLE;
3660       break;
3661     case Intrinsic::x86_sse_ucomigt_ss:
3662     case Intrinsic::x86_sse2_ucomigt_sd:
3663       Opc = X86ISD::UCOMI;
3664       CC = ISD::SETGT;
3665       break;
3666     case Intrinsic::x86_sse_ucomige_ss:
3667     case Intrinsic::x86_sse2_ucomige_sd:
3668       Opc = X86ISD::UCOMI;
3669       CC = ISD::SETGE;
3670       break;
3671     case Intrinsic::x86_sse_ucomineq_ss:
3672     case Intrinsic::x86_sse2_ucomineq_sd:
3673       Opc = X86ISD::UCOMI;
3674       CC = ISD::SETNE;
3675       break;
3676     }
3677     bool Flip;
3678     unsigned X86CC;
3679     translateX86CC(CC, true, X86CC, Flip);
3680     SDOperand Cond = DAG.getNode(Opc, MVT::Flag, Op.getOperand(Flip?2:1),
3681                                  Op.getOperand(Flip?1:2));
3682     SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8, 
3683                                   DAG.getConstant(X86CC, MVT::i8), Cond);
3684     return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
3685   }
3686   }
3687 }
3688
3689 /// LowerOperation - Provide custom lowering hooks for some operations.
3690 ///
3691 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3692   switch (Op.getOpcode()) {
3693   default: assert(0 && "Should not custom lower this!");
3694   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
3695   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
3696   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
3697   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
3698   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
3699   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
3700   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
3701   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
3702   case ISD::SHL_PARTS:
3703   case ISD::SRA_PARTS:
3704   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
3705   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
3706   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
3707   case ISD::FABS:               return LowerFABS(Op, DAG);
3708   case ISD::FNEG:               return LowerFNEG(Op, DAG);
3709   case ISD::SETCC:              return LowerSETCC(Op, DAG);
3710   case ISD::SELECT:             return LowerSELECT(Op, DAG);
3711   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
3712   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
3713   case ISD::CALL:               return LowerCALL(Op, DAG);
3714   case ISD::RET:                return LowerRET(Op, DAG);
3715   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
3716   case ISD::MEMSET:             return LowerMEMSET(Op, DAG);
3717   case ISD::MEMCPY:             return LowerMEMCPY(Op, DAG);
3718   case ISD::READCYCLECOUNTER:   return LowerREADCYCLCECOUNTER(Op, DAG);
3719   case ISD::VASTART:            return LowerVASTART(Op, DAG);
3720   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3721   }
3722 }
3723
3724 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
3725   switch (Opcode) {
3726   default: return NULL;
3727   case X86ISD::SHLD:               return "X86ISD::SHLD";
3728   case X86ISD::SHRD:               return "X86ISD::SHRD";
3729   case X86ISD::FAND:               return "X86ISD::FAND";
3730   case X86ISD::FXOR:               return "X86ISD::FXOR";
3731   case X86ISD::FILD:               return "X86ISD::FILD";
3732   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
3733   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
3734   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
3735   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
3736   case X86ISD::FLD:                return "X86ISD::FLD";
3737   case X86ISD::FST:                return "X86ISD::FST";
3738   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
3739   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
3740   case X86ISD::CALL:               return "X86ISD::CALL";
3741   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
3742   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
3743   case X86ISD::CMP:                return "X86ISD::CMP";
3744   case X86ISD::TEST:               return "X86ISD::TEST";
3745   case X86ISD::COMI:               return "X86ISD::COMI";
3746   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
3747   case X86ISD::SETCC:              return "X86ISD::SETCC";
3748   case X86ISD::CMOV:               return "X86ISD::CMOV";
3749   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
3750   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
3751   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
3752   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
3753   case X86ISD::LOAD_PACK:          return "X86ISD::LOAD_PACK";
3754   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
3755   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
3756   case X86ISD::S2VEC:              return "X86ISD::S2VEC";
3757   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
3758   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
3759   }
3760 }
3761
3762 /// isLegalAddressImmediate - Return true if the integer value or
3763 /// GlobalValue can be used as the offset of the target addressing mode.
3764 bool X86TargetLowering::isLegalAddressImmediate(int64_t V) const {
3765   // X86 allows a sign-extended 32-bit immediate field.
3766   return (V > -(1LL << 32) && V < (1LL << 32)-1);
3767 }
3768
3769 bool X86TargetLowering::isLegalAddressImmediate(GlobalValue *GV) const {
3770   // GV is 64-bit but displacement field is 32-bit unless we are in small code
3771   // model. Mac OS X happens to support only small PIC code model.
3772   // FIXME: better support for other OS's.
3773   if (Subtarget->is64Bit() && !Subtarget->isTargetDarwin())
3774     return false;
3775   if (Subtarget->isTargetDarwin()) {
3776     Reloc::Model RModel = getTargetMachine().getRelocationModel();
3777     if (RModel == Reloc::Static)
3778       return true;
3779     else if (RModel == Reloc::DynamicNoPIC)
3780       return !DarwinGVRequiresExtraLoad(GV);
3781     else
3782       return false;
3783   } else
3784     return true;
3785 }
3786
3787 /// isShuffleMaskLegal - Targets can use this to indicate that they only
3788 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
3789 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
3790 /// are assumed to be legal.
3791 bool
3792 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
3793   // Only do shuffles on 128-bit vector types for now.
3794   if (MVT::getSizeInBits(VT) == 64) return false;
3795   return (Mask.Val->getNumOperands() <= 4 ||
3796           isSplatMask(Mask.Val)  ||
3797           isPSHUFHW_PSHUFLWMask(Mask.Val) ||
3798           X86::isUNPCKLMask(Mask.Val) ||
3799           X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
3800           X86::isUNPCKHMask(Mask.Val));
3801 }
3802
3803 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
3804                                                MVT::ValueType EVT,
3805                                                SelectionDAG &DAG) const {
3806   unsigned NumElts = BVOps.size();
3807   // Only do shuffles on 128-bit vector types for now.
3808   if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
3809   if (NumElts == 2) return true;
3810   if (NumElts == 4) {
3811     return (isMOVLMask(BVOps)  || isCommutedMOVL(BVOps, true) ||
3812             isSHUFPMask(BVOps) || isCommutedSHUFP(BVOps));
3813   }
3814   return false;
3815 }
3816
3817 //===----------------------------------------------------------------------===//
3818 //                           X86 Scheduler Hooks
3819 //===----------------------------------------------------------------------===//
3820
3821 MachineBasicBlock *
3822 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3823                                            MachineBasicBlock *BB) {
3824   switch (MI->getOpcode()) {
3825   default: assert(false && "Unexpected instr type to insert");
3826   case X86::CMOV_FR32:
3827   case X86::CMOV_FR64:
3828   case X86::CMOV_V4F32:
3829   case X86::CMOV_V2F64:
3830   case X86::CMOV_V2I64: {
3831     // To "insert" a SELECT_CC instruction, we actually have to insert the
3832     // diamond control-flow pattern.  The incoming instruction knows the
3833     // destination vreg to set, the condition code register to branch on, the
3834     // true/false values to select between, and a branch opcode to use.
3835     const BasicBlock *LLVM_BB = BB->getBasicBlock();
3836     ilist<MachineBasicBlock>::iterator It = BB;
3837     ++It;
3838   
3839     //  thisMBB:
3840     //  ...
3841     //   TrueVal = ...
3842     //   cmpTY ccX, r1, r2
3843     //   bCC copy1MBB
3844     //   fallthrough --> copy0MBB
3845     MachineBasicBlock *thisMBB = BB;
3846     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
3847     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
3848     unsigned Opc = getCondBrOpcodeForX86CC(MI->getOperand(3).getImmedValue());
3849     BuildMI(BB, Opc, 1).addMBB(sinkMBB);
3850     MachineFunction *F = BB->getParent();
3851     F->getBasicBlockList().insert(It, copy0MBB);
3852     F->getBasicBlockList().insert(It, sinkMBB);
3853     // Update machine-CFG edges by first adding all successors of the current
3854     // block to the new block which will contain the Phi node for the select.
3855     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
3856         e = BB->succ_end(); i != e; ++i)
3857       sinkMBB->addSuccessor(*i);
3858     // Next, remove all successors of the current block, and add the true
3859     // and fallthrough blocks as its successors.
3860     while(!BB->succ_empty())
3861       BB->removeSuccessor(BB->succ_begin());
3862     BB->addSuccessor(copy0MBB);
3863     BB->addSuccessor(sinkMBB);
3864   
3865     //  copy0MBB:
3866     //   %FalseValue = ...
3867     //   # fallthrough to sinkMBB
3868     BB = copy0MBB;
3869   
3870     // Update machine-CFG edges
3871     BB->addSuccessor(sinkMBB);
3872   
3873     //  sinkMBB:
3874     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
3875     //  ...
3876     BB = sinkMBB;
3877     BuildMI(BB, X86::PHI, 4, MI->getOperand(0).getReg())
3878       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
3879       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
3880
3881     delete MI;   // The pseudo instruction is gone now.
3882     return BB;
3883   }
3884
3885   case X86::FP_TO_INT16_IN_MEM:
3886   case X86::FP_TO_INT32_IN_MEM:
3887   case X86::FP_TO_INT64_IN_MEM: {
3888     // Change the floating point control register to use "round towards zero"
3889     // mode when truncating to an integer value.
3890     MachineFunction *F = BB->getParent();
3891     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3892     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
3893
3894     // Load the old value of the high byte of the control word...
3895     unsigned OldCW =
3896       F->getSSARegMap()->createVirtualRegister(X86::GR16RegisterClass);
3897     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
3898
3899     // Set the high part to be round to zero...
3900     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
3901
3902     // Reload the modified control word now...
3903     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
3904
3905     // Restore the memory image of control word to original value
3906     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
3907
3908     // Get the X86 opcode to use.
3909     unsigned Opc;
3910     switch (MI->getOpcode()) {
3911     default: assert(0 && "illegal opcode!");
3912     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
3913     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
3914     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
3915     }
3916
3917     X86AddressMode AM;
3918     MachineOperand &Op = MI->getOperand(0);
3919     if (Op.isRegister()) {
3920       AM.BaseType = X86AddressMode::RegBase;
3921       AM.Base.Reg = Op.getReg();
3922     } else {
3923       AM.BaseType = X86AddressMode::FrameIndexBase;
3924       AM.Base.FrameIndex = Op.getFrameIndex();
3925     }
3926     Op = MI->getOperand(1);
3927     if (Op.isImmediate())
3928       AM.Scale = Op.getImmedValue();
3929     Op = MI->getOperand(2);
3930     if (Op.isImmediate())
3931       AM.IndexReg = Op.getImmedValue();
3932     Op = MI->getOperand(3);
3933     if (Op.isGlobalAddress()) {
3934       AM.GV = Op.getGlobal();
3935     } else {
3936       AM.Disp = Op.getImmedValue();
3937     }
3938     addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(MI->getOperand(4).getReg());
3939
3940     // Reload the original control word now.
3941     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
3942
3943     delete MI;   // The pseudo instruction is gone now.
3944     return BB;
3945   }
3946   }
3947 }
3948
3949 //===----------------------------------------------------------------------===//
3950 //                           X86 Optimization Hooks
3951 //===----------------------------------------------------------------------===//
3952
3953 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
3954                                                        uint64_t Mask,
3955                                                        uint64_t &KnownZero, 
3956                                                        uint64_t &KnownOne,
3957                                                        unsigned Depth) const {
3958   unsigned Opc = Op.getOpcode();
3959   assert((Opc >= ISD::BUILTIN_OP_END ||
3960           Opc == ISD::INTRINSIC_WO_CHAIN ||
3961           Opc == ISD::INTRINSIC_W_CHAIN ||
3962           Opc == ISD::INTRINSIC_VOID) &&
3963          "Should use MaskedValueIsZero if you don't know whether Op"
3964          " is a target node!");
3965
3966   KnownZero = KnownOne = 0;   // Don't know anything.
3967   switch (Opc) {
3968   default: break;
3969   case X86ISD::SETCC: 
3970     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
3971     break;
3972   }
3973 }
3974
3975 //===----------------------------------------------------------------------===//
3976 //                           X86 Inline Assembly Support
3977 //===----------------------------------------------------------------------===//
3978
3979 std::vector<unsigned> X86TargetLowering::
3980 getRegClassForInlineAsmConstraint(const std::string &Constraint,
3981                                   MVT::ValueType VT) const {
3982   if (Constraint.size() == 1) {
3983     // FIXME: not handling fp-stack yet!
3984     // FIXME: not handling MMX registers yet ('y' constraint).
3985     switch (Constraint[0]) {      // GCC X86 Constraint Letters
3986     default: break;  // Unknown constriant letter
3987     case 'r':   // GENERAL_REGS
3988     case 'R':   // LEGACY_REGS
3989       if (VT == MVT::i32)
3990         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
3991                                      X86::ESI, X86::EDI, X86::EBP, X86::ESP, 0);
3992       else if (VT == MVT::i16)
3993         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 
3994                                      X86::SI, X86::DI, X86::BP, X86::SP, 0);
3995       else if (VT == MVT::i8)
3996         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
3997       break;
3998     case 'l':   // INDEX_REGS
3999       if (VT == MVT::i32)
4000         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
4001                                      X86::ESI, X86::EDI, X86::EBP, 0);
4002       else if (VT == MVT::i16)
4003         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 
4004                                      X86::SI, X86::DI, X86::BP, 0);
4005       else if (VT == MVT::i8)
4006         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4007       break;
4008     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
4009     case 'Q':   // Q_REGS
4010       if (VT == MVT::i32)
4011         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
4012       else if (VT == MVT::i16)
4013         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
4014       else if (VT == MVT::i8)
4015         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::DL, 0);
4016         break;
4017     case 'x':   // SSE_REGS if SSE1 allowed
4018       if (Subtarget->hasSSE1())
4019         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4020                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
4021                                      0);
4022       return std::vector<unsigned>();
4023     case 'Y':   // SSE_REGS if SSE2 allowed
4024       if (Subtarget->hasSSE2())
4025         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
4026                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
4027                                      0);
4028       return std::vector<unsigned>();
4029     }
4030   }
4031   
4032   return std::vector<unsigned>();
4033 }