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