#include Intrinsics.h into all dag isels
[oota-llvm.git] / lib / Target / Sparc / SparcISelDAGToDAG.cpp
1 //===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===//
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 an instruction selector for the SPARC target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sparc.h"
15 #include "SparcTargetMachine.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Support/Debug.h"
27 #include <iostream>
28 #include <set>
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 // TargetLowering Implementation
33 //===----------------------------------------------------------------------===//
34
35 namespace SPISD {
36   enum {
37     FIRST_NUMBER = ISD::BUILTIN_OP_END+SP::INSTRUCTION_LIST_END,
38     CMPICC,      // Compare two GPR operands, set icc.
39     CMPFCC,      // Compare two FP operands, set fcc.
40     BRICC,       // Branch to dest on icc condition
41     BRFCC,       // Branch to dest on fcc condition
42     SELECT_ICC,  // Select between two values using the current ICC flags.
43     SELECT_FCC,  // Select between two values using the current FCC flags.
44     
45     Hi, Lo,      // Hi/Lo operations, typically on a global address.
46     
47     FTOI,        // FP to Int within a FP register.
48     ITOF,        // Int to FP within a FP register.
49
50     CALL,        // A call instruction.
51     RET_FLAG,    // Return with a flag operand.
52   };
53 }
54
55 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
56 /// condition.
57 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
58   switch (CC) {
59   default: assert(0 && "Unknown integer condition code!");
60   case ISD::SETEQ:  return SPCC::ICC_E;
61   case ISD::SETNE:  return SPCC::ICC_NE;
62   case ISD::SETLT:  return SPCC::ICC_L;
63   case ISD::SETGT:  return SPCC::ICC_G;
64   case ISD::SETLE:  return SPCC::ICC_LE;
65   case ISD::SETGE:  return SPCC::ICC_GE;
66   case ISD::SETULT: return SPCC::ICC_CS;
67   case ISD::SETULE: return SPCC::ICC_LEU;
68   case ISD::SETUGT: return SPCC::ICC_GU;
69   case ISD::SETUGE: return SPCC::ICC_CC;
70   }
71 }
72
73 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
74 /// FCC condition.
75 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
76   switch (CC) {
77   default: assert(0 && "Unknown fp condition code!");
78   case ISD::SETEQ:  return SPCC::FCC_E;
79   case ISD::SETNE:  return SPCC::FCC_NE;
80   case ISD::SETLT:  return SPCC::FCC_L;
81   case ISD::SETGT:  return SPCC::FCC_G;
82   case ISD::SETLE:  return SPCC::FCC_LE;
83   case ISD::SETGE:  return SPCC::FCC_GE;
84   case ISD::SETULT: return SPCC::FCC_UL;
85   case ISD::SETULE: return SPCC::FCC_ULE;
86   case ISD::SETUGT: return SPCC::FCC_UG;
87   case ISD::SETUGE: return SPCC::FCC_UGE;
88   case ISD::SETUO:  return SPCC::FCC_U;
89   case ISD::SETO:   return SPCC::FCC_O;
90   case ISD::SETONE: return SPCC::FCC_LG;
91   case ISD::SETUEQ: return SPCC::FCC_UE;
92   }
93 }
94
95 namespace {
96   class SparcTargetLowering : public TargetLowering {
97     int VarArgsFrameOffset;   // Frame offset to start of varargs area.
98   public:
99     SparcTargetLowering(TargetMachine &TM);
100     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
101     
102     /// computeMaskedBitsForTargetNode - Determine which of the bits specified 
103     /// in Mask are known to be either zero or one and return them in the 
104     /// KnownZero/KnownOne bitsets.
105     virtual void computeMaskedBitsForTargetNode(const SDOperand Op,
106                                                 uint64_t Mask,
107                                                 uint64_t &KnownZero, 
108                                                 uint64_t &KnownOne,
109                                                 unsigned Depth = 0) const;
110     
111     virtual std::vector<SDOperand>
112       LowerArguments(Function &F, SelectionDAG &DAG);
113     virtual std::pair<SDOperand, SDOperand>
114       LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
115                   unsigned CC,
116                   bool isTailCall, SDOperand Callee, ArgListTy &Args,
117                   SelectionDAG &DAG);
118     virtual MachineBasicBlock *InsertAtEndOfBasicBlock(MachineInstr *MI,
119                                                        MachineBasicBlock *MBB);
120     
121     virtual const char *getTargetNodeName(unsigned Opcode) const;
122   };
123 }
124
125 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
126   : TargetLowering(TM) {
127   
128   // Set up the register classes.
129   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
130   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
131   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
132
133   // Custom legalize GlobalAddress nodes into LO/HI parts.
134   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
135   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
136   
137   // Sparc doesn't have sext_inreg, replace them with shl/sra
138   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
139   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
140   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
141
142   // Sparc has no REM operation.
143   setOperationAction(ISD::UREM, MVT::i32, Expand);
144   setOperationAction(ISD::SREM, MVT::i32, Expand);
145
146   // Custom expand fp<->sint
147   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
148   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
149
150   // Expand fp<->uint
151   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
152   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
153   
154   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
155   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
156   
157   // Turn FP extload into load/fextend
158   setOperationAction(ISD::EXTLOAD, MVT::f32, Expand);
159   
160   // Sparc has no select or setcc: expand to SELECT_CC.
161   setOperationAction(ISD::SELECT, MVT::i32, Expand);
162   setOperationAction(ISD::SELECT, MVT::f32, Expand);
163   setOperationAction(ISD::SELECT, MVT::f64, Expand);
164   setOperationAction(ISD::SETCC, MVT::i32, Expand);
165   setOperationAction(ISD::SETCC, MVT::f32, Expand);
166   setOperationAction(ISD::SETCC, MVT::f64, Expand);
167   
168   // Sparc doesn't have BRCOND either, it has BR_CC.
169   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
170   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
171   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
172   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
173   
174   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
175   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
176   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
177   
178   // SPARC has no intrinsics for these particular operations.
179   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
180   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
181   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
182   
183   setOperationAction(ISD::FSIN , MVT::f64, Expand);
184   setOperationAction(ISD::FCOS , MVT::f64, Expand);
185   setOperationAction(ISD::FSIN , MVT::f32, Expand);
186   setOperationAction(ISD::FCOS , MVT::f32, Expand);
187   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
188   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
189   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
190   setOperationAction(ISD::ROTL , MVT::i32, Expand);
191   setOperationAction(ISD::ROTR , MVT::i32, Expand);
192   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
193   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
194   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
195
196   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
197   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
198   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
199
200   // We don't have line number support yet.
201   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
202   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
203   setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
204
205   // RET must be custom lowered, to meet ABI requirements
206   setOperationAction(ISD::RET               , MVT::Other, Custom);
207   
208   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
209   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
210   // VAARG needs to be lowered to not do unaligned accesses for doubles.
211   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
212   
213   // Use the default implementation.
214   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
215   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
216   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
217   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
218   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
219
220   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
221   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
222   
223   setStackPointerRegisterToSaveRestore(SP::O6);
224
225   if (TM.getSubtarget<SparcSubtarget>().isV9()) {
226     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
227   }
228   
229   computeRegisterProperties();
230 }
231
232 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
233   switch (Opcode) {
234   default: return 0;
235   case SPISD::CMPICC:     return "SPISD::CMPICC";
236   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
237   case SPISD::BRICC:      return "SPISD::BRICC";
238   case SPISD::BRFCC:      return "SPISD::BRFCC";
239   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
240   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
241   case SPISD::Hi:         return "SPISD::Hi";
242   case SPISD::Lo:         return "SPISD::Lo";
243   case SPISD::FTOI:       return "SPISD::FTOI";
244   case SPISD::ITOF:       return "SPISD::ITOF";
245   case SPISD::CALL:       return "SPISD::CALL";
246   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
247   }
248 }
249
250 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
251 /// be zero. Op is expected to be a target specific node. Used by DAG
252 /// combiner.
253 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
254                                                          uint64_t Mask,
255                                                          uint64_t &KnownZero, 
256                                                          uint64_t &KnownOne,
257                                                          unsigned Depth) const {
258   uint64_t KnownZero2, KnownOne2;
259   KnownZero = KnownOne = 0;   // Don't know anything.
260   
261   switch (Op.getOpcode()) {
262   default: break;
263   case SPISD::SELECT_ICC:
264   case SPISD::SELECT_FCC:
265     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
266     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
267     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
268     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
269     
270     // Only known if known in both the LHS and RHS.
271     KnownOne &= KnownOne2;
272     KnownZero &= KnownZero2;
273     break;
274   }
275 }
276
277 /// LowerArguments - V8 uses a very simple ABI, where all values are passed in
278 /// either one or two GPRs, including FP values.  TODO: we should pass FP values
279 /// in FP registers for fastcc functions.
280 std::vector<SDOperand>
281 SparcTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
282   MachineFunction &MF = DAG.getMachineFunction();
283   SSARegMap *RegMap = MF.getSSARegMap();
284   std::vector<SDOperand> ArgValues;
285   
286   static const unsigned ArgRegs[] = {
287     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
288   };
289   
290   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
291   unsigned ArgOffset = 68;
292   
293   SDOperand Root = DAG.getRoot();
294   std::vector<SDOperand> OutChains;
295
296   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
297     MVT::ValueType ObjectVT = getValueType(I->getType());
298     
299     switch (ObjectVT) {
300     default: assert(0 && "Unhandled argument type!");
301     case MVT::i1:
302     case MVT::i8:
303     case MVT::i16:
304     case MVT::i32:
305       if (I->use_empty()) {                // Argument is dead.
306         if (CurArgReg < ArgRegEnd) ++CurArgReg;
307         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
308       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
309         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
310         MF.addLiveIn(*CurArgReg++, VReg);
311         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
312         if (ObjectVT != MVT::i32) {
313           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
314                                                        : ISD::AssertZext;
315           Arg = DAG.getNode(AssertOp, MVT::i32, Arg, 
316                             DAG.getValueType(ObjectVT));
317           Arg = DAG.getNode(ISD::TRUNCATE, ObjectVT, Arg);
318         }
319         ArgValues.push_back(Arg);
320       } else {
321         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
322         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
323         SDOperand Load;
324         if (ObjectVT == MVT::i32) {
325           Load = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
326         } else {
327           unsigned LoadOp =
328             I->getType()->isSigned() ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
329
330           // Sparc is big endian, so add an offset based on the ObjectVT.
331           unsigned Offset = 4-std::max(1U, MVT::getSizeInBits(ObjectVT)/8);
332           FIPtr = DAG.getNode(ISD::ADD, MVT::i32, FIPtr,
333                               DAG.getConstant(Offset, MVT::i32));
334           Load = DAG.getExtLoad(LoadOp, MVT::i32, Root, FIPtr,
335                                 DAG.getSrcValue(0), ObjectVT);
336           Load = DAG.getNode(ISD::TRUNCATE, ObjectVT, Load);
337         }
338         ArgValues.push_back(Load);
339       }
340       
341       ArgOffset += 4;
342       break;
343     case MVT::f32:
344       if (I->use_empty()) {                // Argument is dead.
345         if (CurArgReg < ArgRegEnd) ++CurArgReg;
346         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
347       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
348         // FP value is passed in an integer register.
349         unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
350         MF.addLiveIn(*CurArgReg++, VReg);
351         SDOperand Arg = DAG.getCopyFromReg(Root, VReg, MVT::i32);
352
353         Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Arg);
354         ArgValues.push_back(Arg);
355       } else {
356         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
357         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
358         SDOperand Load = DAG.getLoad(MVT::f32, Root, FIPtr, DAG.getSrcValue(0));
359         ArgValues.push_back(Load);
360       }
361       ArgOffset += 4;
362       break;
363
364     case MVT::i64:
365     case MVT::f64:
366       if (I->use_empty()) {                // Argument is dead.
367         if (CurArgReg < ArgRegEnd) ++CurArgReg;
368         if (CurArgReg < ArgRegEnd) ++CurArgReg;
369         ArgValues.push_back(DAG.getNode(ISD::UNDEF, ObjectVT));
370       } else if (/* FIXME: Apparently this isn't safe?? */
371                  0 && CurArgReg == ArgRegEnd && ObjectVT == MVT::f64 &&
372                  ((CurArgReg-ArgRegs) & 1) == 0) {
373         // If this is a double argument and the whole thing lives on the stack,
374         // and the argument is aligned, load the double straight from the stack.
375         // We can't do a load in cases like void foo([6ints], int,double),
376         // because the double wouldn't be aligned!
377         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(8, ArgOffset);
378         SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
379         ArgValues.push_back(DAG.getLoad(MVT::f64, Root, FIPtr, 
380                                         DAG.getSrcValue(0)));
381       } else {
382         SDOperand HiVal;
383         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
384           unsigned VRegHi = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
385           MF.addLiveIn(*CurArgReg++, VRegHi);
386           HiVal = DAG.getCopyFromReg(Root, VRegHi, MVT::i32);
387         } else {
388           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
389           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
390           HiVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
391         }
392         
393         SDOperand LoVal;
394         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
395           unsigned VRegLo = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
396           MF.addLiveIn(*CurArgReg++, VRegLo);
397           LoVal = DAG.getCopyFromReg(Root, VRegLo, MVT::i32);
398         } else {
399           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4);
400           SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
401           LoVal = DAG.getLoad(MVT::i32, Root, FIPtr, DAG.getSrcValue(0));
402         }
403         
404         // Compose the two halves together into an i64 unit.
405         SDOperand WholeValue = 
406           DAG.getNode(ISD::BUILD_PAIR, MVT::i64, LoVal, HiVal);
407         
408         // If we want a double, do a bit convert.
409         if (ObjectVT == MVT::f64)
410           WholeValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, WholeValue);
411         
412         ArgValues.push_back(WholeValue);
413       }
414       ArgOffset += 8;
415       break;
416     }
417   }
418   
419   // Store remaining ArgRegs to the stack if this is a varargs function.
420   if (F.getFunctionType()->isVarArg()) {
421     // Remember the vararg offset for the va_start implementation.
422     VarArgsFrameOffset = ArgOffset;
423     
424     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
425       unsigned VReg = RegMap->createVirtualRegister(&SP::IntRegsRegClass);
426       MF.addLiveIn(*CurArgReg, VReg);
427       SDOperand Arg = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
428
429       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset);
430       SDOperand FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
431
432       OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getRoot(),
433                                       Arg, FIPtr, DAG.getSrcValue(0)));
434       ArgOffset += 4;
435     }
436   }
437   
438   if (!OutChains.empty())
439     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
440   
441   // Finally, inform the code generator which regs we return values in.
442   switch (getValueType(F.getReturnType())) {
443   default: assert(0 && "Unknown type!");
444   case MVT::isVoid: break;
445   case MVT::i1:
446   case MVT::i8:
447   case MVT::i16:
448   case MVT::i32:
449     MF.addLiveOut(SP::I0);
450     break;
451   case MVT::i64:
452     MF.addLiveOut(SP::I0);
453     MF.addLiveOut(SP::I1);
454     break;
455   case MVT::f32:
456     MF.addLiveOut(SP::F0);
457     break;
458   case MVT::f64:
459     MF.addLiveOut(SP::D0);
460     break;
461   }
462   
463   return ArgValues;
464 }
465
466 std::pair<SDOperand, SDOperand>
467 SparcTargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
468                                  bool isVarArg, unsigned CC,
469                                  bool isTailCall, SDOperand Callee, 
470                                  ArgListTy &Args, SelectionDAG &DAG) {
471   MachineFunction &MF = DAG.getMachineFunction();
472   // Count the size of the outgoing arguments.
473   unsigned ArgsSize = 0;
474   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
475     switch (getValueType(Args[i].second)) {
476     default: assert(0 && "Unknown value type!");
477     case MVT::i1:
478     case MVT::i8:
479     case MVT::i16:
480     case MVT::i32:
481     case MVT::f32:
482       ArgsSize += 4;
483       break;
484     case MVT::i64:
485     case MVT::f64:
486       ArgsSize += 8;
487       break;
488     }
489   }
490   if (ArgsSize > 4*6)
491     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
492   else
493     ArgsSize = 0;
494
495   // Keep stack frames 8-byte aligned.
496   ArgsSize = (ArgsSize+7) & ~7;
497
498   Chain = DAG.getCALLSEQ_START(Chain,DAG.getConstant(ArgsSize, getPointerTy()));
499   
500   SDOperand StackPtr, NullSV;
501   std::vector<SDOperand> Stores;
502   std::vector<SDOperand> RegValuesToPass;
503   unsigned ArgOffset = 68;
504   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
505     SDOperand Val = Args[i].first;
506     MVT::ValueType ObjectVT = Val.getValueType();
507     SDOperand ValToStore(0, 0);
508     unsigned ObjSize;
509     switch (ObjectVT) {
510     default: assert(0 && "Unhandled argument type!");
511     case MVT::i1:
512     case MVT::i8:
513     case MVT::i16:
514       // Promote the integer to 32-bits.  If the input type is signed, use a
515       // sign extend, otherwise use a zero extend.
516       if (Args[i].second->isSigned())
517         Val = DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Val);
518       else
519         Val = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Val);
520       // FALL THROUGH
521     case MVT::i32:
522       ObjSize = 4;
523
524       if (RegValuesToPass.size() >= 6) {
525         ValToStore = Val;
526       } else {
527         RegValuesToPass.push_back(Val);
528       }
529       break;
530     case MVT::f32:
531       ObjSize = 4;
532       if (RegValuesToPass.size() >= 6) {
533         ValToStore = Val;
534       } else {
535         // Convert this to a FP value in an int reg.
536         Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Val);
537         RegValuesToPass.push_back(Val);
538       }
539       break;
540     case MVT::f64:
541       ObjSize = 8;
542       // If we can store this directly into the outgoing slot, do so.  We can
543       // do this when all ArgRegs are used and if the outgoing slot is aligned.
544       // FIXME: McGill/misr fails with this.
545       if (0 && RegValuesToPass.size() >= 6 && ((ArgOffset-68) & 7) == 0) {
546         ValToStore = Val;
547         break;
548       }
549       
550       // Otherwise, convert this to a FP value in int regs.
551       Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Val);
552       // FALL THROUGH
553     case MVT::i64:
554       ObjSize = 8;
555       if (RegValuesToPass.size() >= 6) {
556         ValToStore = Val;    // Whole thing is passed in memory.
557         break;
558       }
559       
560       // Split the value into top and bottom part.  Top part goes in a reg.
561       SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val, 
562                                  DAG.getConstant(1, MVT::i32));
563       SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Val,
564                                  DAG.getConstant(0, MVT::i32));
565       RegValuesToPass.push_back(Hi);
566       
567       if (RegValuesToPass.size() >= 6) {
568         ValToStore = Lo;
569         ArgOffset += 4;
570         ObjSize = 4;
571       } else {
572         RegValuesToPass.push_back(Lo);
573       }
574       break;
575     }
576     
577     if (ValToStore.Val) {
578       if (!StackPtr.Val) {
579         StackPtr = DAG.getRegister(SP::O6, MVT::i32);
580         NullSV = DAG.getSrcValue(NULL);
581       }
582       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
583       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
584       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
585                                    ValToStore, PtrOff, NullSV));
586     }
587     ArgOffset += ObjSize;
588   }
589   
590   // Emit all stores, make sure the occur before any copies into physregs.
591   if (!Stores.empty())
592     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
593   
594   static const unsigned ArgRegs[] = {
595     SP::O0, SP::O1, SP::O2, SP::O3, SP::O4, SP::O5
596   };
597   
598   // Build a sequence of copy-to-reg nodes chained together with token chain
599   // and flag operands which copy the outgoing args into O[0-5].
600   SDOperand InFlag;
601   for (unsigned i = 0, e = RegValuesToPass.size(); i != e; ++i) {
602     Chain = DAG.getCopyToReg(Chain, ArgRegs[i], RegValuesToPass[i], InFlag);
603     InFlag = Chain.getValue(1);
604   }
605
606   // If the callee is a GlobalAddress node (quite common, every direct call is)
607   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
608   // Likewise ExternalSymbol -> TargetExternalSymbol.
609   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
610     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
611   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
612     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
613
614   std::vector<MVT::ValueType> NodeTys;
615   NodeTys.push_back(MVT::Other);   // Returns a chain
616   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
617   std::vector<SDOperand> Ops;
618   Ops.push_back(Chain);
619   Ops.push_back(Callee);
620   if (InFlag.Val)
621     Ops.push_back(InFlag);
622   Chain = DAG.getNode(SPISD::CALL, NodeTys, Ops);
623   InFlag = Chain.getValue(1);
624   
625   MVT::ValueType RetTyVT = getValueType(RetTy);
626   SDOperand RetVal;
627   if (RetTyVT != MVT::isVoid) {
628     switch (RetTyVT) {
629     default: assert(0 && "Unknown value type to return!");
630     case MVT::i1:
631     case MVT::i8:
632     case MVT::i16:
633       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
634       Chain = RetVal.getValue(1);
635       
636       // Add a note to keep track of whether it is sign or zero extended.
637       RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext :ISD::AssertZext,
638                            MVT::i32, RetVal, DAG.getValueType(RetTyVT));
639       RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
640       break;
641     case MVT::i32:
642       RetVal = DAG.getCopyFromReg(Chain, SP::O0, MVT::i32, InFlag);
643       Chain = RetVal.getValue(1);
644       break;
645     case MVT::f32:
646       RetVal = DAG.getCopyFromReg(Chain, SP::F0, MVT::f32, InFlag);
647       Chain = RetVal.getValue(1);
648       break;
649     case MVT::f64:
650       RetVal = DAG.getCopyFromReg(Chain, SP::D0, MVT::f64, InFlag);
651       Chain = RetVal.getValue(1);
652       break;
653     case MVT::i64:
654       SDOperand Lo = DAG.getCopyFromReg(Chain, SP::O1, MVT::i32, InFlag);
655       SDOperand Hi = DAG.getCopyFromReg(Lo.getValue(1), SP::O0, MVT::i32, 
656                                         Lo.getValue(2));
657       RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi);
658       Chain = Hi.getValue(1);
659       break;
660     }
661   }
662   
663   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
664                       DAG.getConstant(ArgsSize, getPointerTy()));
665   
666   return std::make_pair(RetVal, Chain);
667 }
668
669 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
670 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
671 static void LookThroughSetCC(SDOperand &LHS, SDOperand &RHS,
672                              ISD::CondCode CC, unsigned &SPCC) {
673   if (isa<ConstantSDNode>(RHS) && cast<ConstantSDNode>(RHS)->getValue() == 0 &&
674       CC == ISD::SETNE && 
675       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
676         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
677        (LHS.getOpcode() == SPISD::SELECT_FCC &&
678         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
679       isa<ConstantSDNode>(LHS.getOperand(0)) &&
680       isa<ConstantSDNode>(LHS.getOperand(1)) &&
681       cast<ConstantSDNode>(LHS.getOperand(0))->getValue() == 1 &&
682       cast<ConstantSDNode>(LHS.getOperand(1))->getValue() == 0) {
683     SDOperand CMPCC = LHS.getOperand(3);
684     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getValue();
685     LHS = CMPCC.getOperand(0);
686     RHS = CMPCC.getOperand(1);
687   }
688 }
689
690
691 SDOperand SparcTargetLowering::
692 LowerOperation(SDOperand Op, SelectionDAG &DAG) {
693   switch (Op.getOpcode()) {
694   default: assert(0 && "Should not custom lower this!");
695   case ISD::GlobalAddress: {
696     GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
697     SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32);
698     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, GA);
699     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, GA);
700     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
701   }
702   case ISD::ConstantPool: {
703     Constant *C = cast<ConstantPoolSDNode>(Op)->get();
704     SDOperand CP = DAG.getTargetConstantPool(C, MVT::i32,
705                                   cast<ConstantPoolSDNode>(Op)->getAlignment());
706     SDOperand Hi = DAG.getNode(SPISD::Hi, MVT::i32, CP);
707     SDOperand Lo = DAG.getNode(SPISD::Lo, MVT::i32, CP);
708     return DAG.getNode(ISD::ADD, MVT::i32, Lo, Hi);
709   }
710   case ISD::FP_TO_SINT:
711     // Convert the fp value to integer in an FP register.
712     assert(Op.getValueType() == MVT::i32);
713     Op = DAG.getNode(SPISD::FTOI, MVT::f32, Op.getOperand(0));
714     return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
715   case ISD::SINT_TO_FP: {
716     assert(Op.getOperand(0).getValueType() == MVT::i32);
717     SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
718     // Convert the int value to FP in an FP register.
719     return DAG.getNode(SPISD::ITOF, Op.getValueType(), Tmp);
720   }
721   case ISD::BR_CC: {
722     SDOperand Chain = Op.getOperand(0);
723     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
724     SDOperand LHS = Op.getOperand(2);
725     SDOperand RHS = Op.getOperand(3);
726     SDOperand Dest = Op.getOperand(4);
727     unsigned Opc, SPCC = ~0U;
728     
729     // If this is a br_cc of a "setcc", and if the setcc got lowered into
730     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
731     LookThroughSetCC(LHS, RHS, CC, SPCC);
732     
733     // Get the condition flag.
734     SDOperand CompareFlag;
735     if (LHS.getValueType() == MVT::i32) {
736       std::vector<MVT::ValueType> VTs;
737       VTs.push_back(MVT::i32);
738       VTs.push_back(MVT::Flag);
739       std::vector<SDOperand> Ops;
740       Ops.push_back(LHS);
741       Ops.push_back(RHS);
742       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
743       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
744       Opc = SPISD::BRICC;
745     } else {
746       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
747       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
748       Opc = SPISD::BRFCC;
749     }
750     return DAG.getNode(Opc, MVT::Other, Chain, Dest,
751                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
752   }
753   case ISD::SELECT_CC: {
754     SDOperand LHS = Op.getOperand(0);
755     SDOperand RHS = Op.getOperand(1);
756     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
757     SDOperand TrueVal = Op.getOperand(2);
758     SDOperand FalseVal = Op.getOperand(3);
759     unsigned Opc, SPCC = ~0U;
760
761     // If this is a select_cc of a "setcc", and if the setcc got lowered into
762     // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
763     LookThroughSetCC(LHS, RHS, CC, SPCC);
764     
765     SDOperand CompareFlag;
766     if (LHS.getValueType() == MVT::i32) {
767       std::vector<MVT::ValueType> VTs;
768       VTs.push_back(LHS.getValueType());   // subcc returns a value
769       VTs.push_back(MVT::Flag);
770       std::vector<SDOperand> Ops;
771       Ops.push_back(LHS);
772       Ops.push_back(RHS);
773       CompareFlag = DAG.getNode(SPISD::CMPICC, VTs, Ops).getValue(1);
774       Opc = SPISD::SELECT_ICC;
775       if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
776     } else {
777       CompareFlag = DAG.getNode(SPISD::CMPFCC, MVT::Flag, LHS, RHS);
778       Opc = SPISD::SELECT_FCC;
779       if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
780     }
781     return DAG.getNode(Opc, TrueVal.getValueType(), TrueVal, FalseVal, 
782                        DAG.getConstant(SPCC, MVT::i32), CompareFlag);
783   }
784   case ISD::VASTART: {
785     // vastart just stores the address of the VarArgsFrameIndex slot into the
786     // memory location argument.
787     SDOperand Offset = DAG.getNode(ISD::ADD, MVT::i32,
788                                    DAG.getRegister(SP::I6, MVT::i32),
789                                 DAG.getConstant(VarArgsFrameOffset, MVT::i32));
790     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), Offset, 
791                        Op.getOperand(1), Op.getOperand(2));
792   }
793   case ISD::VAARG: {
794     SDNode *Node = Op.Val;
795     MVT::ValueType VT = Node->getValueType(0);
796     SDOperand InChain = Node->getOperand(0);
797     SDOperand VAListPtr = Node->getOperand(1);
798     SDOperand VAList = DAG.getLoad(getPointerTy(), InChain, VAListPtr,
799                                    Node->getOperand(2));
800     // Increment the pointer, VAList, to the next vaarg
801     SDOperand NextPtr = DAG.getNode(ISD::ADD, getPointerTy(), VAList, 
802                                     DAG.getConstant(MVT::getSizeInBits(VT)/8, 
803                                                     getPointerTy()));
804     // Store the incremented VAList to the legalized pointer
805     InChain = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), NextPtr,
806                           VAListPtr, Node->getOperand(2));
807     // Load the actual argument out of the pointer VAList, unless this is an
808     // f64 load.
809     if (VT != MVT::f64) {
810       return DAG.getLoad(VT, InChain, VAList, DAG.getSrcValue(0));
811     } else {
812       // Otherwise, load it as i64, then do a bitconvert.
813       SDOperand V = DAG.getLoad(MVT::i64, InChain, VAList, DAG.getSrcValue(0));
814       std::vector<MVT::ValueType> Tys;
815       Tys.push_back(MVT::f64);
816       Tys.push_back(MVT::Other);
817       std::vector<SDOperand> Ops;
818       // Bit-Convert the value to f64.
819       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f64, V));
820       Ops.push_back(V.getValue(1));
821       return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
822     }
823   }
824   case ISD::DYNAMIC_STACKALLOC: {
825     SDOperand Chain = Op.getOperand(0);  // Legalize the chain.
826     SDOperand Size  = Op.getOperand(1);  // Legalize the size.
827     
828     unsigned SPReg = SP::O6;
829     SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, MVT::i32);
830     SDOperand NewSP = DAG.getNode(ISD::SUB, MVT::i32, SP, Size);    // Value
831     Chain = DAG.getCopyToReg(SP.getValue(1), SPReg, NewSP);      // Output chain
832
833     // The resultant pointer is actually 16 words from the bottom of the stack,
834     // to provide a register spill area.
835     SDOperand NewVal = DAG.getNode(ISD::ADD, MVT::i32, NewSP,
836                                    DAG.getConstant(96, MVT::i32));
837     std::vector<MVT::ValueType> Tys;
838     Tys.push_back(MVT::i32);
839     Tys.push_back(MVT::Other);
840     std::vector<SDOperand> Ops;
841     Ops.push_back(NewVal);
842     Ops.push_back(Chain);
843     return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops);
844   }
845   case ISD::RET: {
846     SDOperand Copy;
847     
848     switch(Op.getNumOperands()) {
849     default:
850       assert(0 && "Do not know how to return this many arguments!");
851       abort();
852     case 1: 
853       return SDOperand(); // ret void is legal
854     case 2: {
855       unsigned ArgReg;
856       switch(Op.getOperand(1).getValueType()) {
857       default: assert(0 && "Unknown type to return!");
858       case MVT::i32: ArgReg = SP::I0; break;
859       case MVT::f32: ArgReg = SP::F0; break;
860       case MVT::f64: ArgReg = SP::D0; break;
861       }
862       Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
863                               SDOperand());
864       break;
865     }
866     case 3:
867       Copy = DAG.getCopyToReg(Op.getOperand(0), SP::I0, Op.getOperand(2), 
868                               SDOperand());
869       Copy = DAG.getCopyToReg(Copy, SP::I1, Op.getOperand(1), Copy.getValue(1));
870       break;
871     }
872     return DAG.getNode(SPISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
873   }
874   }
875 }
876
877 MachineBasicBlock *
878 SparcTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
879                                              MachineBasicBlock *BB) {
880   unsigned BROpcode;
881   unsigned CC;
882   // Figure out the conditional branch opcode to use for this select_cc.
883   switch (MI->getOpcode()) {
884   default: assert(0 && "Unknown SELECT_CC!");
885   case SP::SELECT_CC_Int_ICC:
886   case SP::SELECT_CC_FP_ICC:
887   case SP::SELECT_CC_DFP_ICC:
888     BROpcode = SP::BCOND;
889     break;
890   case SP::SELECT_CC_Int_FCC:
891   case SP::SELECT_CC_FP_FCC:
892   case SP::SELECT_CC_DFP_FCC:
893     BROpcode = SP::FBCOND;
894     break;
895   }
896
897   CC = (SPCC::CondCodes)MI->getOperand(3).getImmedValue();
898   
899   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
900   // control-flow pattern.  The incoming instruction knows the destination vreg
901   // to set, the condition code register to branch on, the true/false values to
902   // select between, and a branch opcode to use.
903   const BasicBlock *LLVM_BB = BB->getBasicBlock();
904   ilist<MachineBasicBlock>::iterator It = BB;
905   ++It;
906   
907   //  thisMBB:
908   //  ...
909   //   TrueVal = ...
910   //   [f]bCC copy1MBB
911   //   fallthrough --> copy0MBB
912   MachineBasicBlock *thisMBB = BB;
913   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
914   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
915   BuildMI(BB, BROpcode, 2).addMBB(sinkMBB).addImm(CC);
916   MachineFunction *F = BB->getParent();
917   F->getBasicBlockList().insert(It, copy0MBB);
918   F->getBasicBlockList().insert(It, sinkMBB);
919   // Update machine-CFG edges
920   BB->addSuccessor(copy0MBB);
921   BB->addSuccessor(sinkMBB);
922   
923   //  copy0MBB:
924   //   %FalseValue = ...
925   //   # fallthrough to sinkMBB
926   BB = copy0MBB;
927   
928   // Update machine-CFG edges
929   BB->addSuccessor(sinkMBB);
930   
931   //  sinkMBB:
932   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
933   //  ...
934   BB = sinkMBB;
935   BuildMI(BB, SP::PHI, 4, MI->getOperand(0).getReg())
936     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
937     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
938   
939   delete MI;   // The pseudo instruction is gone now.
940   return BB;
941 }
942   
943 //===----------------------------------------------------------------------===//
944 // Instruction Selector Implementation
945 //===----------------------------------------------------------------------===//
946
947 //===--------------------------------------------------------------------===//
948 /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine
949 /// instructions for SelectionDAG operations.
950 ///
951 namespace {
952 class SparcDAGToDAGISel : public SelectionDAGISel {
953   SparcTargetLowering Lowering;
954
955   /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can
956   /// make the right decision when generating code for different targets.
957   const SparcSubtarget &Subtarget;
958 public:
959   SparcDAGToDAGISel(TargetMachine &TM)
960     : SelectionDAGISel(Lowering), Lowering(TM),
961       Subtarget(TM.getSubtarget<SparcSubtarget>()) {
962   }
963
964   void Select(SDOperand &Result, SDOperand Op);
965
966   // Complex Pattern Selectors.
967   bool SelectADDRrr(SDOperand N, SDOperand &R1, SDOperand &R2);
968   bool SelectADDRri(SDOperand N, SDOperand &Base, SDOperand &Offset);
969   
970   /// InstructionSelectBasicBlock - This callback is invoked by
971   /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
972   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
973   
974   virtual const char *getPassName() const {
975     return "SPARC DAG->DAG Pattern Instruction Selection";
976   } 
977   
978   // Include the pieces autogenerated from the target description.
979 #include "SparcGenDAGISel.inc"
980 };
981 }  // end anonymous namespace
982
983 /// InstructionSelectBasicBlock - This callback is invoked by
984 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
985 void SparcDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
986   DEBUG(BB->dump());
987   
988   // Select target instructions for the DAG.
989   DAG.setRoot(SelectRoot(DAG.getRoot()));
990   CodeGenMap.clear();
991   DAG.RemoveDeadNodes();
992   
993   // Emit machine code to BB. 
994   ScheduleAndEmitDAG(DAG);
995 }
996
997 bool SparcDAGToDAGISel::SelectADDRri(SDOperand Addr, SDOperand &Base,
998                                      SDOperand &Offset) {
999   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1000     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1001     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1002     return true;
1003   }
1004   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1005       Addr.getOpcode() == ISD::TargetGlobalAddress)
1006     return false;  // direct calls.
1007   
1008   if (Addr.getOpcode() == ISD::ADD) {
1009     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
1010       if (Predicate_simm13(CN)) {
1011         if (FrameIndexSDNode *FIN = 
1012                 dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
1013           // Constant offset from frame ref.
1014           Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1015         } else {
1016           Base = Addr.getOperand(0);
1017         }
1018         Offset = CurDAG->getTargetConstant(CN->getValue(), MVT::i32);
1019         return true;
1020       }
1021     }
1022     if (Addr.getOperand(0).getOpcode() == SPISD::Lo) {
1023       Base = Addr.getOperand(1);
1024       Offset = Addr.getOperand(0).getOperand(0);
1025       return true;
1026     }
1027     if (Addr.getOperand(1).getOpcode() == SPISD::Lo) {
1028       Base = Addr.getOperand(0);
1029       Offset = Addr.getOperand(1).getOperand(0);
1030       return true;
1031     }
1032   }
1033   Base = Addr;
1034   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1035   return true;
1036 }
1037
1038 bool SparcDAGToDAGISel::SelectADDRrr(SDOperand Addr, SDOperand &R1, 
1039                                      SDOperand &R2) {
1040   if (Addr.getOpcode() == ISD::FrameIndex) return false;
1041   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1042       Addr.getOpcode() == ISD::TargetGlobalAddress)
1043     return false;  // direct calls.
1044   
1045   if (Addr.getOpcode() == ISD::ADD) {
1046     if (isa<ConstantSDNode>(Addr.getOperand(1)) &&
1047         Predicate_simm13(Addr.getOperand(1).Val))
1048       return false;  // Let the reg+imm pattern catch this!
1049     if (Addr.getOperand(0).getOpcode() == SPISD::Lo ||
1050         Addr.getOperand(1).getOpcode() == SPISD::Lo)
1051       return false;  // Let the reg+imm pattern catch this!
1052     R1 = Addr.getOperand(0);
1053     R2 = Addr.getOperand(1);
1054     return true;
1055   }
1056
1057   R1 = Addr;
1058   R2 = CurDAG->getRegister(SP::G0, MVT::i32);
1059   return true;
1060 }
1061
1062 void SparcDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
1063   SDNode *N = Op.Val;
1064   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
1065       N->getOpcode() < SPISD::FIRST_NUMBER) {
1066     Result = Op;
1067     return;   // Already selected.
1068   }
1069
1070                  // If this has already been converted, use it.
1071   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
1072   if (CGMI != CodeGenMap.end()) {
1073     Result = CGMI->second;
1074     return;
1075   }
1076   
1077   switch (N->getOpcode()) {
1078   default: break;
1079   case ISD::SDIV:
1080   case ISD::UDIV: {
1081     // FIXME: should use a custom expander to expose the SRA to the dag.
1082     SDOperand DivLHS, DivRHS;
1083     Select(DivLHS, N->getOperand(0));
1084     Select(DivRHS, N->getOperand(1));
1085     
1086     // Set the Y register to the high-part.
1087     SDOperand TopPart;
1088     if (N->getOpcode() == ISD::SDIV) {
1089       TopPart = SDOperand(CurDAG->getTargetNode(SP::SRAri, MVT::i32, DivLHS,
1090                                    CurDAG->getTargetConstant(31, MVT::i32)), 0);
1091     } else {
1092       TopPart = CurDAG->getRegister(SP::G0, MVT::i32);
1093     }
1094     TopPart = SDOperand(CurDAG->getTargetNode(SP::WRYrr, MVT::Flag, TopPart,
1095                                      CurDAG->getRegister(SP::G0, MVT::i32)), 0);
1096
1097     // FIXME: Handle div by immediate.
1098     unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr;
1099     Result = CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart);
1100     return;
1101   }    
1102   case ISD::MULHU:
1103   case ISD::MULHS: {
1104     // FIXME: Handle mul by immediate.
1105     SDOperand MulLHS, MulRHS;
1106     Select(MulLHS, N->getOperand(0));
1107     Select(MulRHS, N->getOperand(1));
1108     unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr;
1109     SDNode *Mul = CurDAG->getTargetNode(Opcode, MVT::i32, MVT::Flag,
1110                                         MulLHS, MulRHS);
1111     // The high part is in the Y register.
1112     Result = CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDOperand(Mul, 1));
1113     return;
1114   }
1115   }
1116   
1117   SelectCode(Result, Op);
1118 }
1119
1120
1121 /// createSparcISelDag - This pass converts a legalized DAG into a 
1122 /// SPARC-specific DAG, ready for instruction scheduling.
1123 ///
1124 FunctionPass *llvm::createSparcISelDag(TargetMachine &TM) {
1125   return new SparcDAGToDAGISel(TM);
1126 }