split sparc lowering out into SparcISelLowering.{cpp|h} to follow
[oota-llvm.git] / lib / Target / Sparc / SparcISelLowering.cpp
1 //===-- SparcISelLowering.cpp - Sparc DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Sparc uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcISelLowering.h"
16 #include "SparcTargetMachine.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // TargetLowering Implementation
28 //===----------------------------------------------------------------------===//
29
30 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
31 /// condition.
32 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
33   switch (CC) {
34   default: assert(0 && "Unknown integer condition code!");
35   case ISD::SETEQ:  return SPCC::ICC_E;
36   case ISD::SETNE:  return SPCC::ICC_NE;
37   case ISD::SETLT:  return SPCC::ICC_L;
38   case ISD::SETGT:  return SPCC::ICC_G;
39   case ISD::SETLE:  return SPCC::ICC_LE;
40   case ISD::SETGE:  return SPCC::ICC_GE;
41   case ISD::SETULT: return SPCC::ICC_CS;
42   case ISD::SETULE: return SPCC::ICC_LEU;
43   case ISD::SETUGT: return SPCC::ICC_GU;
44   case ISD::SETUGE: return SPCC::ICC_CC;
45   }
46 }
47
48 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
49 /// FCC condition.
50 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
51   switch (CC) {
52   default: assert(0 && "Unknown fp condition code!");
53   case ISD::SETEQ:
54   case ISD::SETOEQ: return SPCC::FCC_E;
55   case ISD::SETNE:
56   case ISD::SETUNE: return SPCC::FCC_NE;
57   case ISD::SETLT:
58   case ISD::SETOLT: return SPCC::FCC_L;
59   case ISD::SETGT:
60   case ISD::SETOGT: return SPCC::FCC_G;
61   case ISD::SETLE:
62   case ISD::SETOLE: return SPCC::FCC_LE;
63   case ISD::SETGE:
64   case ISD::SETOGE: return SPCC::FCC_GE;
65   case ISD::SETULT: return SPCC::FCC_UL;
66   case ISD::SETULE: return SPCC::FCC_ULE;
67   case ISD::SETUGT: return SPCC::FCC_UG;
68   case ISD::SETUGE: return SPCC::FCC_UGE;
69   case ISD::SETUO:  return SPCC::FCC_U;
70   case ISD::SETO:   return SPCC::FCC_O;
71   case ISD::SETONE: return SPCC::FCC_LG;
72   case ISD::SETUEQ: return SPCC::FCC_UE;
73   }
74 }
75
76
77 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
78   : TargetLowering(TM) {
79   
80   // Set up the register classes.
81   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
82   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
83   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
84
85   // Turn FP extload into load/fextend
86   setLoadXAction(ISD::EXTLOAD, MVT::f32, Expand);
87   // Sparc doesn't have i1 sign extending load
88   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
89   // Turn FP truncstore into trunc + store.
90   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
91
92   // Custom legalize GlobalAddress nodes into LO/HI parts.
93   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
94   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
95   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
96   
97   // Sparc doesn't have sext_inreg, replace them with shl/sra
98   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
99   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
100   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
101
102   // Sparc has no REM or DIVREM operations.
103   setOperationAction(ISD::UREM, MVT::i32, Expand);
104   setOperationAction(ISD::SREM, MVT::i32, Expand);
105   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
106   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
107
108   // Custom expand fp<->sint
109   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
110   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
111
112   // Expand fp<->uint
113   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
114   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
115   
116   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
117   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
118   
119   // Sparc has no select or setcc: expand to SELECT_CC.
120   setOperationAction(ISD::SELECT, MVT::i32, Expand);
121   setOperationAction(ISD::SELECT, MVT::f32, Expand);
122   setOperationAction(ISD::SELECT, MVT::f64, Expand);
123   setOperationAction(ISD::SETCC, MVT::i32, Expand);
124   setOperationAction(ISD::SETCC, MVT::f32, Expand);
125   setOperationAction(ISD::SETCC, MVT::f64, Expand);
126   
127   // Sparc doesn't have BRCOND either, it has BR_CC.
128   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
129   setOperationAction(ISD::BRIND, MVT::Other, Expand);
130   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
131   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
132   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
133   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
134   
135   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
136   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
137   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
138   
139   // SPARC has no intrinsics for these particular operations.
140   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
141   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
142   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
143   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
144
145   setOperationAction(ISD::FSIN , MVT::f64, Expand);
146   setOperationAction(ISD::FCOS , MVT::f64, Expand);
147   setOperationAction(ISD::FREM , MVT::f64, Expand);
148   setOperationAction(ISD::FSIN , MVT::f32, Expand);
149   setOperationAction(ISD::FCOS , MVT::f32, Expand);
150   setOperationAction(ISD::FREM , MVT::f32, Expand);
151   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
152   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
153   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
154   setOperationAction(ISD::ROTL , MVT::i32, Expand);
155   setOperationAction(ISD::ROTR , MVT::i32, Expand);
156   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
157   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
158   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
159   setOperationAction(ISD::FPOW , MVT::f64, Expand);
160   setOperationAction(ISD::FPOW , MVT::f32, Expand);
161
162   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
163   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
164   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
165
166   // FIXME: Sparc provides these multiplies, but we don't have them yet.
167   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
168     
169   // We don't have line number support yet.
170   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
171   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
172   setOperationAction(ISD::LABEL, MVT::Other, Expand);
173
174   // RET must be custom lowered, to meet ABI requirements
175   setOperationAction(ISD::RET               , MVT::Other, Custom);
176
177   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
178   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
179   // VAARG needs to be lowered to not do unaligned accesses for doubles.
180   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
181   
182   // Use the default implementation.
183   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
184   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
185   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
186   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
187   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
188
189   // No debug info support yet.
190   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
191   setOperationAction(ISD::LABEL, MVT::Other, Expand);
192   setOperationAction(ISD::DECLARE, MVT::Other, Expand);
193     
194   setStackPointerRegisterToSaveRestore(SP::O6);
195
196   if (TM.getSubtarget<SparcSubtarget>().isV9())
197     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
198   
199   computeRegisterProperties();
200 }
201
202 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
203   switch (Opcode) {
204   default: return 0;
205   case SPISD::CMPICC:     return "SPISD::CMPICC";
206   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
207   case SPISD::BRICC:      return "SPISD::BRICC";
208   case SPISD::BRFCC:      return "SPISD::BRFCC";
209   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
210   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
211   case SPISD::Hi:         return "SPISD::Hi";
212   case SPISD::Lo:         return "SPISD::Lo";
213   case SPISD::FTOI:       return "SPISD::FTOI";
214   case SPISD::ITOF:       return "SPISD::ITOF";
215   case SPISD::CALL:       return "SPISD::CALL";
216   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
217   }
218 }
219
220 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
221 /// be zero. Op is expected to be a target specific node. Used by DAG
222 /// combiner.
223 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
224                                                          const APInt &Mask,
225                                                          APInt &KnownZero, 
226                                                          APInt &KnownOne,
227                                                          const SelectionDAG &DAG,
228                                                          unsigned Depth) const {
229   APInt KnownZero2, KnownOne2;
230   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
231   
232   switch (Op.getOpcode()) {
233   default: break;
234   case SPISD::SELECT_ICC:
235   case SPISD::SELECT_FCC:
236     DAG.ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne,
237                           Depth+1);
238     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2,
239                           Depth+1);
240     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
241     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
242     
243     // Only known if known in both the LHS and RHS.
244     KnownOne &= KnownOne2;
245     KnownZero &= KnownZero2;
246     break;
247   }
248 }
249
250 /// LowerArguments - V8 uses a very simple ABI, where all values are passed in
251 /// either one or two GPRs, including FP values.  TODO: we should pass FP values
252 /// in FP registers for fastcc functions.
253 std::vector<SDOperand>
254 SparcTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
255   MachineFunction &MF = DAG.getMachineFunction();
256   MachineRegisterInfo &RegInfo = MF.getRegInfo();
257   std::vector<SDOperand> ArgValues;
258   
259   static const unsigned ArgRegs[] = {
260     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
261   };
262   
263   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
264   unsigned ArgOffset = 68;
265   
266   SDOperand Root = DAG.getRoot();
267   std::vector<SDOperand> OutChains;
268
269   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
270     MVT::ValueType ObjectVT = getValueType(I->getType());
271     
272     switch (ObjectVT) {
273     default: assert(0 && "Unhandled argument type!");
274     case MVT::i1:
275     case MVT::i8:
276     case MVT::i16:
277     case MVT::i32:
278       if (I->use_empty()) {                // Argument is dead.
279         if (CurArgReg < ArgRegEnd) ++CurArgReg;
280         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
281       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
282         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
283         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
284         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
285         if (ObjectVT != MVT::i32) {
286           unsigned AssertOp = ISD::AssertSext;
287           Arg = DAG.getNode(AssertOp, MVT::i32, Arg, 
288                             DAG.getValueType(ObjectVT));
289           Arg = DAG.getNode(ISD::TRUNCATE, ObjectVT, Arg);
290         }
291         ArgValues.push_back(Arg);
292       } else {
293         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
294         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
295         SDOperand Load;
296         if (ObjectVT == MVT::i32) {
297           Load = DAG.getLoad(MVT::i32, Root, FIPtr, NULL, 0);
298         } else {
299           ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
300
301           // Sparc is big endian, so add an offset based on the ObjectVT.
302           unsigned Offset = 4-std::max(1U, MVT::getSizeInBits(ObjectVT)/8);
303           FIPtr = DAG.getNode(ISD::ADD, MVT::i32, FIPtr,
304                               DAG.getConstant(Offset, MVT::i32));
305           Load = DAG.getExtLoad(LoadOp, MVT::i32, Root, FIPtr,
306                                 NULL, 0, ObjectVT);
307           Load = DAG.getNode(ISD::TRUNCATE, ObjectVT, Load);
308         }
309         ArgValues.push_back(Load);
310       }
311       
312       ArgOffset += 4;
313       break;
314     case MVT::f32:
315       if (I->use_empty()) {                // Argument is dead.
316         if (CurArgReg < ArgRegEnd) ++CurArgReg;
317         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
318       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
319         // FP value is passed in an integer register.
320         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
321         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
322         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
323
324         Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Arg);
325         ArgValues.push_back(Arg);
326       } else {
327         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
328         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
329         SDOperand Load = DAG.getLoad(MVT::f32, Root, FIPtr, NULL, 0);
330         ArgValues.push_back(Load);
331       }
332       ArgOffset += 4;
333       break;
334
335     case MVT::i64:
336     case MVT::f64:
337       if (I->use_empty()) {                // Argument is dead.
338         if (CurArgReg < ArgRegEnd) ++CurArgReg;
339         if (CurArgReg < ArgRegEnd) ++CurArgReg;
340         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
341       } else if (/* FIXME: Apparently this isn't safe?? */
342                  0 && CurArgReg == ArgRegEnd && ObjectVT == MVT::f64 &&
343                  ((CurArgReg-ArgRegs) & 1) == 0) {
344         // If this is a double argument and the whole thing lives on the stack,
345         // and the argument is aligned, load the double straight from the stack.
346         // We can't do a load in cases like void foo([6ints], int,double),
347         // because the double wouldn't be aligned!
348         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset);
349         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
350         ArgValues.push_back(DAG.getLoad(MVT::f64, Root, FIPtr, NULL, 0));
351       } else {
352         SDOperand HiVal;
353         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
354           unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
355           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegHi);
356           HiVal = DAG.getCopyFromReg(Root, VRegHi, MVT::i32);
357         } else {
358           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
359           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
360           HiVal = DAG.getLoad(MVT::i32, Root, FIPtr, NULL, 0);
361         }
362         
363         SDOperand LoVal;
364         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
365           unsigned VRegLo = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
366           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegLo);
367           LoVal = DAG.getCopyFromReg(Root, VRegLo, MVT::i32);
368         } else {
369           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4);
370           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
371           LoVal = DAG.getLoad(MVT::i32, Root, FIPtr, NULL, 0);
372         }
373         
374         // Compose the two halves together into an i64 unit.
375         SDOperand WholeValue = 
376           DAG.getNode(ISD::BUILD_PAIR, MVT::i64, LoVal, HiVal);
377         
378         // If we want a double, do a bit convert.
379         if (ObjectVT == MVT::f64)
380           WholeValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, WholeValue);
381         
382         ArgValues.push_back(WholeValue);
383       }
384       ArgOffset += 8;
385       break;
386     }
387   }
388   
389   // Store remaining ArgRegs to the stack if this is a varargs function.
390   if (F.getFunctionType()->isVarArg()) {
391     // Remember the vararg offset for the va_start implementation.
392     VarArgsFrameOffset = ArgOffset;
393     
394     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
395       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
396       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
397       SDOperand Arg = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
398
399       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
400       SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
401
402       OutChains.push_back(DAG.getStore(DAG.getRoot(), Arg, FIPtr, NULL, 0));
403       ArgOffset += 4;
404     }
405   }
406   
407   if (!OutChains.empty())
408     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
409                             &OutChains[0], OutChains.size()));
410   
411   // Finally, inform the code generator which regs we return values in.
412   switch (getValueType(F.getReturnType())) {
413   default: assert(0 && "Unknown type!");
414   case MVT::isVoid: break;
415   case MVT::i1:
416   case MVT::i8:
417   case MVT::i16:
418   case MVT::i32:
419     MF.getRegInfo().addLiveOut(SP::I0);
420     break;
421   case MVT::i64:
422     MF.getRegInfo().addLiveOut(SP::I0);
423     MF.getRegInfo().addLiveOut(SP::I1);
424     break;
425   case MVT::f32:
426     MF.getRegInfo().addLiveOut(SP::F0);
427     break;
428   case MVT::f64:
429     MF.getRegInfo().addLiveOut(SP::D0);
430     break;
431   }
432   
433   return ArgValues;
434 }
435
436 std::pair<SDOperand, SDOperand>
437 SparcTargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
438                                  bool RetSExt, bool RetZExt, bool isVarArg,
439                                  unsigned CC, bool isTailCall, SDOperand Callee,
440                                  ArgListTy &Args, SelectionDAG &DAG) {
441   // Count the size of the outgoing arguments.
442   unsigned ArgsSize = 0;
443   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
444     switch (getValueType(Args[i].Ty)) {
445     default: assert(0 && "Unknown value type!");
446     case MVT::i1:
447     case MVT::i8:
448     case MVT::i16:
449     case MVT::i32:
450     case MVT::f32:
451       ArgsSize += 4;
452       break;
453     case MVT::i64:
454     case MVT::f64:
455       ArgsSize += 8;
456       break;
457     }
458   }
459   if (ArgsSize > 4*6)
460     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
461   else
462     ArgsSize = 0;
463
464   // Keep stack frames 8-byte aligned.
465   ArgsSize = (ArgsSize+7) & ~7;
466
467   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(ArgsSize, getPointerTy()));
468   
469   SDOperand StackPtr;
470   std::vector<SDOperand> Stores;
471   std::vector<SDOperand> RegValuesToPass;
472   unsigned ArgOffset = 68;
473   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
474     SDOperand Val = Args[i].Node;
475     MVT::ValueType ObjectVT = Val.getValueType();
476     SDOperand ValToStore(0, 0);
477     unsigned ObjSize;
478     switch (ObjectVT) {
479     default: assert(0 && "Unhandled argument type!");
480     case MVT::i1:
481     case MVT::i8:
482     case MVT::i16: {
483       // Promote the integer to 32-bits.  If the input type is signed, use a
484       // sign extend, otherwise use a zero extend.
485       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
486       if (Args[i].isSExt)
487         ExtendKind = ISD::SIGN_EXTEND;
488       else if (Args[i].isZExt)
489         ExtendKind = ISD::ZERO_EXTEND;
490       Val = DAG.getNode(ExtendKind, MVT::i32, Val);
491       // FALL THROUGH
492     }
493     case MVT::i32:
494       ObjSize = 4;
495
496       if (RegValuesToPass.size() >= 6) {
497         ValToStore = Val;
498       } else {
499         RegValuesToPass.push_back(Val);
500       }
501       break;
502     case MVT::f32:
503       ObjSize = 4;
504       if (RegValuesToPass.size() >= 6) {
505         ValToStore = Val;
506       } else {
507         // Convert this to a FP value in an int reg.
508         Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Val);
509         RegValuesToPass.push_back(Val);
510       }
511       break;
512     case MVT::f64:
513       ObjSize = 8;
514       // If we can store this directly into the outgoing slot, do so.  We can
515       // do this when all ArgRegs are used and if the outgoing slot is aligned.
516       // FIXME: McGill/misr fails with this.
517       if (0 && RegValuesToPass.size() >= 6 && ((ArgOffset-68) & 7) == 0) {
518         ValToStore = Val;
519         break;
520       }
521       
522       // Otherwise, convert this to a FP value in int regs.
523       Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Val);
524       // FALL THROUGH
525     case MVT::i64:
526       ObjSize = 8;
527       if (RegValuesToPass.size() >= 6) {
528         ValToStore = Val;    // Whole thing is passed in memory.
529         break;
530       }
531       
532       // Split the value into top and bottom part.  Top part goes in a reg.
533       SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, getPointerTy(), Val, 
534                                  DAG.getConstant(1, MVT::i32));
535       SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, getPointerTy(), Val,
536                                  DAG.getConstant(0, MVT::i32));
537       RegValuesToPass.push_back(Hi);
538       
539       if (RegValuesToPass.size() >= 6) {
540         ValToStore = Lo;
541         ArgOffset += 4;
542         ObjSize = 4;
543       } else {
544         RegValuesToPass.push_back(Lo);
545       }
546       break;
547     }
548     
549     if (ValToStore.Val) {
550       if (!StackPtr.Val) {
551         StackPtr = DAG.getRegister(SP::O6, MVT::i32);
552       }
553       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
554       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
555       Stores.push_back(DAG.getStore(Chain, ValToStore, PtrOff, NULL, 0));
556     }
557     ArgOffset += ObjSize;
558   }
559   
560   // Emit all stores, make sure the occur before any copies into physregs.
561   if (!Stores.empty())
562     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],Stores.size());
563   
564   static const unsigned ArgRegs[] = {
565     SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5
566   };
567   
568   // Build a sequence of copy-to-reg nodes chained together with token chain
569   // and flag operands which copy the outgoing args into O[0-5].
570   SDOperand InFlag;
571   for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
572     Chain = DAG.getCopyToReg(Chain, ArgRegs[i], RegValuesToPass[i], InFlag);
573     InFlag = Chain.getValue(1);
574   }
575
576   // If the callee is a GlobalAddress node (quite common, every direct call is)
577   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
578   // Likewise ExternalSymbol -> TargetExternalSymbol.
579   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
580     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
581   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
582     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
583
584   std::vector<MVT::ValueType> NodeTys;
585   NodeTys.push_back(MVT::Other);   // Returns a chain
586   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
587   SDOperand Ops[] = { Chain, Callee, InFlag };
588   Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops, InFlag.Val ? 3 : 2);
589   InFlag = Chain.getValue(1);
590   
591   MVT::ValueType RetTyVT = getValueType(RetTy);
592   SDOperand RetVal;
593   if (RetTyVT != MVT::isVoid) {
594     switch (RetTyVT) {
595     default: assert(0 && "Unknown value type to return!");
596     case MVT::i1:
597     case MVT::i8:
598     case MVT::i16: {
599       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
600       Chain = RetVal.getValue(1);
601       
602       // Add a note to keep track of whether it is sign or zero extended.
603       ISD::NodeType AssertKind = ISD::DELETED_NODE;
604       if (RetSExt)
605         AssertKind = ISD::AssertSext;
606       else if (RetZExt)
607         AssertKind = ISD::AssertZext;
608
609       if (AssertKind != ISD::DELETED_NODE)
610         RetVal = DAG.getNode(AssertKind, MVT::i32, RetVal,
611                              DAG.getValueType(RetTyVT));
612
613       RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
614       break;
615     }
616     case MVT::i32:
617       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
618       Chain = RetVal.getValue(1);
619       break;
620     case MVT::f32:
621       RetVal = DAG.getCopyFromReg(Chain, SP::F0, MVT::f32, InFlag);
622       Chain = RetVal.getValue(1);
623       break;
624     case MVT::f64:
625       RetVal = DAG.getCopyFromReg(Chain, SP::D0, MVT::f64, InFlag);
626       Chain = RetVal.getValue(1);
627       break;
628     case MVT::i64:
629       SDOperand Lo = DAG.getCopyFromReg(Chain, SP::O1, MVT::i32, InFlag);
630       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), SP::O0, MVT::i32, 
631                                         Lo.getValue(2));
632       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
633       Chain = Hi.getValue(1);
634       break;
635     }
636   }
637   
638   Chain = DAG.getCALLSEQ_END(Chain,
639                              DAG.getConstant(ArgsSize, getPointerTy()),
640                              DAG.getConstant(0, getPointerTy()),
641                              SDOperand());
642   return std::make_pair(RetVal, Chain);
643 }
644
645 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
646 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
647 static void LookThroughSetCC(SDOperand &LHS, SDOperand &RHS,
648                              ISD::CondCode CC, unsigned &SPCC) {
649   if (isa<ConstantSDNode>(RHS) && cast<ConstantSDNode>(RHS)->getValue() == 0 &&
650       CC == ISD::SETNE && 
651       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
652         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
653        (LHS.getOpcode() == SPISD::SELECT_FCC &&
654         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
655       isa<ConstantSDNode>(LHS.getOperand(0)) &&
656       isa<ConstantSDNode>(LHS.getOperand(1)) &&
657       cast<ConstantSDNode>(LHS.getOperand(0))->getValue() == 1 &&
658       cast<ConstantSDNode>(LHS.getOperand(1))->getValue() == 0) {
659     SDOperand CMPCC = LHS.getOperand(3);
660     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getValue();
661     LHS = CMPCC.getOperand(0);
662     RHS = CMPCC.getOperand(1);
663   }
664 }
665
666 static SDOperand LowerGLOBALADDRESS(SDOperand Op, SelectionDAG &DAG) {
667   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
668   SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
669   SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, GA);
670   SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, GA);
671   return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
672 }
673
674 static SDOperand LowerCONSTANTPOOL(SDOperand Op, SelectionDAG &DAG) {
675   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
676   Constant *C = N->getConstVal();
677   SDOperand CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
678   SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, CP);
679   SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, CP);
680   return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
681 }
682
683 static SDOperand LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
684   // Convert the fp value to integer in an FP register.
685   assert(Op.getValueType() == MVT::i32);
686   Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
687   return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
688 }
689
690 static SDOperand LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
691   assert(Op.getOperand(0).getValueType() == MVT::i32);
692   SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
693   // Convert the int value to FP in an FP register.
694   return DAG.getNode(SPISD::ITOF, Op.getValueType(), Tmp);
695 }
696
697 static SDOperand LowerBR_CC(SDOperand Op, SelectionDAG &DAG) {
698   SDOperand Chain = Op.getOperand(0);
699   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
700   SDOperand LHS = Op.getOperand(2);
701   SDOperand RHS = Op.getOperand(3);
702   SDOperand Dest = Op.getOperand(4);
703   unsigned Opc, SPCC = ~0U;
704   
705   // If this is a br_cc of a "setcc", and if the setcc got lowered into
706   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
707   LookThroughSetCC(LHS, RHS, CC, SPCC);
708   
709   // Get the condition flag.
710   SDOperand CompareFlag;
711   if (LHS.getValueType() == MVT::i32) {
712     std::vector<MVT::ValueType> VTs;
713     VTs.push_back(MVT::i32);
714     VTs.push_back(MVT::Flag);
715     SDOperand Ops[2] = { LHS, RHS };
716     CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops, 2).getValue(1);
717     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
718     Opc = SPISD::BRICC;
719   } else {
720     CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
721     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
722     Opc = SPISD::BRFCC;
723   }
724   return DAG.getNode(Opc, MVT::Other, Chain, Dest,
725                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
726 }
727
728 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
729   SDOperand LHS = Op.getOperand(0);
730   SDOperand RHS = Op.getOperand(1);
731   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
732   SDOperand TrueVal = Op.getOperand(2);
733   SDOperand FalseVal = Op.getOperand(3);
734   unsigned Opc, SPCC = ~0U;
735   
736   // If this is a select_cc of a "setcc", and if the setcc got lowered into
737   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
738   LookThroughSetCC(LHS, RHS, CC, SPCC);
739   
740   SDOperand CompareFlag;
741   if (LHS.getValueType() == MVT::i32) {
742     std::vector<MVT::ValueType> VTs;
743     VTs.push_back(LHS.getValueType());   // subcc returns a value
744     VTs.push_back(MVT::Flag);
745     SDOperand Ops[2] = { LHS, RHS };
746     CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops, 2).getValue(1);
747     Opc = SPISD::SELECT_ICC;
748     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
749   } else {
750     CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
751     Opc = SPISD::SELECT_FCC;
752     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
753   }
754   return DAG.getNode(Opc, TrueVal.getValueType(), TrueVal, FalseVal, 
755                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
756 }
757
758 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
759                               SparcTargetLowering &TLI) {
760   // vastart just stores the address of the VarArgsFrameIndex slot into the
761   // memory location argument.
762   SDOperand Offset = DAG.getNode(ISD::ADD, MVT::i32,
763                                  DAG.getRegister(SP::I6, MVT::i32),
764                                  DAG.getConstant(TLI.getVarArgsFrameOffset(),
765                                                  MVT::i32));
766   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
767   return DAG.getStore(Op.getOperand(0), Offset, Op.getOperand(1), SV, 0);
768 }
769
770 static SDOperand LowerVAARG(SDOperand Op, SelectionDAG &DAG) {
771   SDNode *Node = Op.Val;
772   MVT::ValueType VT = Node->getValueType(0);
773   SDOperand InChain = Node->getOperand(0);
774   SDOperand VAListPtr = Node->getOperand(1);
775   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
776   SDOperand VAList = DAG.getLoad(MVT::i32, InChain, VAListPtr, SV, 0);
777   // Increment the pointer, VAList, to the next vaarg
778   SDOperand NextPtr = DAG.getNode(ISD::ADD, MVT::i32, VAList, 
779                                   DAG.getConstant(MVT::getSizeInBits(VT)/8, 
780                                                   MVT::i32));
781   // Store the incremented VAList to the legalized pointer
782   InChain = DAG.getStore(VAList.getValue(1), NextPtr,
783                          VAListPtr, SV, 0);
784   // Load the actual argument out of the pointer VAList, unless this is an
785   // f64 load.
786   if (VT != MVT::f64)
787     return DAG.getLoad(VT, InChain, VAList, NULL, 0);
788   
789   // Otherwise, load it as i64, then do a bitconvert.
790   SDOperand V = DAG.getLoad(MVT::i64, InChain, VAList, NULL, 0);
791   
792   // Bit-Convert the value to f64.
793   SDOperand Ops[2] = {
794     DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V),
795     V.getValue(1)
796   };
797   return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(MVT::f64, MVT::Other),
798                      Ops, 2);
799 }
800
801 static SDOperand LowerDYNAMIC_STACKALLOC(SDOperand Op, SelectionDAG &DAG) {
802   SDOperand Chain = Op.getOperand(0);  // Legalize the chain.
803   SDOperand Size  = Op.getOperand(1);  // Legalize the size.
804   
805   unsigned SPReg = SP::O6;
806   SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, MVT::i32);
807   SDOperand NewSP = DAG.getNode(ISD::SUB, MVT::i32, SP, Size);    // Value
808   Chain = DAG.getCopyToReg(SP.getValue(1), SPReg, NewSP);      // Output chain
809   
810   // The resultant pointer is actually 16 words from the bottom of the stack,
811   // to provide a register spill area.
812   SDOperand NewVal = DAG.getNode(ISD::ADD, MVT::i32, NewSP,
813                                  DAG.getConstant(96, MVT::i32));
814   std::vector<MVT::ValueType> Tys;
815   Tys.push_back(MVT::i32);
816   Tys.push_back(MVT::Other);
817   SDOperand Ops[2] = { NewVal, Chain };
818   return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2);
819 }
820
821 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
822   SDOperand Copy;
823   
824   switch(Op.getNumOperands()) {
825   default:
826     assert(0 && "Do not know how to return this many arguments!");
827     abort();
828   case 1: 
829     return SDOperand(); // ret void is legal
830   case 3: {
831     unsigned ArgReg;
832     switch(Op.getOperand(1).getValueType()) {
833       default: assert(0 && "Unknown type to return!");
834       case MVT::i32: ArgReg = SP::I0; break;
835       case MVT::f32: ArgReg = SP::F0; break;
836       case MVT::f64: ArgReg = SP::D0; break;
837     }
838     Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
839                             SDOperand());
840     break;
841   }
842   case 5:
843     Copy = DAG.getCopyToReg(Op.getOperand(0), SP::I0, Op.getOperand(3), 
844                             SDOperand());
845     Copy = DAG.getCopyToReg(Copy, SP::I1, Op.getOperand(1), Copy.getValue(1));
846     break;
847   }
848   return DAG.getNode(SPISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
849 }
850
851
852 SDOperand SparcTargetLowering::
853 LowerOperation(SDOperand Op, SelectionDAG &DAG) {
854   switch (Op.getOpcode()) {
855   default: assert(0 && "Should not custom lower this!");
856   // Frame & Return address.  Currently unimplemented
857   case ISD::RETURNADDR: return SDOperand();
858   case ISD::FRAMEADDR:  return SDOperand();
859   case ISD::GlobalTLSAddress:
860     assert(0 && "TLS not implemented for Sparc.");
861   case ISD::GlobalAddress:      return LowerGLOBALADDRESS(Op, DAG);
862   case ISD::ConstantPool:       return LowerCONSTANTPOOL(Op, DAG);
863   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
864   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
865   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
866   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
867   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
868   case ISD::VAARG:              return LowerVAARG(Op, DAG);
869   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
870   case ISD::RET:                return LowerRET(Op, DAG);
871   }
872 }
873
874 MachineBasicBlock *
875 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
876                                                  MachineBasicBlock *BB) {
877   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
878   unsigned BROpcode;
879   unsigned CC;
880   // Figure out the conditional branch opcode to use for this select_cc.
881   switch (MI->getOpcode()) {
882   default: assert(0 && "Unknown SELECT_CC!");
883   case SP::SELECT_CC_Int_ICC:
884   case SP::SELECT_CC_FP_ICC:
885   case SP::SELECT_CC_DFP_ICC:
886     BROpcode = SP::BCOND;
887     break;
888   case SP::SELECT_CC_Int_FCC:
889   case SP::SELECT_CC_FP_FCC:
890   case SP::SELECT_CC_DFP_FCC:
891     BROpcode = SP::FBCOND;
892     break;
893   }
894
895   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
896   
897   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
898   // control-flow pattern.  The incoming instruction knows the destination vreg
899   // to set, the condition code register to branch on, the true/false values to
900   // select between, and a branch opcode to use.
901   const BasicBlock *LLVM_BB = BB->getBasicBlock();
902   ilist<MachineBasicBlock>::iterator It = BB;
903   ++It;
904   
905   //  thisMBB:
906   //  ...
907   //   TrueVal = ...
908   //   [f]bCC copy1MBB
909   //   fallthrough --> copy0MBB
910   MachineBasicBlock *thisMBB = BB;
911   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
912   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
913   BuildMI(BB, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
914   MachineFunction *F = BB->getParent();
915   F->getBasicBlockList().insert(It, copy0MBB);
916   F->getBasicBlockList().insert(It, sinkMBB);
917   // Update machine-CFG edges by first adding all successors of the current
918   // block to the new block which will contain the Phi node for the select.
919   for(MachineBasicBlock::succ_iterator i = BB->succ_begin(), 
920       e = BB->succ_end(); i != e; ++i)
921     sinkMBB->addSuccessor(*i);
922   // Next, remove all successors of the current block, and add the true
923   // and fallthrough blocks as its successors.
924   while(!BB->succ_empty())
925     BB->removeSuccessor(BB->succ_begin());
926   BB->addSuccessor(copy0MBB);
927   BB->addSuccessor(sinkMBB);
928   
929   //  copy0MBB:
930   //   %FalseValue = ...
931   //   # fallthrough to sinkMBB
932   BB = copy0MBB;
933   
934   // Update machine-CFG edges
935   BB->addSuccessor(sinkMBB);
936   
937   //  sinkMBB:
938   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
939   //  ...
940   BB = sinkMBB;
941   BuildMI(BB, TII.get(SP::PHI), MI->getOperand(0).getReg())
942     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
943     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
944   
945   delete MI;   // The pseudo instruction is gone now.
946   return BB;
947 }
948