5873716d47073f9ffb5b9d758ff3483bc3cc19ca
[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/Function.h"
22 #include "llvm/ADT/VectorExtras.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SSARegMap.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Target/TargetOptions.h"
31 using namespace llvm;
32
33 // FIXME: temporary.
34 #include "llvm/Support/CommandLine.h"
35 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
36                                   cl::desc("Enable fastcc on X86"));
37
38 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
39   : TargetLowering(TM) {
40   Subtarget = &TM.getSubtarget<X86Subtarget>();
41   X86ScalarSSE = Subtarget->hasSSE2();
42
43   // Set up the TargetLowering object.
44
45   // X86 is weird, it always uses i8 for shift amounts and setcc results.
46   setShiftAmountType(MVT::i8);
47   setSetCCResultType(MVT::i8);
48   setSetCCResultContents(ZeroOrOneSetCCResult);
49   setSchedulingPreference(SchedulingForRegPressure);
50   setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
51   setStackPointerRegisterToSaveRestore(X86::ESP);
52
53   // Add legal addressing mode scale values.
54   addLegalAddressScale(8);
55   addLegalAddressScale(4);
56   addLegalAddressScale(2);
57   // Enter the ones which require both scale + index last. These are more
58   // expensive.
59   addLegalAddressScale(9);
60   addLegalAddressScale(5);
61   addLegalAddressScale(3);
62   
63   // Set up the register classes.
64   addRegisterClass(MVT::i8, X86::R8RegisterClass);
65   addRegisterClass(MVT::i16, X86::R16RegisterClass);
66   addRegisterClass(MVT::i32, X86::R32RegisterClass);
67
68   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
69   // operation.
70   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
71   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
72   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
73
74   if (X86ScalarSSE)
75     // No SSE i64 SINT_TO_FP, so expand i32 UINT_TO_FP instead.
76     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Expand);
77   else
78     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
79
80   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
81   // this operation.
82   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
83   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
84   // SSE has no i16 to fp conversion, only i32
85   if (X86ScalarSSE)
86     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
87   else {
88     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
89     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
90   }
91
92   // We can handle SINT_TO_FP and FP_TO_SINT from/to i64 even though i64
93   // isn't legal.
94   setOperationAction(ISD::SINT_TO_FP       , MVT::i64  , Custom);
95   setOperationAction(ISD::FP_TO_SINT       , MVT::i64  , Custom);
96
97   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
98   // this operation.
99   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
100   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
101
102   if (X86ScalarSSE) {
103     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
104   } else {
105     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
106     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
107   }
108
109   // Handle FP_TO_UINT by promoting the destination to a larger signed
110   // conversion.
111   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
112   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
113   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
114
115   if (X86ScalarSSE && !Subtarget->hasSSE3())
116     // Expand FP_TO_UINT into a select.
117     // FIXME: We would like to use a Custom expander here eventually to do
118     // the optimal thing for SSE vs. the default expansion in the legalizer.
119     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Expand);
120   else
121     // With SSE3 we can use fisttpll to convert to a signed i64.
122     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
123
124   setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
125   setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
126
127   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
128   setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
129   setOperationAction(ISD::BRTWOWAY_CC      , MVT::Other, Expand);
130   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
131   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
132   setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
133   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
134   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Expand);
135   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
136   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
137   setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
138   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
139   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
140   setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
141   setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
142   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
143   setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
144   setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
145   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
146   setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
147   setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
148   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
149   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
150
151   // These should be promoted to a larger select which is supported.
152   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
153   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
154
155   // X86 wants to expand cmov itself.
156   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
157   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
158   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
159   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
160   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
161   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
162   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
163   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
164   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
165   // X86 ret instruction may pop stack.
166   setOperationAction(ISD::RET             , MVT::Other, Custom);
167   // Darwin ABI issue.
168   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
169   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
170   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
171   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
172   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
173   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
174   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
175   // X86 wants to expand memset / memcpy itself.
176   setOperationAction(ISD::MEMSET          , MVT::Other, Custom);
177   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
178
179   // We don't have line number support yet.
180   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
181   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
182   // FIXME - use subtarget debug flags
183   if (!TM.getSubtarget<X86Subtarget>().isTargetDarwin())
184     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
185
186   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
187   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
188   
189   // Use the default implementation.
190   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
191   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
192   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
193   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
194   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
195   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
196
197   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
198   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
199
200   if (X86ScalarSSE) {
201     // Set up the FP register classes.
202     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
203     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
204
205     // SSE has no load+extend ops
206     setOperationAction(ISD::EXTLOAD,  MVT::f32, Expand);
207     setOperationAction(ISD::ZEXTLOAD, MVT::f32, Expand);
208
209     // Use ANDPD to simulate FABS.
210     setOperationAction(ISD::FABS , MVT::f64, Custom);
211     setOperationAction(ISD::FABS , MVT::f32, Custom);
212
213     // Use XORP to simulate FNEG.
214     setOperationAction(ISD::FNEG , MVT::f64, Custom);
215     setOperationAction(ISD::FNEG , MVT::f32, Custom);
216
217     // We don't support sin/cos/fmod
218     setOperationAction(ISD::FSIN , MVT::f64, Expand);
219     setOperationAction(ISD::FCOS , MVT::f64, Expand);
220     setOperationAction(ISD::FREM , MVT::f64, Expand);
221     setOperationAction(ISD::FSIN , MVT::f32, Expand);
222     setOperationAction(ISD::FCOS , MVT::f32, Expand);
223     setOperationAction(ISD::FREM , MVT::f32, Expand);
224
225     // Expand FP immediates into loads from the stack, except for the special
226     // cases we handle.
227     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
228     setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
229     addLegalFPImmediate(+0.0); // xorps / xorpd
230   } else {
231     // Set up the FP register classes.
232     addRegisterClass(MVT::f64, X86::RFPRegisterClass);
233     
234     setOperationAction(ISD::UNDEF, MVT::f64, Expand);
235     
236     if (!UnsafeFPMath) {
237       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
238       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
239     }
240
241     setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
242     addLegalFPImmediate(+0.0); // FLD0
243     addLegalFPImmediate(+1.0); // FLD1
244     addLegalFPImmediate(-0.0); // FLD0/FCHS
245     addLegalFPImmediate(-1.0); // FLD1/FCHS
246   }
247
248   // First set operation action for all vector types to expand. Then we
249   // will selectively turn on ones that can be effectively codegen'd.
250   for (unsigned VT = (unsigned)MVT::Vector + 1;
251        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
252     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
253     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
254     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
255     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
256   }
257
258   if (TM.getSubtarget<X86Subtarget>().hasMMX()) {
259     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
260     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
261     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
262
263     // FIXME: add MMX packed arithmetics
264     setOperationAction(ISD::ConstantVec, MVT::v8i8,  Expand);
265     setOperationAction(ISD::ConstantVec, MVT::v4i16, Expand);
266     setOperationAction(ISD::ConstantVec, MVT::v2i32, Expand);
267   }
268
269   if (TM.getSubtarget<X86Subtarget>().hasSSE1()) {
270     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
271
272     setOperationAction(ISD::ADD        , MVT::v4f32, Legal);
273     setOperationAction(ISD::SUB        , MVT::v4f32, Legal);
274     setOperationAction(ISD::MUL        , MVT::v4f32, Legal);
275     setOperationAction(ISD::LOAD       , MVT::v4f32, Legal);
276     setOperationAction(ISD::ConstantVec, MVT::v4f32, Expand);
277   }
278
279   if (TM.getSubtarget<X86Subtarget>().hasSSE2()) {
280     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
281     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
282     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
283     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
284     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
285
286
287     setOperationAction(ISD::ADD        , MVT::v2f64, Legal);
288     setOperationAction(ISD::SUB        , MVT::v2f64, Legal);
289     setOperationAction(ISD::MUL        , MVT::v2f64, Legal);
290     setOperationAction(ISD::LOAD       , MVT::v2f64, Legal);
291     setOperationAction(ISD::ConstantVec, MVT::v2f64, Expand);
292     setOperationAction(ISD::ConstantVec, MVT::v16i8, Expand);
293     setOperationAction(ISD::ConstantVec, MVT::v8i16, Expand);
294     setOperationAction(ISD::ConstantVec, MVT::v4i32, Expand);
295     setOperationAction(ISD::ConstantVec, MVT::v2i64, Expand);
296   }
297
298   computeRegisterProperties();
299
300   // FIXME: These should be based on subtarget info. Plus, the values should
301   // be smaller when we are in optimizing for size mode.
302   maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
303   maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
304   maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
305   allowUnalignedMemoryAccesses = true; // x86 supports it!
306 }
307
308 std::vector<SDOperand>
309 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
310   if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
311     return LowerFastCCArguments(F, DAG);
312   return LowerCCCArguments(F, DAG);
313 }
314
315 std::pair<SDOperand, SDOperand>
316 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
317                                bool isVarArg, unsigned CallingConv,
318                                bool isTailCall,
319                                SDOperand Callee, ArgListTy &Args,
320                                SelectionDAG &DAG) {
321   assert((!isVarArg || CallingConv == CallingConv::C) &&
322          "Only C takes varargs!");
323
324   // If the callee is a GlobalAddress node (quite common, every direct call is)
325   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
326   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
327     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
328   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
329     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
330
331   if (CallingConv == CallingConv::Fast && EnableFastCC)
332     return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
333   return  LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
334 }
335
336 //===----------------------------------------------------------------------===//
337 //                    C Calling Convention implementation
338 //===----------------------------------------------------------------------===//
339
340 std::vector<SDOperand>
341 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
342   std::vector<SDOperand> ArgValues;
343
344   MachineFunction &MF = DAG.getMachineFunction();
345   MachineFrameInfo *MFI = MF.getFrameInfo();
346
347   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
348   // the stack frame looks like this:
349   //
350   // [ESP] -- return address
351   // [ESP + 4] -- first argument (leftmost lexically)
352   // [ESP + 8] -- second argument, if first argument is four bytes in size
353   //    ...
354   //
355   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
356   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
357     MVT::ValueType ObjectVT = getValueType(I->getType());
358     unsigned ArgIncrement = 4;
359     unsigned ObjSize;
360     switch (ObjectVT) {
361     default: assert(0 && "Unhandled argument type!");
362     case MVT::i1:
363     case MVT::i8:  ObjSize = 1;                break;
364     case MVT::i16: ObjSize = 2;                break;
365     case MVT::i32: ObjSize = 4;                break;
366     case MVT::i64: ObjSize = ArgIncrement = 8; break;
367     case MVT::f32: ObjSize = 4;                break;
368     case MVT::f64: ObjSize = ArgIncrement = 8; break;
369     }
370     // Create the frame index object for this incoming parameter...
371     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
372
373     // Create the SelectionDAG nodes corresponding to a load from this parameter
374     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
375
376     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
377     // dead loads.
378     SDOperand ArgValue;
379     if (!I->use_empty())
380       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
381                              DAG.getSrcValue(NULL));
382     else {
383       if (MVT::isInteger(ObjectVT))
384         ArgValue = DAG.getConstant(0, ObjectVT);
385       else
386         ArgValue = DAG.getConstantFP(0, ObjectVT);
387     }
388     ArgValues.push_back(ArgValue);
389
390     ArgOffset += ArgIncrement;   // Move on to the next argument...
391   }
392
393   // If the function takes variable number of arguments, make a frame index for
394   // the start of the first vararg value... for expansion of llvm.va_start.
395   if (F.isVarArg())
396     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
397   ReturnAddrIndex = 0;     // No return address slot generated yet.
398   BytesToPopOnReturn = 0;  // Callee pops nothing.
399   BytesCallerReserves = ArgOffset;
400
401   // Finally, inform the code generator which regs we return values in.
402   switch (getValueType(F.getReturnType())) {
403   default: assert(0 && "Unknown type!");
404   case MVT::isVoid: break;
405   case MVT::i1:
406   case MVT::i8:
407   case MVT::i16:
408   case MVT::i32:
409     MF.addLiveOut(X86::EAX);
410     break;
411   case MVT::i64:
412     MF.addLiveOut(X86::EAX);
413     MF.addLiveOut(X86::EDX);
414     break;
415   case MVT::f32:
416   case MVT::f64:
417     MF.addLiveOut(X86::ST0);
418     break;
419   }
420   return ArgValues;
421 }
422
423 std::pair<SDOperand, SDOperand>
424 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
425                                   bool isVarArg, bool isTailCall,
426                                   SDOperand Callee, ArgListTy &Args,
427                                   SelectionDAG &DAG) {
428   // Count how many bytes are to be pushed on the stack.
429   unsigned NumBytes = 0;
430
431   if (Args.empty()) {
432     // Save zero bytes.
433     Chain = DAG.getCALLSEQ_START(Chain, DAG.getConstant(0, getPointerTy()));
434   } else {
435     for (unsigned i = 0, e = Args.size(); i != e; ++i)
436       switch (getValueType(Args[i].second)) {
437       default: assert(0 && "Unknown value type!");
438       case MVT::i1:
439       case MVT::i8:
440       case MVT::i16:
441       case MVT::i32:
442       case MVT::f32:
443         NumBytes += 4;
444         break;
445       case MVT::i64:
446       case MVT::f64:
447         NumBytes += 8;
448         break;
449       }
450
451     Chain = DAG.getCALLSEQ_START(Chain,
452                                  DAG.getConstant(NumBytes, getPointerTy()));
453
454     // Arguments go on the stack in reverse order, as specified by the ABI.
455     unsigned ArgOffset = 0;
456     SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
457     std::vector<SDOperand> Stores;
458
459     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
460       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
461       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
462
463       switch (getValueType(Args[i].second)) {
464       default: assert(0 && "Unexpected ValueType for argument!");
465       case MVT::i1:
466       case MVT::i8:
467       case MVT::i16:
468         // Promote the integer to 32 bits.  If the input type is signed use a
469         // sign extend, otherwise use a zero extend.
470         if (Args[i].second->isSigned())
471           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
472         else
473           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
474
475         // FALL THROUGH
476       case MVT::i32:
477       case MVT::f32:
478         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
479                                      Args[i].first, PtrOff,
480                                      DAG.getSrcValue(NULL)));
481         ArgOffset += 4;
482         break;
483       case MVT::i64:
484       case MVT::f64:
485         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
486                                      Args[i].first, PtrOff,
487                                      DAG.getSrcValue(NULL)));
488         ArgOffset += 8;
489         break;
490       }
491     }
492     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
493   }
494
495   std::vector<MVT::ValueType> RetVals;
496   MVT::ValueType RetTyVT = getValueType(RetTy);
497   RetVals.push_back(MVT::Other);
498
499   // The result values produced have to be legal.  Promote the result.
500   switch (RetTyVT) {
501   case MVT::isVoid: break;
502   default:
503     RetVals.push_back(RetTyVT);
504     break;
505   case MVT::i1:
506   case MVT::i8:
507   case MVT::i16:
508     RetVals.push_back(MVT::i32);
509     break;
510   case MVT::f32:
511     if (X86ScalarSSE)
512       RetVals.push_back(MVT::f32);
513     else
514       RetVals.push_back(MVT::f64);
515     break;
516   case MVT::i64:
517     RetVals.push_back(MVT::i32);
518     RetVals.push_back(MVT::i32);
519     break;
520   }
521
522   std::vector<MVT::ValueType> NodeTys;
523   NodeTys.push_back(MVT::Other);   // Returns a chain
524   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
525   std::vector<SDOperand> Ops;
526   Ops.push_back(Chain);
527   Ops.push_back(Callee);
528
529   // FIXME: Do not generate X86ISD::TAILCALL for now.
530   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
531   SDOperand InFlag = Chain.getValue(1);
532
533   NodeTys.clear();
534   NodeTys.push_back(MVT::Other);   // Returns a chain
535   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
536   Ops.clear();
537   Ops.push_back(Chain);
538   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
539   Ops.push_back(DAG.getConstant(0, getPointerTy()));
540   Ops.push_back(InFlag);
541   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
542   InFlag = Chain.getValue(1);
543   
544   SDOperand RetVal;
545   if (RetTyVT != MVT::isVoid) {
546     switch (RetTyVT) {
547     default: assert(0 && "Unknown value type to return!");
548     case MVT::i1:
549     case MVT::i8:
550       RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
551       Chain = RetVal.getValue(1);
552       if (RetTyVT == MVT::i1) 
553         RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
554       break;
555     case MVT::i16:
556       RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
557       Chain = RetVal.getValue(1);
558       break;
559     case MVT::i32:
560       RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
561       Chain = RetVal.getValue(1);
562       break;
563     case MVT::i64: {
564       SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
565       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
566                                         Lo.getValue(2));
567       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
568       Chain = Hi.getValue(1);
569       break;
570     }
571     case MVT::f32:
572     case MVT::f64: {
573       std::vector<MVT::ValueType> Tys;
574       Tys.push_back(MVT::f64);
575       Tys.push_back(MVT::Other);
576       Tys.push_back(MVT::Flag);
577       std::vector<SDOperand> Ops;
578       Ops.push_back(Chain);
579       Ops.push_back(InFlag);
580       RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
581       Chain  = RetVal.getValue(1);
582       InFlag = RetVal.getValue(2);
583       if (X86ScalarSSE) {
584         // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
585         // shouldn't be necessary except that RFP cannot be live across
586         // multiple blocks. When stackifier is fixed, they can be uncoupled.
587         MachineFunction &MF = DAG.getMachineFunction();
588         int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
589         SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
590         Tys.clear();
591         Tys.push_back(MVT::Other);
592         Ops.clear();
593         Ops.push_back(Chain);
594         Ops.push_back(RetVal);
595         Ops.push_back(StackSlot);
596         Ops.push_back(DAG.getValueType(RetTyVT));
597         Ops.push_back(InFlag);
598         Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
599         RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
600                              DAG.getSrcValue(NULL));
601         Chain = RetVal.getValue(1);
602       }
603
604       if (RetTyVT == MVT::f32 && !X86ScalarSSE)
605         // FIXME: we would really like to remember that this FP_ROUND
606         // operation is okay to eliminate if we allow excess FP precision.
607         RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
608       break;
609     }
610     }
611   }
612
613   return std::make_pair(RetVal, Chain);
614 }
615
616 //===----------------------------------------------------------------------===//
617 //                    Fast Calling Convention implementation
618 //===----------------------------------------------------------------------===//
619 //
620 // The X86 'fast' calling convention passes up to two integer arguments in
621 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
622 // and requires that the callee pop its arguments off the stack (allowing proper
623 // tail calls), and has the same return value conventions as C calling convs.
624 //
625 // This calling convention always arranges for the callee pop value to be 8n+4
626 // bytes, which is needed for tail recursion elimination and stack alignment
627 // reasons.
628 //
629 // Note that this can be enhanced in the future to pass fp vals in registers
630 // (when we have a global fp allocator) and do other tricks.
631 //
632
633 /// AddLiveIn - This helper function adds the specified physical register to the
634 /// MachineFunction as a live in value.  It also creates a corresponding virtual
635 /// register for it.
636 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
637                           TargetRegisterClass *RC) {
638   assert(RC->contains(PReg) && "Not the correct regclass!");
639   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
640   MF.addLiveIn(PReg, VReg);
641   return VReg;
642 }
643
644
645 std::vector<SDOperand>
646 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
647   std::vector<SDOperand> ArgValues;
648
649   MachineFunction &MF = DAG.getMachineFunction();
650   MachineFrameInfo *MFI = MF.getFrameInfo();
651
652   // Add DAG nodes to load the arguments...  On entry to a function the stack
653   // frame looks like this:
654   //
655   // [ESP] -- return address
656   // [ESP + 4] -- first nonreg argument (leftmost lexically)
657   // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
658   //    ...
659   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
660
661   // Keep track of the number of integer regs passed so far.  This can be either
662   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
663   // used).
664   unsigned NumIntRegs = 0;
665
666   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
667     MVT::ValueType ObjectVT = getValueType(I->getType());
668     unsigned ArgIncrement = 4;
669     unsigned ObjSize = 0;
670     SDOperand ArgValue;
671
672     switch (ObjectVT) {
673     default: assert(0 && "Unhandled argument type!");
674     case MVT::i1:
675     case MVT::i8:
676       if (NumIntRegs < 2) {
677         if (!I->use_empty()) {
678           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
679                                     X86::R8RegisterClass);
680           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i8);
681           DAG.setRoot(ArgValue.getValue(1));
682           if (ObjectVT == MVT::i1)
683             // FIXME: Should insert a assertzext here.
684             ArgValue = DAG.getNode(ISD::TRUNCATE, MVT::i1, ArgValue);
685         }
686         ++NumIntRegs;
687         break;
688       }
689
690       ObjSize = 1;
691       break;
692     case MVT::i16:
693       if (NumIntRegs < 2) {
694         if (!I->use_empty()) {
695           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
696                                     X86::R16RegisterClass);
697           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i16);
698           DAG.setRoot(ArgValue.getValue(1));
699         }
700         ++NumIntRegs;
701         break;
702       }
703       ObjSize = 2;
704       break;
705     case MVT::i32:
706       if (NumIntRegs < 2) {
707         if (!I->use_empty()) {
708           unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
709                                     X86::R32RegisterClass);
710           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
711           DAG.setRoot(ArgValue.getValue(1));
712         }
713         ++NumIntRegs;
714         break;
715       }
716       ObjSize = 4;
717       break;
718     case MVT::i64:
719       if (NumIntRegs == 0) {
720         if (!I->use_empty()) {
721           unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
722           unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
723
724           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
725           SDOperand Hi  = DAG.getCopyFromReg(Low.getValue(1), TopReg, MVT::i32);
726           DAG.setRoot(Hi.getValue(1));
727
728           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
729         }
730         NumIntRegs = 2;
731         break;
732       } else if (NumIntRegs == 1) {
733         if (!I->use_empty()) {
734           unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
735           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
736           DAG.setRoot(Low.getValue(1));
737
738           // Load the high part from memory.
739           // Create the frame index object for this incoming parameter...
740           int FI = MFI->CreateFixedObject(4, ArgOffset);
741           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
742           SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
743                                      DAG.getSrcValue(NULL));
744           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
745         }
746         ArgOffset += 4;
747         NumIntRegs = 2;
748         break;
749       }
750       ObjSize = ArgIncrement = 8;
751       break;
752     case MVT::f32: ObjSize = 4;                break;
753     case MVT::f64: ObjSize = ArgIncrement = 8; break;
754     }
755
756     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
757     // dead loads.
758     if (ObjSize && !I->use_empty()) {
759       // Create the frame index object for this incoming parameter...
760       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
761
762       // Create the SelectionDAG nodes corresponding to a load from this
763       // parameter.
764       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
765
766       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
767                              DAG.getSrcValue(NULL));
768     } else if (ArgValue.Val == 0) {
769       if (MVT::isInteger(ObjectVT))
770         ArgValue = DAG.getConstant(0, ObjectVT);
771       else
772         ArgValue = DAG.getConstantFP(0, ObjectVT);
773     }
774     ArgValues.push_back(ArgValue);
775
776     if (ObjSize)
777       ArgOffset += ArgIncrement;   // Move on to the next argument.
778   }
779
780   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
781   // arguments and the arguments after the retaddr has been pushed are aligned.
782   if ((ArgOffset & 7) == 0)
783     ArgOffset += 4;
784
785   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
786   ReturnAddrIndex = 0;             // No return address slot generated yet.
787   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
788   BytesCallerReserves = 0;
789
790   // Finally, inform the code generator which regs we return values in.
791   switch (getValueType(F.getReturnType())) {
792   default: assert(0 && "Unknown type!");
793   case MVT::isVoid: break;
794   case MVT::i1:
795   case MVT::i8:
796   case MVT::i16:
797   case MVT::i32:
798     MF.addLiveOut(X86::EAX);
799     break;
800   case MVT::i64:
801     MF.addLiveOut(X86::EAX);
802     MF.addLiveOut(X86::EDX);
803     break;
804   case MVT::f32:
805   case MVT::f64:
806     MF.addLiveOut(X86::ST0);
807     break;
808   }
809   return ArgValues;
810 }
811
812 std::pair<SDOperand, SDOperand>
813 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
814                                      bool isTailCall, SDOperand Callee,
815                                      ArgListTy &Args, SelectionDAG &DAG) {
816   // Count how many bytes are to be pushed on the stack.
817   unsigned NumBytes = 0;
818
819   // Keep track of the number of integer regs passed so far.  This can be either
820   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
821   // used).
822   unsigned NumIntRegs = 0;
823
824   for (unsigned i = 0, e = Args.size(); i != e; ++i)
825     switch (getValueType(Args[i].second)) {
826     default: assert(0 && "Unknown value type!");
827     case MVT::i1:
828     case MVT::i8:
829     case MVT::i16:
830     case MVT::i32:
831       if (NumIntRegs < 2) {
832         ++NumIntRegs;
833         break;
834       }
835       // fall through
836     case MVT::f32:
837       NumBytes += 4;
838       break;
839     case MVT::i64:
840       if (NumIntRegs == 0) {
841         NumIntRegs = 2;
842         break;
843       } else if (NumIntRegs == 1) {
844         NumIntRegs = 2;
845         NumBytes += 4;
846         break;
847       }
848
849       // fall through
850     case MVT::f64:
851       NumBytes += 8;
852       break;
853     }
854
855   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
856   // arguments and the arguments after the retaddr has been pushed are aligned.
857   if ((NumBytes & 7) == 0)
858     NumBytes += 4;
859
860   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(NumBytes, getPointerTy()));
861
862   // Arguments go on the stack in reverse order, as specified by the ABI.
863   unsigned ArgOffset = 0;
864   SDOperand StackPtr = DAG.getRegister(X86::ESP, MVT::i32);
865   NumIntRegs = 0;
866   std::vector<SDOperand> Stores;
867   std::vector<SDOperand> RegValuesToPass;
868   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
869     switch (getValueType(Args[i].second)) {
870     default: assert(0 && "Unexpected ValueType for argument!");
871     case MVT::i1:
872       Args[i].first = DAG.getNode(ISD::ANY_EXTEND, MVT::i8, Args[i].first);
873       // Fall through.
874     case MVT::i8:
875     case MVT::i16:
876     case MVT::i32:
877       if (NumIntRegs < 2) {
878         RegValuesToPass.push_back(Args[i].first);
879         ++NumIntRegs;
880         break;
881       }
882       // Fall through
883     case MVT::f32: {
884       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
885       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
886       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
887                                    Args[i].first, PtrOff,
888                                    DAG.getSrcValue(NULL)));
889       ArgOffset += 4;
890       break;
891     }
892     case MVT::i64:
893       if (NumIntRegs < 2) {    // Can pass part of it in regs?
894         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
895                                    Args[i].first, DAG.getConstant(1, MVT::i32));
896         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
897                                    Args[i].first, DAG.getConstant(0, MVT::i32));
898         RegValuesToPass.push_back(Lo);
899         ++NumIntRegs;
900         if (NumIntRegs < 2) {   // Pass both parts in regs?
901           RegValuesToPass.push_back(Hi);
902           ++NumIntRegs;
903         } else {
904           // Pass the high part in memory.
905           SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
906           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
907           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
908                                        Hi, PtrOff, DAG.getSrcValue(NULL)));
909           ArgOffset += 4;
910         }
911         break;
912       }
913       // Fall through
914     case MVT::f64:
915       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
916       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
917       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
918                                    Args[i].first, PtrOff,
919                                    DAG.getSrcValue(NULL)));
920       ArgOffset += 8;
921       break;
922     }
923   }
924   if (!Stores.empty())
925     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
926
927   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
928   // arguments and the arguments after the retaddr has been pushed are aligned.
929   if ((ArgOffset & 7) == 0)
930     ArgOffset += 4;
931
932   std::vector<MVT::ValueType> RetVals;
933   MVT::ValueType RetTyVT = getValueType(RetTy);
934
935   RetVals.push_back(MVT::Other);
936
937   // The result values produced have to be legal.  Promote the result.
938   switch (RetTyVT) {
939   case MVT::isVoid: break;
940   default:
941     RetVals.push_back(RetTyVT);
942     break;
943   case MVT::i1:
944   case MVT::i8:
945   case MVT::i16:
946     RetVals.push_back(MVT::i32);
947     break;
948   case MVT::f32:
949     if (X86ScalarSSE)
950       RetVals.push_back(MVT::f32);
951     else
952       RetVals.push_back(MVT::f64);
953     break;
954   case MVT::i64:
955     RetVals.push_back(MVT::i32);
956     RetVals.push_back(MVT::i32);
957     break;
958   }
959
960   // Build a sequence of copy-to-reg nodes chained together with token chain
961   // and flag operands which copy the outgoing args into registers.
962   SDOperand InFlag;
963   for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
964     unsigned CCReg;
965     SDOperand RegToPass = RegValuesToPass[i];
966     switch (RegToPass.getValueType()) {
967     default: assert(0 && "Bad thing to pass in regs");
968     case MVT::i8:
969       CCReg = (i == 0) ? X86::AL  : X86::DL;
970       break;
971     case MVT::i16:
972       CCReg = (i == 0) ? X86::AX  : X86::DX;
973       break;
974     case MVT::i32:
975       CCReg = (i == 0) ? X86::EAX : X86::EDX;
976       break;
977     }
978
979     Chain = DAG.getCopyToReg(Chain, CCReg, RegToPass, InFlag);
980     InFlag = Chain.getValue(1);
981   }
982
983   std::vector<MVT::ValueType> NodeTys;
984   NodeTys.push_back(MVT::Other);   // Returns a chain
985   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
986   std::vector<SDOperand> Ops;
987   Ops.push_back(Chain);
988   Ops.push_back(Callee);
989   if (InFlag.Val)
990     Ops.push_back(InFlag);
991
992   // FIXME: Do not generate X86ISD::TAILCALL for now.
993   Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops);
994   InFlag = Chain.getValue(1);
995
996   NodeTys.clear();
997   NodeTys.push_back(MVT::Other);   // Returns a chain
998   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
999   Ops.clear();
1000   Ops.push_back(Chain);
1001   Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1002   Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
1003   Ops.push_back(InFlag);
1004   Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, Ops);
1005   InFlag = Chain.getValue(1);
1006   
1007   SDOperand RetVal;
1008   if (RetTyVT != MVT::isVoid) {
1009     switch (RetTyVT) {
1010     default: assert(0 && "Unknown value type to return!");
1011     case MVT::i1:
1012     case MVT::i8:
1013       RetVal = DAG.getCopyFromReg(Chain, X86::AL, MVT::i8, InFlag);
1014       Chain = RetVal.getValue(1);
1015       if (RetTyVT == MVT::i1) 
1016         RetVal = DAG.getNode(ISD::TRUNCATE, MVT::i1, RetVal);
1017       break;
1018     case MVT::i16:
1019       RetVal = DAG.getCopyFromReg(Chain, X86::AX, MVT::i16, InFlag);
1020       Chain = RetVal.getValue(1);
1021       break;
1022     case MVT::i32:
1023       RetVal = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1024       Chain = RetVal.getValue(1);
1025       break;
1026     case MVT::i64: {
1027       SDOperand Lo = DAG.getCopyFromReg(Chain, X86::EAX, MVT::i32, InFlag);
1028       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), X86::EDX, MVT::i32, 
1029                                         Lo.getValue(2));
1030       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
1031       Chain = Hi.getValue(1);
1032       break;
1033     }
1034     case MVT::f32:
1035     case MVT::f64: {
1036       std::vector<MVT::ValueType> Tys;
1037       Tys.push_back(MVT::f64);
1038       Tys.push_back(MVT::Other);
1039       Tys.push_back(MVT::Flag);
1040       std::vector<SDOperand> Ops;
1041       Ops.push_back(Chain);
1042       Ops.push_back(InFlag);
1043       RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, Ops);
1044       Chain  = RetVal.getValue(1);
1045       InFlag = RetVal.getValue(2);
1046       if (X86ScalarSSE) {
1047         // FIXME: Currently the FST is flagged to the FP_GET_RESULT. This
1048         // shouldn't be necessary except that RFP cannot be live across
1049         // multiple blocks. When stackifier is fixed, they can be uncoupled.
1050         MachineFunction &MF = DAG.getMachineFunction();
1051         int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1052         SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1053         Tys.clear();
1054         Tys.push_back(MVT::Other);
1055         Ops.clear();
1056         Ops.push_back(Chain);
1057         Ops.push_back(RetVal);
1058         Ops.push_back(StackSlot);
1059         Ops.push_back(DAG.getValueType(RetTyVT));
1060         Ops.push_back(InFlag);
1061         Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1062         RetVal = DAG.getLoad(RetTyVT, Chain, StackSlot,
1063                              DAG.getSrcValue(NULL));
1064         Chain = RetVal.getValue(1);
1065       }
1066
1067       if (RetTyVT == MVT::f32 && !X86ScalarSSE)
1068         // FIXME: we would really like to remember that this FP_ROUND
1069         // operation is okay to eliminate if we allow excess FP precision.
1070         RetVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, RetVal);
1071       break;
1072     }
1073     }
1074   }
1075
1076   return std::make_pair(RetVal, Chain);
1077 }
1078
1079 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1080   if (ReturnAddrIndex == 0) {
1081     // Set up a frame object for the return address.
1082     MachineFunction &MF = DAG.getMachineFunction();
1083     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1084   }
1085
1086   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
1087 }
1088
1089
1090
1091 std::pair<SDOperand, SDOperand> X86TargetLowering::
1092 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
1093                         SelectionDAG &DAG) {
1094   SDOperand Result;
1095   if (Depth)        // Depths > 0 not supported yet!
1096     Result = DAG.getConstant(0, getPointerTy());
1097   else {
1098     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
1099     if (!isFrameAddress)
1100       // Just load the return address
1101       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
1102                            DAG.getSrcValue(NULL));
1103     else
1104       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
1105                            DAG.getConstant(4, MVT::i32));
1106   }
1107   return std::make_pair(Result, Chain);
1108 }
1109
1110 /// getCondBrOpcodeForX86CC - Returns the X86 conditional branch opcode
1111 /// which corresponds to the condition code.
1112 static unsigned getCondBrOpcodeForX86CC(unsigned X86CC) {
1113   switch (X86CC) {
1114   default: assert(0 && "Unknown X86 conditional code!");
1115   case X86ISD::COND_A:  return X86::JA;
1116   case X86ISD::COND_AE: return X86::JAE;
1117   case X86ISD::COND_B:  return X86::JB;
1118   case X86ISD::COND_BE: return X86::JBE;
1119   case X86ISD::COND_E:  return X86::JE;
1120   case X86ISD::COND_G:  return X86::JG;
1121   case X86ISD::COND_GE: return X86::JGE;
1122   case X86ISD::COND_L:  return X86::JL;
1123   case X86ISD::COND_LE: return X86::JLE;
1124   case X86ISD::COND_NE: return X86::JNE;
1125   case X86ISD::COND_NO: return X86::JNO;
1126   case X86ISD::COND_NP: return X86::JNP;
1127   case X86ISD::COND_NS: return X86::JNS;
1128   case X86ISD::COND_O:  return X86::JO;
1129   case X86ISD::COND_P:  return X86::JP;
1130   case X86ISD::COND_S:  return X86::JS;
1131   }
1132 }
1133
1134 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1135 /// specific condition code. It returns a false if it cannot do a direct
1136 /// translation. X86CC is the translated CondCode. Flip is set to true if the
1137 /// the order of comparison operands should be flipped.
1138 static bool translateX86CC(SDOperand CC, bool isFP, unsigned &X86CC,
1139                            bool &Flip) {
1140   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1141   Flip = false;
1142   X86CC = X86ISD::COND_INVALID;
1143   if (!isFP) {
1144     switch (SetCCOpcode) {
1145     default: break;
1146     case ISD::SETEQ:  X86CC = X86ISD::COND_E;  break;
1147     case ISD::SETGT:  X86CC = X86ISD::COND_G;  break;
1148     case ISD::SETGE:  X86CC = X86ISD::COND_GE; break;
1149     case ISD::SETLT:  X86CC = X86ISD::COND_L;  break;
1150     case ISD::SETLE:  X86CC = X86ISD::COND_LE; break;
1151     case ISD::SETNE:  X86CC = X86ISD::COND_NE; break;
1152     case ISD::SETULT: X86CC = X86ISD::COND_B;  break;
1153     case ISD::SETUGT: X86CC = X86ISD::COND_A;  break;
1154     case ISD::SETULE: X86CC = X86ISD::COND_BE; break;
1155     case ISD::SETUGE: X86CC = X86ISD::COND_AE; break;
1156     }
1157   } else {
1158     // On a floating point condition, the flags are set as follows:
1159     // ZF  PF  CF   op
1160     //  0 | 0 | 0 | X > Y
1161     //  0 | 0 | 1 | X < Y
1162     //  1 | 0 | 0 | X == Y
1163     //  1 | 1 | 1 | unordered
1164     switch (SetCCOpcode) {
1165     default: break;
1166     case ISD::SETUEQ:
1167     case ISD::SETEQ: X86CC = X86ISD::COND_E;  break;
1168     case ISD::SETOLE: Flip = true; // Fallthrough
1169     case ISD::SETOGT:
1170     case ISD::SETGT: X86CC = X86ISD::COND_A;  break;
1171     case ISD::SETOLT: Flip = true; // Fallthrough
1172     case ISD::SETOGE:
1173     case ISD::SETGE: X86CC = X86ISD::COND_AE; break;
1174     case ISD::SETUGE: Flip = true; // Fallthrough
1175     case ISD::SETULT:
1176     case ISD::SETLT: X86CC = X86ISD::COND_B;  break;
1177     case ISD::SETUGT: Flip = true; // Fallthrough
1178     case ISD::SETULE:
1179     case ISD::SETLE: X86CC = X86ISD::COND_BE; break;
1180     case ISD::SETONE:
1181     case ISD::SETNE: X86CC = X86ISD::COND_NE; break;
1182     case ISD::SETUO: X86CC = X86ISD::COND_P;  break;
1183     case ISD::SETO:  X86CC = X86ISD::COND_NP; break;
1184     }
1185   }
1186
1187   return X86CC != X86ISD::COND_INVALID;
1188 }
1189
1190 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1191 /// code. Current x86 isa includes the following FP cmov instructions:
1192 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1193 static bool hasFPCMov(unsigned X86CC) {
1194   switch (X86CC) {
1195   default:
1196     return false;
1197   case X86ISD::COND_B:
1198   case X86ISD::COND_BE:
1199   case X86ISD::COND_E:
1200   case X86ISD::COND_P:
1201   case X86ISD::COND_A:
1202   case X86ISD::COND_AE:
1203   case X86ISD::COND_NE:
1204   case X86ISD::COND_NP:
1205     return true;
1206   }
1207 }
1208
1209 MachineBasicBlock *
1210 X86TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1211                                            MachineBasicBlock *BB) {
1212   switch (MI->getOpcode()) {
1213   default: assert(false && "Unexpected instr type to insert");
1214   case X86::CMOV_FR32:
1215   case X86::CMOV_FR64: {
1216     // To "insert" a SELECT_CC instruction, we actually have to insert the
1217     // diamond control-flow pattern.  The incoming instruction knows the
1218     // destination vreg to set, the condition code register to branch on, the
1219     // true/false values to select between, and a branch opcode to use.
1220     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1221     ilist<MachineBasicBlock>::iterator It = BB;
1222     ++It;
1223   
1224     //  thisMBB:
1225     //  ...
1226     //   TrueVal = ...
1227     //   cmpTY ccX, r1, r2
1228     //   bCC copy1MBB
1229     //   fallthrough --> copy0MBB
1230     MachineBasicBlock *thisMBB = BB;
1231     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1232     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1233     unsigned Opc = getCondBrOpcodeForX86CC(MI->getOperand(3).getImmedValue());
1234     BuildMI(BB, Opc, 1).addMBB(sinkMBB);
1235     MachineFunction *F = BB->getParent();
1236     F->getBasicBlockList().insert(It, copy0MBB);
1237     F->getBasicBlockList().insert(It, sinkMBB);
1238     // Update machine-CFG edges
1239     BB->addSuccessor(copy0MBB);
1240     BB->addSuccessor(sinkMBB);
1241   
1242     //  copy0MBB:
1243     //   %FalseValue = ...
1244     //   # fallthrough to sinkMBB
1245     BB = copy0MBB;
1246   
1247     // Update machine-CFG edges
1248     BB->addSuccessor(sinkMBB);
1249   
1250     //  sinkMBB:
1251     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1252     //  ...
1253     BB = sinkMBB;
1254     BuildMI(BB, X86::PHI, 4, MI->getOperand(0).getReg())
1255       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1256       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1257
1258     delete MI;   // The pseudo instruction is gone now.
1259     return BB;
1260   }
1261
1262   case X86::FP_TO_INT16_IN_MEM:
1263   case X86::FP_TO_INT32_IN_MEM:
1264   case X86::FP_TO_INT64_IN_MEM: {
1265     // Change the floating point control register to use "round towards zero"
1266     // mode when truncating to an integer value.
1267     MachineFunction *F = BB->getParent();
1268     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
1269     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1270
1271     // Load the old value of the high byte of the control word...
1272     unsigned OldCW =
1273       F->getSSARegMap()->createVirtualRegister(X86::R16RegisterClass);
1274     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
1275
1276     // Set the high part to be round to zero...
1277     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
1278
1279     // Reload the modified control word now...
1280     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1281
1282     // Restore the memory image of control word to original value
1283     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
1284
1285     // Get the X86 opcode to use.
1286     unsigned Opc;
1287     switch (MI->getOpcode()) {
1288     default: assert(0 && "illegal opcode!");
1289     case X86::FP_TO_INT16_IN_MEM: Opc = X86::FpIST16m; break;
1290     case X86::FP_TO_INT32_IN_MEM: Opc = X86::FpIST32m; break;
1291     case X86::FP_TO_INT64_IN_MEM: Opc = X86::FpIST64m; break;
1292     }
1293
1294     X86AddressMode AM;
1295     MachineOperand &Op = MI->getOperand(0);
1296     if (Op.isRegister()) {
1297       AM.BaseType = X86AddressMode::RegBase;
1298       AM.Base.Reg = Op.getReg();
1299     } else {
1300       AM.BaseType = X86AddressMode::FrameIndexBase;
1301       AM.Base.FrameIndex = Op.getFrameIndex();
1302     }
1303     Op = MI->getOperand(1);
1304     if (Op.isImmediate())
1305       AM.Scale = Op.getImmedValue();
1306     Op = MI->getOperand(2);
1307     if (Op.isImmediate())
1308       AM.IndexReg = Op.getImmedValue();
1309     Op = MI->getOperand(3);
1310     if (Op.isGlobalAddress()) {
1311       AM.GV = Op.getGlobal();
1312     } else {
1313       AM.Disp = Op.getImmedValue();
1314     }
1315     addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(MI->getOperand(4).getReg());
1316
1317     // Reload the original control word now.
1318     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1319
1320     delete MI;   // The pseudo instruction is gone now.
1321     return BB;
1322   }
1323   }
1324 }
1325
1326
1327 //===----------------------------------------------------------------------===//
1328 //                           X86 Custom Lowering Hooks
1329 //===----------------------------------------------------------------------===//
1330
1331 /// DarwinGVRequiresExtraLoad - true if accessing the GV requires an extra
1332 /// load. For Darwin, external and weak symbols are indirect, loading the value
1333 /// at address GV rather then the value of GV itself. This means that the
1334 /// GlobalAddress must be in the base or index register of the address, not the
1335 /// GV offset field.
1336 static bool DarwinGVRequiresExtraLoad(GlobalValue *GV) {
1337   return (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
1338           (GV->isExternal() && !GV->hasNotBeenReadFromBytecode()));
1339 }
1340
1341 /// LowerOperation - Provide custom lowering hooks for some operations.
1342 ///
1343 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1344   switch (Op.getOpcode()) {
1345   default: assert(0 && "Should not custom lower this!");
1346   case ISD::SHL_PARTS:
1347   case ISD::SRA_PARTS:
1348   case ISD::SRL_PARTS: {
1349     assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
1350            "Not an i64 shift!");
1351     bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
1352     SDOperand ShOpLo = Op.getOperand(0);
1353     SDOperand ShOpHi = Op.getOperand(1);
1354     SDOperand ShAmt  = Op.getOperand(2);
1355     SDOperand Tmp1 = isSRA ? DAG.getNode(ISD::SRA, MVT::i32, ShOpHi,
1356                                          DAG.getConstant(31, MVT::i8))
1357                            : DAG.getConstant(0, MVT::i32);
1358
1359     SDOperand Tmp2, Tmp3;
1360     if (Op.getOpcode() == ISD::SHL_PARTS) {
1361       Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
1362       Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
1363     } else {
1364       Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
1365       Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
1366     }
1367
1368     SDOperand InFlag = DAG.getNode(X86ISD::TEST, MVT::Flag,
1369                                    ShAmt, DAG.getConstant(32, MVT::i8));
1370
1371     SDOperand Hi, Lo;
1372     SDOperand CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1373
1374     std::vector<MVT::ValueType> Tys;
1375     Tys.push_back(MVT::i32);
1376     Tys.push_back(MVT::Flag);
1377     std::vector<SDOperand> Ops;
1378     if (Op.getOpcode() == ISD::SHL_PARTS) {
1379       Ops.push_back(Tmp2);
1380       Ops.push_back(Tmp3);
1381       Ops.push_back(CC);
1382       Ops.push_back(InFlag);
1383       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1384       InFlag = Hi.getValue(1);
1385
1386       Ops.clear();
1387       Ops.push_back(Tmp3);
1388       Ops.push_back(Tmp1);
1389       Ops.push_back(CC);
1390       Ops.push_back(InFlag);
1391       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1392     } else {
1393       Ops.push_back(Tmp2);
1394       Ops.push_back(Tmp3);
1395       Ops.push_back(CC);
1396       Ops.push_back(InFlag);
1397       Lo = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1398       InFlag = Lo.getValue(1);
1399
1400       Ops.clear();
1401       Ops.push_back(Tmp3);
1402       Ops.push_back(Tmp1);
1403       Ops.push_back(CC);
1404       Ops.push_back(InFlag);
1405       Hi = DAG.getNode(X86ISD::CMOV, Tys, Ops);
1406     }
1407
1408     Tys.clear();
1409     Tys.push_back(MVT::i32);
1410     Tys.push_back(MVT::i32);
1411     Ops.clear();
1412     Ops.push_back(Lo);
1413     Ops.push_back(Hi);
1414     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1415   }
1416   case ISD::SINT_TO_FP: {
1417     assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
1418            Op.getOperand(0).getValueType() >= MVT::i16 &&
1419            "Unknown SINT_TO_FP to lower!");
1420
1421     SDOperand Result;
1422     MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
1423     unsigned Size = MVT::getSizeInBits(SrcVT)/8;
1424     MachineFunction &MF = DAG.getMachineFunction();
1425     int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
1426     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1427     SDOperand Chain = DAG.getNode(ISD::STORE, MVT::Other,
1428                                   DAG.getEntryNode(), Op.getOperand(0),
1429                                   StackSlot, DAG.getSrcValue(NULL));
1430
1431     // Build the FILD
1432     std::vector<MVT::ValueType> Tys;
1433     Tys.push_back(MVT::f64);
1434     Tys.push_back(MVT::Other);
1435     if (X86ScalarSSE) Tys.push_back(MVT::Flag);
1436     std::vector<SDOperand> Ops;
1437     Ops.push_back(Chain);
1438     Ops.push_back(StackSlot);
1439     Ops.push_back(DAG.getValueType(SrcVT));
1440     Result = DAG.getNode(X86ScalarSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
1441                          Tys, Ops);
1442
1443     if (X86ScalarSSE) {
1444       Chain = Result.getValue(1);
1445       SDOperand InFlag = Result.getValue(2);
1446
1447       // FIXME: Currently the FST is flagged to the FILD_FLAG. This
1448       // shouldn't be necessary except that RFP cannot be live across
1449       // multiple blocks. When stackifier is fixed, they can be uncoupled.
1450       MachineFunction &MF = DAG.getMachineFunction();
1451       int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
1452       SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1453       std::vector<MVT::ValueType> Tys;
1454       Tys.push_back(MVT::Other);
1455       std::vector<SDOperand> Ops;
1456       Ops.push_back(Chain);
1457       Ops.push_back(Result);
1458       Ops.push_back(StackSlot);
1459       Ops.push_back(DAG.getValueType(Op.getValueType()));
1460       Ops.push_back(InFlag);
1461       Chain = DAG.getNode(X86ISD::FST, Tys, Ops);
1462       Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
1463                            DAG.getSrcValue(NULL));
1464     }
1465
1466     return Result;
1467   }
1468   case ISD::FP_TO_SINT: {
1469     assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
1470            "Unknown FP_TO_SINT to lower!");
1471     // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
1472     // stack slot.
1473     MachineFunction &MF = DAG.getMachineFunction();
1474     unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
1475     int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1476     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1477
1478     unsigned Opc;
1479     switch (Op.getValueType()) {
1480     default: assert(0 && "Invalid FP_TO_SINT to lower!");
1481     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
1482     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
1483     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
1484     }
1485
1486     SDOperand Chain = DAG.getEntryNode();
1487     SDOperand Value = Op.getOperand(0);
1488     if (X86ScalarSSE) {
1489       assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
1490       Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value, StackSlot, 
1491                           DAG.getSrcValue(0));
1492       std::vector<MVT::ValueType> Tys;
1493       Tys.push_back(MVT::f64);
1494       Tys.push_back(MVT::Other);
1495       std::vector<SDOperand> Ops;
1496       Ops.push_back(Chain);
1497       Ops.push_back(StackSlot);
1498       Ops.push_back(DAG.getValueType(Op.getOperand(0).getValueType()));
1499       Value = DAG.getNode(X86ISD::FLD, Tys, Ops);
1500       Chain = Value.getValue(1);
1501       SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1502       StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1503     }
1504
1505     // Build the FP_TO_INT*_IN_MEM
1506     std::vector<SDOperand> Ops;
1507     Ops.push_back(Chain);
1508     Ops.push_back(Value);
1509     Ops.push_back(StackSlot);
1510     SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
1511
1512     // Load the result.
1513     return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
1514                        DAG.getSrcValue(NULL));
1515   }
1516   case ISD::READCYCLECOUNTER: {
1517     std::vector<MVT::ValueType> Tys;
1518     Tys.push_back(MVT::Other);
1519     Tys.push_back(MVT::Flag);
1520     std::vector<SDOperand> Ops;
1521     Ops.push_back(Op.getOperand(0));
1522     SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, Ops);
1523     Ops.clear();
1524     Ops.push_back(DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1)));
1525     Ops.push_back(DAG.getCopyFromReg(Ops[0].getValue(1), X86::EDX, 
1526                                      MVT::i32, Ops[0].getValue(2)));
1527     Ops.push_back(Ops[1].getValue(1));
1528     Tys[0] = Tys[1] = MVT::i32;
1529     Tys.push_back(MVT::Other);
1530     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
1531   }
1532   case ISD::FABS: {
1533     MVT::ValueType VT = Op.getValueType();
1534     const Type *OpNTy =  MVT::getTypeForValueType(VT);
1535     std::vector<Constant*> CV;
1536     if (VT == MVT::f64) {
1537       CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(~(1ULL << 63))));
1538       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1539     } else {
1540       CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(~(1U << 31))));
1541       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1542       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1543       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1544     }
1545     Constant *CS = ConstantStruct::get(CV);
1546     SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
1547     SDOperand Mask 
1548       = DAG.getNode(X86ISD::LOAD_PACK,
1549                     VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
1550     return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
1551   }
1552   case ISD::FNEG: {
1553     MVT::ValueType VT = Op.getValueType();
1554     const Type *OpNTy =  MVT::getTypeForValueType(VT);
1555     std::vector<Constant*> CV;
1556     if (VT == MVT::f64) {
1557       CV.push_back(ConstantFP::get(OpNTy, BitsToDouble(1ULL << 63)));
1558       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1559     } else {
1560       CV.push_back(ConstantFP::get(OpNTy, BitsToFloat(1U << 31)));
1561       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1562       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1563       CV.push_back(ConstantFP::get(OpNTy, 0.0));
1564     }
1565     Constant *CS = ConstantStruct::get(CV);
1566     SDOperand CPIdx = DAG.getConstantPool(CS, getPointerTy(), 4);
1567     SDOperand Mask 
1568       = DAG.getNode(X86ISD::LOAD_PACK,
1569                     VT, DAG.getEntryNode(), CPIdx, DAG.getSrcValue(NULL));
1570     return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
1571   }
1572   case ISD::SETCC: {
1573     assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
1574     SDOperand Cond;
1575     SDOperand CC = Op.getOperand(2);
1576     ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
1577     bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
1578     bool Flip;
1579     unsigned X86CC;
1580     if (translateX86CC(CC, isFP, X86CC, Flip)) {
1581       if (Flip)
1582         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1583                            Op.getOperand(1), Op.getOperand(0));
1584       else
1585         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1586                            Op.getOperand(0), Op.getOperand(1));
1587       return DAG.getNode(X86ISD::SETCC, MVT::i8, 
1588                          DAG.getConstant(X86CC, MVT::i8), Cond);
1589     } else {
1590       assert(isFP && "Illegal integer SetCC!");
1591
1592       Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1593                          Op.getOperand(0), Op.getOperand(1));
1594       std::vector<MVT::ValueType> Tys;
1595       std::vector<SDOperand> Ops;
1596       switch (SetCCOpcode) {
1597       default: assert(false && "Illegal floating point SetCC!");
1598       case ISD::SETOEQ: {  // !PF & ZF
1599         Tys.push_back(MVT::i8);
1600         Tys.push_back(MVT::Flag);
1601         Ops.push_back(DAG.getConstant(X86ISD::COND_NP, MVT::i8));
1602         Ops.push_back(Cond);
1603         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1604         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1605                                      DAG.getConstant(X86ISD::COND_E, MVT::i8),
1606                                      Tmp1.getValue(1));
1607         return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
1608       }
1609       case ISD::SETUNE: {  // PF | !ZF
1610         Tys.push_back(MVT::i8);
1611         Tys.push_back(MVT::Flag);
1612         Ops.push_back(DAG.getConstant(X86ISD::COND_P, MVT::i8));
1613         Ops.push_back(Cond);
1614         SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1615         SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
1616                                      DAG.getConstant(X86ISD::COND_NE, MVT::i8),
1617                                      Tmp1.getValue(1));
1618         return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
1619       }
1620       }
1621     }
1622   }
1623   case ISD::SELECT: {
1624     MVT::ValueType VT = Op.getValueType();
1625     bool isFP      = MVT::isFloatingPoint(VT);
1626     bool isFPStack = isFP && !X86ScalarSSE;
1627     bool isFPSSE   = isFP && X86ScalarSSE;
1628     bool addTest   = false;
1629     SDOperand Op0 = Op.getOperand(0);
1630     SDOperand Cond, CC;
1631     if (Op0.getOpcode() == ISD::SETCC)
1632       Op0 = LowerOperation(Op0, DAG);
1633
1634     if (Op0.getOpcode() == X86ISD::SETCC) {
1635       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1636       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1637       // have another use it will be eliminated.
1638       // If the X86ISD::SETCC has more than one use, then it's probably better
1639       // to use a test instead of duplicating the X86ISD::CMP (for register
1640       // pressure reason).
1641       if (Op0.getOperand(1).getOpcode() == X86ISD::CMP) {
1642         if (!Op0.hasOneUse()) {
1643           std::vector<MVT::ValueType> Tys;
1644           for (unsigned i = 0; i < Op0.Val->getNumValues(); ++i)
1645             Tys.push_back(Op0.Val->getValueType(i));
1646           std::vector<SDOperand> Ops;
1647           for (unsigned i = 0; i < Op0.getNumOperands(); ++i)
1648             Ops.push_back(Op0.getOperand(i));
1649           Op0 = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1650         }
1651
1652         CC   = Op0.getOperand(0);
1653         Cond = Op0.getOperand(1);
1654         // Make a copy as flag result cannot be used by more than one.
1655         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1656                            Cond.getOperand(0), Cond.getOperand(1));
1657         addTest =
1658           isFPStack && !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
1659       } else
1660         addTest = true;
1661     } else
1662       addTest = true;
1663
1664     if (addTest) {
1665       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1666       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Op0, Op0);
1667     }
1668
1669     std::vector<MVT::ValueType> Tys;
1670     Tys.push_back(Op.getValueType());
1671     Tys.push_back(MVT::Flag);
1672     std::vector<SDOperand> Ops;
1673     // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
1674     // condition is true.
1675     Ops.push_back(Op.getOperand(2));
1676     Ops.push_back(Op.getOperand(1));
1677     Ops.push_back(CC);
1678     Ops.push_back(Cond);
1679     return DAG.getNode(X86ISD::CMOV, Tys, Ops);
1680   }
1681   case ISD::BRCOND: {
1682     bool addTest = false;
1683     SDOperand Cond  = Op.getOperand(1);
1684     SDOperand Dest  = Op.getOperand(2);
1685     SDOperand CC;
1686     if (Cond.getOpcode() == ISD::SETCC)
1687       Cond = LowerOperation(Cond, DAG);
1688
1689     if (Cond.getOpcode() == X86ISD::SETCC) {
1690       // If condition flag is set by a X86ISD::CMP, then make a copy of it
1691       // (since flag operand cannot be shared). If the X86ISD::SETCC does not
1692       // have another use it will be eliminated.
1693       // If the X86ISD::SETCC has more than one use, then it's probably better
1694       // to use a test instead of duplicating the X86ISD::CMP (for register
1695       // pressure reason).
1696       if (Cond.getOperand(1).getOpcode() == X86ISD::CMP) {
1697         if (!Cond.hasOneUse()) {
1698           std::vector<MVT::ValueType> Tys;
1699           for (unsigned i = 0; i < Cond.Val->getNumValues(); ++i)
1700             Tys.push_back(Cond.Val->getValueType(i));
1701           std::vector<SDOperand> Ops;
1702           for (unsigned i = 0; i < Cond.getNumOperands(); ++i)
1703             Ops.push_back(Cond.getOperand(i));
1704           Cond = DAG.getNode(X86ISD::SETCC, Tys, Ops);
1705         }
1706
1707         CC   = Cond.getOperand(0);
1708         Cond = Cond.getOperand(1);
1709         // Make a copy as flag result cannot be used by more than one.
1710         Cond = DAG.getNode(X86ISD::CMP, MVT::Flag,
1711                            Cond.getOperand(0), Cond.getOperand(1));
1712       } else
1713         addTest = true;
1714     } else
1715       addTest = true;
1716
1717     if (addTest) {
1718       CC = DAG.getConstant(X86ISD::COND_NE, MVT::i8);
1719       Cond = DAG.getNode(X86ISD::TEST, MVT::Flag, Cond, Cond);
1720     }
1721     return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
1722                        Op.getOperand(0), Op.getOperand(2), CC, Cond);
1723   }
1724   case ISD::MEMSET: {
1725     SDOperand InFlag(0, 0);
1726     SDOperand Chain = Op.getOperand(0);
1727     unsigned Align =
1728       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1729     if (Align == 0) Align = 1;
1730
1731     ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
1732     // If not DWORD aligned, call memset if size is less than the threshold.
1733     // It knows how to align to the right boundary first.
1734     if ((Align & 3) != 0 ||
1735         (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
1736       MVT::ValueType IntPtr = getPointerTy();
1737       const Type *IntPtrTy = getTargetData().getIntPtrType();
1738       std::vector<std::pair<SDOperand, const Type*> > Args;
1739       Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
1740       // Extend the ubyte argument to be an int value for the call.
1741       SDOperand Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
1742       Args.push_back(std::make_pair(Val, IntPtrTy));
1743       Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
1744       std::pair<SDOperand,SDOperand> CallResult =
1745         LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
1746                     DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
1747       return CallResult.second;
1748     }
1749
1750     MVT::ValueType AVT;
1751     SDOperand Count;
1752     ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1753     unsigned BytesLeft = 0;
1754     bool TwoRepStos = false;
1755     if (ValC) {
1756       unsigned ValReg;
1757       unsigned Val = ValC->getValue() & 255;
1758
1759       // If the value is a constant, then we can potentially use larger sets.
1760       switch (Align & 3) {
1761       case 2:   // WORD aligned
1762         AVT = MVT::i16;
1763         Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1764         BytesLeft = I->getValue() % 2;
1765         Val    = (Val << 8) | Val;
1766         ValReg = X86::AX;
1767         break;
1768       case 0:   // DWORD aligned
1769         AVT = MVT::i32;
1770         if (I) {
1771           Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1772           BytesLeft = I->getValue() % 4;
1773         } else {
1774           Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1775                               DAG.getConstant(2, MVT::i8));
1776           TwoRepStos = true;
1777         }
1778         Val = (Val << 8)  | Val;
1779         Val = (Val << 16) | Val;
1780         ValReg = X86::EAX;
1781         break;
1782       default:  // Byte aligned
1783         AVT = MVT::i8;
1784         Count = Op.getOperand(3);
1785         ValReg = X86::AL;
1786         break;
1787       }
1788
1789       Chain  = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
1790                                 InFlag);
1791       InFlag = Chain.getValue(1);
1792     } else {
1793       AVT = MVT::i8;
1794       Count  = Op.getOperand(3);
1795       Chain  = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
1796       InFlag = Chain.getValue(1);
1797     }
1798
1799     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1800     InFlag = Chain.getValue(1);
1801     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1802     InFlag = Chain.getValue(1);
1803
1804     std::vector<MVT::ValueType> Tys;
1805     Tys.push_back(MVT::Other);
1806     Tys.push_back(MVT::Flag);
1807     std::vector<SDOperand> Ops;
1808     Ops.push_back(Chain);
1809     Ops.push_back(DAG.getValueType(AVT));
1810     Ops.push_back(InFlag);
1811     Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
1812
1813     if (TwoRepStos) {
1814       InFlag = Chain.getValue(1);
1815       Count = Op.getOperand(3);
1816       MVT::ValueType CVT = Count.getValueType();
1817       SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
1818                                    DAG.getConstant(3, CVT));
1819       Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
1820       InFlag = Chain.getValue(1);
1821       Tys.clear();
1822       Tys.push_back(MVT::Other);
1823       Tys.push_back(MVT::Flag);
1824       Ops.clear();
1825       Ops.push_back(Chain);
1826       Ops.push_back(DAG.getValueType(MVT::i8));
1827       Ops.push_back(InFlag);
1828       Chain  = DAG.getNode(X86ISD::REP_STOS, Tys, Ops);
1829     } else if (BytesLeft) {
1830       // Issue stores for the last 1 - 3 bytes.
1831       SDOperand Value;
1832       unsigned Val = ValC->getValue() & 255;
1833       unsigned Offset = I->getValue() - BytesLeft;
1834       SDOperand DstAddr = Op.getOperand(1);
1835       MVT::ValueType AddrVT = DstAddr.getValueType();
1836       if (BytesLeft >= 2) {
1837         Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
1838         Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1839                             DAG.getNode(ISD::ADD, AddrVT, DstAddr,
1840                                         DAG.getConstant(Offset, AddrVT)),
1841                             DAG.getSrcValue(NULL));
1842         BytesLeft -= 2;
1843         Offset += 2;
1844       }
1845
1846       if (BytesLeft == 1) {
1847         Value = DAG.getConstant(Val, MVT::i8);
1848         Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1849                             DAG.getNode(ISD::ADD, AddrVT, DstAddr,
1850                                         DAG.getConstant(Offset, AddrVT)),
1851                             DAG.getSrcValue(NULL));
1852       }
1853     }
1854
1855     return Chain;
1856   }
1857   case ISD::MEMCPY: {
1858     SDOperand Chain = Op.getOperand(0);
1859     unsigned Align =
1860       (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
1861     if (Align == 0) Align = 1;
1862
1863     ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
1864     // If not DWORD aligned, call memcpy if size is less than the threshold.
1865     // It knows how to align to the right boundary first.
1866     if ((Align & 3) != 0 ||
1867         (I && I->getValue() < Subtarget->getMinRepStrSizeThreshold())) {
1868       MVT::ValueType IntPtr = getPointerTy();
1869       const Type *IntPtrTy = getTargetData().getIntPtrType();
1870       std::vector<std::pair<SDOperand, const Type*> > Args;
1871       Args.push_back(std::make_pair(Op.getOperand(1), IntPtrTy));
1872       Args.push_back(std::make_pair(Op.getOperand(2), IntPtrTy));
1873       Args.push_back(std::make_pair(Op.getOperand(3), IntPtrTy));
1874       std::pair<SDOperand,SDOperand> CallResult =
1875         LowerCallTo(Chain, Type::VoidTy, false, CallingConv::C, false,
1876                     DAG.getExternalSymbol("memcpy", IntPtr), Args, DAG);
1877       return CallResult.second;
1878     }
1879
1880     MVT::ValueType AVT;
1881     SDOperand Count;
1882     unsigned BytesLeft = 0;
1883     bool TwoRepMovs = false;
1884     switch (Align & 3) {
1885     case 2:   // WORD aligned
1886       AVT = MVT::i16;
1887       Count = DAG.getConstant(I->getValue() / 2, MVT::i32);
1888       BytesLeft = I->getValue() % 2;
1889       break;
1890     case 0:   // DWORD aligned
1891       AVT = MVT::i32;
1892       if (I) {
1893         Count = DAG.getConstant(I->getValue() / 4, MVT::i32);
1894         BytesLeft = I->getValue() % 4;
1895       } else {
1896         Count = DAG.getNode(ISD::SRL, MVT::i32, Op.getOperand(3),
1897                             DAG.getConstant(2, MVT::i8));
1898         TwoRepMovs = true;
1899       }
1900       break;
1901     default:  // Byte aligned
1902       AVT = MVT::i8;
1903       Count = Op.getOperand(3);
1904       break;
1905     }
1906
1907     SDOperand InFlag(0, 0);
1908     Chain  = DAG.getCopyToReg(Chain, X86::ECX, Count, InFlag);
1909     InFlag = Chain.getValue(1);
1910     Chain  = DAG.getCopyToReg(Chain, X86::EDI, Op.getOperand(1), InFlag);
1911     InFlag = Chain.getValue(1);
1912     Chain  = DAG.getCopyToReg(Chain, X86::ESI, Op.getOperand(2), InFlag);
1913     InFlag = Chain.getValue(1);
1914
1915     std::vector<MVT::ValueType> Tys;
1916     Tys.push_back(MVT::Other);
1917     Tys.push_back(MVT::Flag);
1918     std::vector<SDOperand> Ops;
1919     Ops.push_back(Chain);
1920     Ops.push_back(DAG.getValueType(AVT));
1921     Ops.push_back(InFlag);
1922     Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
1923
1924     if (TwoRepMovs) {
1925       InFlag = Chain.getValue(1);
1926       Count = Op.getOperand(3);
1927       MVT::ValueType CVT = Count.getValueType();
1928       SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
1929                                    DAG.getConstant(3, CVT));
1930       Chain  = DAG.getCopyToReg(Chain, X86::ECX, Left, InFlag);
1931       InFlag = Chain.getValue(1);
1932       Tys.clear();
1933       Tys.push_back(MVT::Other);
1934       Tys.push_back(MVT::Flag);
1935       Ops.clear();
1936       Ops.push_back(Chain);
1937       Ops.push_back(DAG.getValueType(MVT::i8));
1938       Ops.push_back(InFlag);
1939       Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, Ops);
1940     } else if (BytesLeft) {
1941       // Issue loads and stores for the last 1 - 3 bytes.
1942       unsigned Offset = I->getValue() - BytesLeft;
1943       SDOperand DstAddr = Op.getOperand(1);
1944       MVT::ValueType DstVT = DstAddr.getValueType();
1945       SDOperand SrcAddr = Op.getOperand(2);
1946       MVT::ValueType SrcVT = SrcAddr.getValueType();
1947       SDOperand Value;
1948       if (BytesLeft >= 2) {
1949         Value = DAG.getLoad(MVT::i16, Chain,
1950                             DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
1951                                         DAG.getConstant(Offset, SrcVT)),
1952                             DAG.getSrcValue(NULL));
1953         Chain = Value.getValue(1);
1954         Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1955                             DAG.getNode(ISD::ADD, DstVT, DstAddr,
1956                                         DAG.getConstant(Offset, DstVT)),
1957                             DAG.getSrcValue(NULL));
1958         BytesLeft -= 2;
1959         Offset += 2;
1960       }
1961
1962       if (BytesLeft == 1) {
1963         Value = DAG.getLoad(MVT::i8, Chain,
1964                             DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
1965                                         DAG.getConstant(Offset, SrcVT)),
1966                             DAG.getSrcValue(NULL));
1967         Chain = Value.getValue(1);
1968         Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1969                             DAG.getNode(ISD::ADD, DstVT, DstAddr,
1970                                         DAG.getConstant(Offset, DstVT)),
1971                             DAG.getSrcValue(NULL));
1972       }
1973     }
1974
1975     return Chain;
1976   }
1977
1978   // ConstantPool, GlobalAddress, and ExternalSymbol are lowered as their
1979   // target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
1980   // one of the above mentioned nodes. It has to be wrapped because otherwise
1981   // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
1982   // be used to form addressing mode. These wrapped nodes will be selected
1983   // into MOV32ri.
1984   case ISD::ConstantPool: {
1985     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1986     SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
1987                          DAG.getTargetConstantPool(CP->get(), getPointerTy(),
1988                                                    CP->getAlignment()));
1989     if (getTargetMachine().getSubtarget<X86Subtarget>().isTargetDarwin()) {
1990       // With PIC, the address is actually $g + Offset.
1991       if (getTargetMachine().getRelocationModel() == Reloc::PIC)
1992         Result = DAG.getNode(ISD::ADD, getPointerTy(),
1993                 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()), Result);    
1994     }
1995
1996     return Result;
1997   }
1998   case ISD::GlobalAddress: {
1999     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2000     SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2001                          DAG.getTargetGlobalAddress(GV, getPointerTy()));
2002     if (getTargetMachine().
2003         getSubtarget<X86Subtarget>().isTargetDarwin()) {
2004       // With PIC, the address is actually $g + Offset.
2005       if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2006         Result = DAG.getNode(ISD::ADD, getPointerTy(),
2007                     DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()), Result);
2008
2009       // For Darwin, external and weak symbols are indirect, so we want to load
2010       // the value at address GV, not the value of GV itself. This means that
2011       // the GlobalAddress must be in the base or index register of the address,
2012       // not the GV offset field.
2013       if (getTargetMachine().getRelocationModel() != Reloc::Static &&
2014           DarwinGVRequiresExtraLoad(GV))
2015         Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(),
2016                              Result, DAG.getSrcValue(NULL));
2017     }
2018
2019     return Result;
2020   }
2021   case ISD::ExternalSymbol: {
2022     const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
2023     SDOperand Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(),
2024                          DAG.getTargetExternalSymbol(Sym, getPointerTy()));
2025     if (getTargetMachine().
2026         getSubtarget<X86Subtarget>().isTargetDarwin()) {
2027       // With PIC, the address is actually $g + Offset.
2028       if (getTargetMachine().getRelocationModel() == Reloc::PIC)
2029         Result = DAG.getNode(ISD::ADD, getPointerTy(),
2030                     DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()), Result);
2031     }
2032
2033     return Result;
2034   }
2035   case ISD::VASTART: {
2036     // vastart just stores the address of the VarArgsFrameIndex slot into the
2037     // memory location argument.
2038     // FIXME: Replace MVT::i32 with PointerTy
2039     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
2040     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
2041                        Op.getOperand(1), Op.getOperand(2));
2042   }
2043   case ISD::RET: {
2044     SDOperand Copy;
2045     
2046     switch(Op.getNumOperands()) {
2047     default:
2048       assert(0 && "Do not know how to return this many arguments!");
2049       abort();
2050     case 1: 
2051       return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Op.getOperand(0),
2052                          DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
2053     case 2: {
2054       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
2055       if (MVT::isInteger(ArgVT))
2056         Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EAX, Op.getOperand(1),
2057                                 SDOperand());
2058       else if (!X86ScalarSSE) {
2059         std::vector<MVT::ValueType> Tys;
2060         Tys.push_back(MVT::Other);
2061         Tys.push_back(MVT::Flag);
2062         std::vector<SDOperand> Ops;
2063         Ops.push_back(Op.getOperand(0));
2064         Ops.push_back(Op.getOperand(1));
2065         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
2066       } else {
2067         SDOperand MemLoc;
2068         SDOperand Chain = Op.getOperand(0);
2069         SDOperand Value = Op.getOperand(1);
2070
2071         if (Value.getOpcode() == ISD::LOAD &&
2072             (Chain == Value.getValue(1) || Chain == Value.getOperand(0))) {
2073           Chain  = Value.getOperand(0);
2074           MemLoc = Value.getOperand(1);
2075         } else {
2076           // Spill the value to memory and reload it into top of stack.
2077           unsigned Size = MVT::getSizeInBits(ArgVT)/8;
2078           MachineFunction &MF = DAG.getMachineFunction();
2079           int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
2080           MemLoc = DAG.getFrameIndex(SSFI, getPointerTy());
2081           Chain = DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), 
2082                               Value, MemLoc, DAG.getSrcValue(0));
2083         }
2084         std::vector<MVT::ValueType> Tys;
2085         Tys.push_back(MVT::f64);
2086         Tys.push_back(MVT::Other);
2087         std::vector<SDOperand> Ops;
2088         Ops.push_back(Chain);
2089         Ops.push_back(MemLoc);
2090         Ops.push_back(DAG.getValueType(ArgVT));
2091         Copy = DAG.getNode(X86ISD::FLD, Tys, Ops);
2092         Tys.clear();
2093         Tys.push_back(MVT::Other);
2094         Tys.push_back(MVT::Flag);
2095         Ops.clear();
2096         Ops.push_back(Copy.getValue(1));
2097         Ops.push_back(Copy);
2098         Copy = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops);
2099       }
2100       break;
2101     }
2102     case 3:
2103       Copy = DAG.getCopyToReg(Op.getOperand(0), X86::EDX, Op.getOperand(2), 
2104                               SDOperand());
2105       Copy = DAG.getCopyToReg(Copy, X86::EAX,Op.getOperand(1),Copy.getValue(1));
2106       break;
2107     }
2108     return DAG.getNode(X86ISD::RET_FLAG, MVT::Other,
2109                        Copy, DAG.getConstant(getBytesToPopOnReturn(), MVT::i16),
2110                        Copy.getValue(1));
2111   }
2112   }
2113 }
2114
2115 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
2116   switch (Opcode) {
2117   default: return NULL;
2118   case X86ISD::SHLD:               return "X86ISD::SHLD";
2119   case X86ISD::SHRD:               return "X86ISD::SHRD";
2120   case X86ISD::FAND:               return "X86ISD::FAND";
2121   case X86ISD::FXOR:               return "X86ISD::FXOR";
2122   case X86ISD::FILD:               return "X86ISD::FILD";
2123   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
2124   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
2125   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
2126   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
2127   case X86ISD::FLD:                return "X86ISD::FLD";
2128   case X86ISD::FST:                return "X86ISD::FST";
2129   case X86ISD::FP_GET_RESULT:      return "X86ISD::FP_GET_RESULT";
2130   case X86ISD::FP_SET_RESULT:      return "X86ISD::FP_SET_RESULT";
2131   case X86ISD::CALL:               return "X86ISD::CALL";
2132   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
2133   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
2134   case X86ISD::CMP:                return "X86ISD::CMP";
2135   case X86ISD::TEST:               return "X86ISD::TEST";
2136   case X86ISD::SETCC:              return "X86ISD::SETCC";
2137   case X86ISD::CMOV:               return "X86ISD::CMOV";
2138   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
2139   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
2140   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
2141   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
2142   case X86ISD::LOAD_PACK:          return "X86ISD::LOAD_PACK";
2143   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
2144   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
2145   }
2146 }
2147
2148 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
2149                                                        uint64_t Mask,
2150                                                        uint64_t &KnownZero, 
2151                                                        uint64_t &KnownOne,
2152                                                        unsigned Depth) const {
2153
2154   unsigned Opc = Op.getOpcode();
2155   KnownZero = KnownOne = 0;   // Don't know anything.
2156
2157   switch (Opc) {
2158   default:
2159     assert(Opc >= ISD::BUILTIN_OP_END && "Expected a target specific node");
2160     break;
2161   case X86ISD::SETCC: 
2162     KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
2163     break;
2164   }
2165 }
2166
2167 std::vector<unsigned> X86TargetLowering::
2168 getRegClassForInlineAsmConstraint(const std::string &Constraint,
2169                                   MVT::ValueType VT) const {
2170   if (Constraint.size() == 1) {
2171     // FIXME: not handling fp-stack yet!
2172     // FIXME: not handling MMX registers yet ('y' constraint).
2173     switch (Constraint[0]) {      // GCC X86 Constraint Letters
2174     default: break;  // Unknown constriant letter
2175     case 'r':   // GENERAL_REGS
2176     case 'R':   // LEGACY_REGS
2177       return make_vector<unsigned>(X86::EAX, X86::EBX, X86::ECX, X86::EDX,
2178                                    X86::ESI, X86::EDI, X86::EBP, X86::ESP, 0);
2179     case 'l':   // INDEX_REGS
2180       return make_vector<unsigned>(X86::EAX, X86::EBX, X86::ECX, X86::EDX,
2181                                    X86::ESI, X86::EDI, X86::EBP, 0);
2182     case 'q':   // Q_REGS (GENERAL_REGS in 64-bit mode)
2183     case 'Q':   // Q_REGS
2184       return make_vector<unsigned>(X86::EAX, X86::EBX, X86::ECX, X86::EDX, 0);
2185     case 'x':   // SSE_REGS if SSE1 allowed
2186       if (Subtarget->hasSSE1())
2187         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2188                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
2189                                      0);
2190       return std::vector<unsigned>();
2191     case 'Y':   // SSE_REGS if SSE2 allowed
2192       if (Subtarget->hasSSE2())
2193         return make_vector<unsigned>(X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2194                                      X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7,
2195                                      0);
2196       return std::vector<unsigned>();
2197     }
2198   }
2199   
2200   return std::vector<unsigned>();
2201 }
2202
2203 /// isLegalAddressImmediate - Return true if the integer value or
2204 /// GlobalValue can be used as the offset of the target addressing mode.
2205 bool X86TargetLowering::isLegalAddressImmediate(int64_t V) const {
2206   // X86 allows a sign-extended 32-bit immediate field.
2207   return (V > -(1LL << 32) && V < (1LL << 32)-1);
2208 }
2209
2210 bool X86TargetLowering::isLegalAddressImmediate(GlobalValue *GV) const {
2211   if (getTargetMachine().
2212       getSubtarget<X86Subtarget>().isTargetDarwin()) {
2213     Reloc::Model RModel = getTargetMachine().getRelocationModel();
2214     if (RModel == Reloc::Static)
2215       return true;
2216     else if (RModel == Reloc::DynamicNoPIC)
2217       return !DarwinGVRequiresExtraLoad(GV);
2218     else
2219       return false;
2220   } else
2221     return true;
2222 }