Added LLVM copyright header (for lack of a better term).
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9RegInfo.cpp
index dfb55176960ad07c8dbee5128227b7d842ba3b82..1a48d9cf20e22c95492ace2cf1b11192f6fa5dd5 100644 (file)
-#include "llvm/Target/Sparc.h"
+//===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
+// 
+//                     The LLVM Compiler Infrastructure
+//
+// This file was developed by the LLVM research group and is distributed under
+// the University of Illinois Open Source License. See LICENSE.TXT for details.
+// 
+//===----------------------------------------------------------------------===//
+//
+// This file contains implementation of Sparc specific helper methods
+// used for register allocation.
+//
+//===----------------------------------------------------------------------===//
+
 #include "SparcInternals.h"
-#include "llvm/Method.h"
+#include "SparcRegClassInfo.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionInfo.h"
+#include "llvm/CodeGen/InstrSelection.h"
+#include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineCodeForInstruction.h"
+#include "llvm/CodeGen/MachineInstrAnnot.h"
+#include "../../CodeGen/RegAlloc/LiveRangeInfo.h"   // FIXME!!
+#include "../../CodeGen/RegAlloc/LiveRange.h"       // FIXME!!
 #include "llvm/iTerminators.h"
 #include "llvm/iOther.h"
-#include "llvm/CodeGen/InstrScheduling.h"
-#include "llvm/CodeGen/InstrSelection.h"
-
-#include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
-#include "llvm/CodeGen/PhyRegAlloc.h"
+#include "llvm/Function.h"
+#include "llvm/DerivedTypes.h"
 
+enum {
+  BadRegClass = ~0
+};
 
+UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
+  : TargetRegInfo(tgt), NumOfIntArgRegs(6), NumOfFloatArgRegs(32)
+{
+  MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
+  MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
+  MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
+  MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
+  MachineRegClassArr.push_back(new SparcSpecialRegClass(SpecialRegClassID));
+  
+  assert(SparcFloatRegClass::StartOfNonVolatileRegs == 32 && 
+         "32 Float regs are used for float arg passing");
+}
 
 
-//---------------------------------------------------------------------------
-// UltraSparcRegInfo
-//---------------------------------------------------------------------------
+// getZeroRegNum - returns the register that contains always zero.
+// this is the unified register number
+//
+int UltraSparcRegInfo::getZeroRegNum() const {
+  return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                          SparcIntRegClass::g0);
+}
 
-//---------------------------------------------------------------------------
-// Finds the return value of a call instruction
-//---------------------------------------------------------------------------
+// getCallAddressReg - returns the reg used for pushing the address when a
+// method is called. This can be used for other purposes between calls
+//
+unsigned UltraSparcRegInfo::getCallAddressReg() const {
+  return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                          SparcIntRegClass::o7);
+}
 
-const Value * 
-UltraSparcRegInfo::getCallInstRetVal(const MachineInstr *CallMI) const{
+// Returns the register containing the return address.
+// It should be made sure that this  register contains the return 
+// value when a return instruction is reached.
+//
+unsigned UltraSparcRegInfo::getReturnAddressReg() const {
+  return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                          SparcIntRegClass::i7);
+}
 
-  unsigned OpCode = CallMI->getOpCode();
-  unsigned NumOfImpRefs =  CallMI->getNumImplicitRefs();
+// Register get name implementations...
+
+// Int register names in same order as enum in class SparcIntRegClass
+static const char * const IntRegNames[] = {
+  "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
+  "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
+  "i0", "i1", "i2", "i3", "i4", "i5",  
+  "i6", "i7",
+  "g0", "g1", "g2", "g3", "g4", "g5",  "g6", "g7", 
+  "o6"
+}; 
+
+const char * const SparcIntRegClass::getRegName(unsigned reg) const {
+  assert(reg < NumOfAllRegs);
+  return IntRegNames[reg];
+}
 
-  if( OpCode == CALL ) {
+static const char * const FloatRegNames[] = {    
+  "f0",  "f1",  "f2",  "f3",  "f4",  "f5",  "f6",  "f7",  "f8",  "f9", 
+  "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
+  "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29",
+  "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39",
+  "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49",
+  "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59",
+  "f60", "f61", "f62", "f63"
+};
+
+const char * const SparcFloatRegClass::getRegName(unsigned reg) const {
+  assert (reg < NumOfAllRegs);
+  return FloatRegNames[reg];
+}
 
-    // The one before the last implicit operand is the return value of 
-    // a CALL instr
-    if( NumOfImpRefs > 1 )
-      if(  CallMI->implicitRefIsDefined(NumOfImpRefs-2) ) 
-       return  CallMI->getImplicitRef(NumOfImpRefs-2); 
 
-  }
-  else if( OpCode == JMPLCALL) {
+static const char * const IntCCRegNames[] = {    
+  "xcc",  "icc",  "ccr"
+};
 
-    // The last implicit operand is the return value of a JMPL in   
-    if( NumOfImpRefs > 0 )
-      if(  CallMI->implicitRefIsDefined(NumOfImpRefs-1) ) 
-       return  CallMI->getImplicitRef(NumOfImpRefs-1); 
-  }
-  else
-    assert(0 && "OpCode must be CALL/JMPL for a call instr");
+const char * const SparcIntCCRegClass::getRegName(unsigned reg) const {
+  assert(reg < 3);
+  return IntCCRegNames[reg];
+}
 
-  return NULL;
+static const char * const FloatCCRegNames[] = {    
+  "fcc0", "fcc1",  "fcc2",  "fcc3"
+};
 
+const char * const SparcFloatCCRegClass::getRegName(unsigned reg) const {
+  assert (reg < 5);
+  return FloatCCRegNames[reg];
 }
 
-//---------------------------------------------------------------------------
-// Finds the return address of a call instruction
-//---------------------------------------------------------------------------
-
-const Value *
-UltraSparcRegInfo::getCallInstRetAddr(const MachineInstr *CallMI)const {
+static const char * const SpecialRegNames[] = {    
+  "fsr"
+};
 
-  unsigned OpCode = CallMI->getOpCode();
+const char * const SparcSpecialRegClass::getRegName(unsigned reg) const {
+  assert (reg < 1);
+  return SpecialRegNames[reg];
+}
 
-  if( OpCode == CALL) {
+// Get unified reg number for frame pointer
+unsigned UltraSparcRegInfo::getFramePointer() const {
+  return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                          SparcIntRegClass::i6);
+}
 
-    unsigned NumOfImpRefs =  CallMI->getNumImplicitRefs();
+// Get unified reg number for stack pointer
+unsigned UltraSparcRegInfo::getStackPointer() const {
+  return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                          SparcIntRegClass::o6);
+}
 
-    assert( NumOfImpRefs && "CALL instr must have at least on ImpRef");
-    // The last implicit operand is the return address of a CALL instr
-    return  CallMI->getImplicitRef(NumOfImpRefs-1); 
 
-  }
-  else if( OpCode == JMPLCALL ) {
+//---------------------------------------------------------------------------
+// Finds whether a call is an indirect call
+//---------------------------------------------------------------------------
 
-    MachineOperand & MO  = ( MachineOperand &) CallMI->getOperand(2);
-    return MO.getVRegValue();
+inline bool
+isVarArgsFunction(const Type *funcType) {
+  return cast<FunctionType>(cast<PointerType>(funcType)
+                            ->getElementType())->isVarArg();
+}
 
-  }
-  else
-    assert(0 && "OpCode must be CALL/JMPL for a call instr");
+inline bool
+isVarArgsCall(const MachineInstr *CallMI) {
+  Value* callee = CallMI->getOperand(0).getVRegValue();
+  // const Type* funcType = isa<Function>(callee)? callee->getType()
+  //   : cast<PointerType>(callee->getType())->getElementType();
+  const Type* funcType = callee->getType();
+  return isVarArgsFunction(funcType);
+}
 
-  assert(0  && "There must be a return addr for a call instr");
 
-  return NULL;
+// Get the register number for the specified argument #argNo,
+// 
+// Return value:
+//      getInvalidRegNum(),  if there is no int register available for the arg. 
+//      regNum,              otherwise (this is NOT the unified reg. num).
+//                           regClassId is set to the register class ID.
+// 
+int
+UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
+                                   unsigned argNo, unsigned& regClassId) const
+{
+  regClassId = IntRegClassID;
+  if (argNo >= NumOfIntArgRegs)
+    return getInvalidRegNum();
+  else
+    return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
+}
 
+// Get the register number for the specified FP argument #argNo,
+// Use INT regs for FP args if this is a varargs call.
+// 
+// Return value:
+//      getInvalidRegNum(),  if there is no int register available for the arg. 
+//      regNum,              otherwise (this is NOT the unified reg. num).
+//                           regClassId is set to the register class ID.
+// 
+int
+UltraSparcRegInfo::regNumForFPArg(unsigned regType,
+                                  bool inCallee, bool isVarArgsCall,
+                                  unsigned argNo, unsigned& regClassId) const
+{
+  if (isVarArgsCall)
+    return regNumForIntArg(inCallee, isVarArgsCall, argNo, regClassId);
+  else
+    {
+      regClassId = FloatRegClassID;
+      if (regType == FPSingleRegType)
+        return (argNo*2+1 >= NumOfFloatArgRegs)?
+          getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2 + 1);
+      else if (regType == FPDoubleRegType)
+        return (argNo*2 >= NumOfFloatArgRegs)?
+          getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2);
+      else
+        assert(0 && "Illegal FP register type");
+       return 0;
+    }
 }
 
 
 //---------------------------------------------------------------------------
-// Finds the # of actual arguments of the call instruction
+// Finds the return address of a call sparc specific call instruction
 //---------------------------------------------------------------------------
 
-const unsigned 
-UltraSparcRegInfo::getCallInstNumArgs(const MachineInstr *CallMI) const {
+// The following 4  methods are used to find the RegType (SparcInternals.h)
+// of a LiveRange, a Value, and for a given register unified reg number.
+//
+int UltraSparcRegInfo::getRegTypeForClassAndType(unsigned regClassID,
+                                                 const Type* type) const
+{
+  switch (regClassID) {
+  case IntRegClassID:                   return IntRegType; 
+  case FloatRegClassID:
+    if (type == Type::FloatTy)          return FPSingleRegType;
+    else if (type == Type::DoubleTy)    return FPDoubleRegType;
+    assert(0 && "Unknown type in FloatRegClass"); return 0;
+  case IntCCRegClassID:                 return IntCCRegType; 
+  case FloatCCRegClassID:               return FloatCCRegType; 
+  case SpecialRegClassID:               return SpecialRegType; 
+  default: assert( 0 && "Unknown reg class ID"); return 0;
+  }
+}
 
-  unsigned OpCode = CallMI->getOpCode();
-  unsigned NumOfImpRefs =  CallMI->getNumImplicitRefs();
-  int NumArgs = -1;
+int UltraSparcRegInfo::getRegTypeForDataType(const Type* type) const
+{
+  return getRegTypeForClassAndType(getRegClassIDOfType(type), type);
+}
 
-  if( OpCode == CALL ) {
+int UltraSparcRegInfo::getRegTypeForLR(const LiveRange *LR) const
+{
+  return getRegTypeForClassAndType(LR->getRegClassID(), LR->getType());
+}
 
-    switch( NumOfImpRefs ) {
+int UltraSparcRegInfo::getRegType(int unifiedRegNum) const
+{
+  if (unifiedRegNum < 32) 
+    return IntRegType;
+  else if (unifiedRegNum < (32 + 32))
+    return FPSingleRegType;
+  else if (unifiedRegNum < (64 + 32))
+    return FPDoubleRegType;
+  else if (unifiedRegNum < (64+32+4))
+    return FloatCCRegType;
+  else if (unifiedRegNum < (64+32+4+2))  
+    return IntCCRegType;             
+  else 
+    assert(0 && "Invalid unified register number in getRegType");
+  return 0;
+}
 
-    case 0: assert(0 && "A CALL inst must have at least one ImpRef (RetAddr)");
 
-    case 1: NumArgs = 0;
-            break;
+// To find the register class used for a specified Type
+//
+unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
+                                                bool isCCReg) const {
+  Type::PrimitiveID ty = type->getPrimitiveID();
+  unsigned res;
     
-    default:  // two or more implicit refs
-      if(  CallMI->implicitRefIsDefined(NumOfImpRefs-2) ) 
-       NumArgs = NumOfImpRefs - 2;    // i.e., NumOfImpRef-2 is the ret val
-      else 
-       NumArgs = NumOfImpRefs - 1;
-    }
-
-  }
-  else if( OpCode == JMPLCALL ) {
-
-    // The last implicit operand is the return value of a JMPL instr
-    if( NumOfImpRefs > 0 ) {
-      if(  CallMI->implicitRefIsDefined(NumOfImpRefs-1) ) 
-       NumArgs = NumOfImpRefs - 1;    // i.e., NumOfImpRef-1 is the ret val
-      else 
-       NumArgs = NumOfImpRefs;
-    }
-    else 
-      NumArgs = NumOfImpRefs;
+  // FIXME: Comparing types like this isn't very safe...
+  if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
+      (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
+    res = IntRegClassID;             // sparc int reg (ty=0: void)
+  else if (ty <= Type::DoubleTyID)
+    res = FloatRegClassID;           // sparc float reg class
+  else { 
+    //std::cerr << "TypeID: " << ty << "\n";
+    assert(0 && "Cannot resolve register class for type");
+    return 0;
   }
-  else
-    assert(0 && "OpCode must be CALL/JMPL for a call instr");
-
-  assert( (NumArgs != -1)  && "Internal error in getCallInstNumArgs" );
-  return (unsigned) NumArgs;
-
+  
+  if (isCCReg)
+    return res + 2;      // corresponding condition code register 
+  else 
+    return res;
 }
 
+unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
+  switch(regType) {
+  case IntRegType:      return IntRegClassID;
+  case FPSingleRegType:
+  case FPDoubleRegType: return FloatRegClassID;
+  case IntCCRegType:    return IntCCRegClassID;
+  case FloatCCRegType:  return FloatCCRegClassID;
+  default:
+    assert(0 && "Invalid register type in getRegClassIDOfRegType");
+    return 0;
+  }
+}
 
 //---------------------------------------------------------------------------
-// Suggests a register for the ret address in the RET machine instruction
+// Suggests a register for the ret address in the RET machine instruction.
+// We always suggest %i7 by convention.
 //---------------------------------------------------------------------------
-
-void UltraSparcRegInfo::suggestReg4RetAddr(const MachineInstr * RetMI, 
+void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI, 
                                           LiveRangeInfo& LRI) const {
 
-  assert( (RetMI->getNumOperands() >= 2)
-          && "JMPL/RETURN must have 3 and 2 operands respectively");
+  assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
   
-  MachineOperand & MO  = ( MachineOperand &) RetMI->getOperand(0);
-
-  MO.setRegForValue( getUnifiedRegNum( IntRegClassID, SparcIntRegOrder::i7) );
+  // return address is always mapped to i7 so set it immediately
+  RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
+                                              SparcIntRegClass::i7));
   
-  // TODO (Optimize)
+  // Possible Optimization
   // Instead of setting the color, we can suggest one. In that case,
   // we have to test later whether it received the suggested color.
   // In that case, a LR has to be created at the start of method.
   // It has to be done as follows (remove the setRegVal above):
 
-  /*
-  const Value *RetAddrVal = MO.getVRegValue();
-
-  assert( RetAddrVal && "LR for ret address must be created at start");
-
-  LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
-  RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
-  SparcIntRegOrdr::i7) );
-  */
-
-
+  // MachineOperand & MO  = RetMI->getOperand(0);
+  // const Value *RetAddrVal = MO.getVRegValue();
+  // assert( RetAddrVal && "LR for ret address must be created at start");
+  // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
+  // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
+  //                              SparcIntRegOrdr::i7) );
 }
 
 
 //---------------------------------------------------------------------------
-// Suggests a register for the ret address in the JMPL/CALL machine instr
+// Suggests a register for the ret address in the JMPL/CALL machine instr.
+// Sparc ABI dictates that %o7 be used for this purpose.
 //---------------------------------------------------------------------------
-void UltraSparcRegInfo::suggestReg4CallAddr(const MachineInstr * CallMI,
-                                           LiveRangeInfo& LRI,
-                                           vector<RegClass *> RCList) const {
-
-
-  const Value *RetAddrVal = getCallInstRetAddr( CallMI );
-
-  // RetAddrVal cannot be NULL (asserted in  getCallInstRetAddr)
-  // create a new LR for the return address and color it
-  
-  LiveRange * RetAddrLR = new LiveRange();  
-  RetAddrLR->add( RetAddrVal );
-  unsigned RegClassID = getRegClassIDOfValue( RetAddrVal );
-  RetAddrLR->setRegClass( RCList[RegClassID] );
-  RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o7));
-  LRI.addLRToMap( RetAddrVal, RetAddrLR);
-  
-
-  /*  
-  assert( (CallMI->getNumOperands() == 3) && "JMPL must have 3 operands");
-
-  // directly set color since the LR of ret address (if there were one) 
-  // will not extend after the call instr
-
-  MachineOperand & MO  = ( MachineOperand &) CallMI->getOperand(2);
-  MO.setRegForValue( getUnifiedRegNum( IntRegClassID,SparcIntRegOrder::o7) );
+void
+UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
+                                       LiveRangeInfo& LRI) const
+{
+  CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
+  const Value *RetAddrVal = argDesc->getReturnAddrReg();
+  assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
 
-  */
+  // A LR must already exist for the return address.
+  LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
+  assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
 
+  unsigned RegClassID = RetAddrLR->getRegClassID();
+  RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
 }
 
 
 
-
 //---------------------------------------------------------------------------
 //  This method will suggest colors to incoming args to a method. 
+//  According to the Sparc ABI, the first 6 incoming args are in 
+//  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
-//  done - it will be colored (or spilled) as a normal value.
+//  done - it will be colored (or spilled) as a normal live range.
 //---------------------------------------------------------------------------
-
-void UltraSparcRegInfo::suggestRegs4MethodArgs(const Method *const Meth, 
+void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth, 
                                               LiveRangeInfo& LRI) const 
 {
-
-                                                 // get the argument list
-  const Method::ArgumentListType& ArgList = Meth->getArgumentList();           
-                                                 // get an iterator to arg list
-  Method::ArgumentListType::const_iterator ArgIt = ArgList.begin(); 
-
-  // for each argument
-  for( unsigned argNo=0; ArgIt != ArgList.end() ; ++ArgIt, ++argNo) {    
-
-    // get the LR of arg
-    LiveRange *const LR = LRI.getLiveRangeForValue((const Value *) *ArgIt); 
-    assert( LR && "No live range found for method arg");
-
-    unsigned RegType = getRegType( LR );
-
-
-    // if the arg is in int class - allocate a reg for an int arg
-    if( RegType == IntRegType ) {
-
-      if( argNo < NumOfIntArgRegs) {
-       LR->setSuggestedColor( SparcIntRegOrder::i0 + argNo );
-
-      }
+  // Check if this is a varArgs function. needed for choosing regs.
+  bool isVarArgs = isVarArgsFunction(Meth->getType());
   
-      else {
-       // Do NOTHING as this will be colored as a normal value.
-       if (DEBUG_RA) cerr << " Int Regr not suggested for method arg\n";
-      }
-     
-    }
-    else if( RegType==FPSingleRegType && (argNo*2+1) < NumOfFloatArgRegs) 
-      LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2 + 1) );
+  // Count the arguments, *ignoring* whether they are int or FP args.
+  // Use this common arg numbering to pick the right int or fp register.
+  unsigned argNo=0;
+  for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
+      I != E; ++I, ++argNo) {
+    LiveRange *LR = LRI.getLiveRangeForValue(I);
+    assert(LR && "No live range found for method arg");
     
-    else if( RegType == FPDoubleRegType && (argNo*2) < NumOfFloatArgRegs) 
-      LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2) ); 
+    unsigned regType = getRegTypeForLR(LR);
+    unsigned regClassIDOfArgReg = BadRegClass; // for chosen reg (unused)
     
-
+    int regNum = (regType == IntRegType)
+      ? regNumForIntArg(/*inCallee*/ true, isVarArgs, argNo, regClassIDOfArgReg)
+      : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs, argNo,
+                       regClassIDOfArgReg); 
+    
+    if (regNum != getInvalidRegNum())
+      LR->setSuggestedColor(regNum);
   }
-  
 }
 
+
 //---------------------------------------------------------------------------
-// 
+// This method is called after graph coloring to move incoming args to
+// the correct hardware registers if they did not receive the correct
+// (suggested) color through graph coloring.
 //---------------------------------------------------------------------------
+void UltraSparcRegInfo::colorMethodArgs(const Function *Meth, 
+                            LiveRangeInfo &LRI,
+                            std::vector<MachineInstr*>& InstrnsBefore,
+                            std::vector<MachineInstr*>& InstrnsAfter) const {
 
-void UltraSparcRegInfo::colorMethodArgs(const Method *const Meth, 
-                                       LiveRangeInfo& LRI,
-                                       AddedInstrns *const FirstAI) const {
-
-                                                 // get the argument list
-  const Method::ArgumentListType& ArgList = Meth->getArgumentList();           
-                                                 // get an iterator to arg list
-  Method::ArgumentListType::const_iterator ArgIt = ArgList.begin(); 
-
+  // check if this is a varArgs function. needed for choosing regs.
+  bool isVarArgs = isVarArgsFunction(Meth->getType());
   MachineInstr *AdMI;
 
-
   // for each argument
-  for( unsigned argNo=0; ArgIt != ArgList.end() ; ++ArgIt, ++argNo) {    
-
+  // for each argument.  count INT and FP arguments separately.
+  unsigned argNo=0, intArgNo=0, fpArgNo=0;
+  for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
+      I != E; ++I, ++argNo) {
     // get the LR of arg
-    LiveRange *const LR = LRI.getLiveRangeForValue((const Value *) *ArgIt); 
+    LiveRange *LR = LRI.getLiveRangeForValue(I);
     assert( LR && "No live range found for method arg");
 
-
-    unsigned RegType = getRegType( LR );
-    unsigned RegClassID = (LR->getRegClass())->getID();
-
-
-    // find whether this argument is coming in a register (if not, on stack)
-
+    unsigned regType = getRegTypeForLR(LR);
+    unsigned RegClassID = LR->getRegClassID();
+    
+    // Find whether this argument is coming in a register (if not, on stack)
+    // Also find the correct register the argument must use (UniArgReg)
+    //
     bool isArgInReg = false;
-    unsigned UniArgReg = InvalidRegNum;         // reg that LR MUST be colored with
-
-    if( (RegType== IntRegType && argNo <  NumOfIntArgRegs)) {
-      isArgInReg = true;
-      UniArgReg = getUnifiedRegNum( RegClassID, SparcIntRegOrder::i0 + argNo );
-    }
-    else if(RegType == FPSingleRegType && argNo < NumOfFloatArgRegs)  { 
-      isArgInReg = true;
-      UniArgReg = getUnifiedRegNum( RegClassID, 
-                                   SparcFloatRegOrder::f0 + argNo*2 + 1 ) ;
-    }
-    else if(RegType == FPDoubleRegType && argNo < NumOfFloatArgRegs)  { 
+    unsigned UniArgReg = getInvalidRegNum(); // reg that LR MUST be colored with
+    unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
+    
+    int regNum = (regType == IntRegType)
+      ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
+                        argNo, regClassIDOfArgReg)
+      : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
+                       argNo, regClassIDOfArgReg);
+    
+    if(regNum != getInvalidRegNum()) {
       isArgInReg = true;
-      UniArgReg = getUnifiedRegNum(RegClassID, SparcFloatRegOrder::f0+argNo*2);
+      UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
     }
-
     
-    if( LR->hasColor() ) {
+    if( ! LR->isMarkedForSpill() ) {    // if this arg received a register
 
       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
 
       // if LR received the correct color, nothing to do
+      //
       if( UniLRReg == UniArgReg )
        continue;
 
-      // We are here because the LR did not have a suggested 
-      // color or did not receive the suggested color but LR got a register.
-      // Now we have to copy %ix reg (or stack pos of arg) 
-      // to the register it was colored with.
+      // We are here because the LR did not receive the suggested 
+      // but LR received another register.
+      // Now we have to copy the %i reg (or stack pos of arg) 
+      // to the register the LR was colored with.
       
-      // if the arg is coming in UniArgReg register MUST go into
+      // if the arg is coming in UniArgReg register, it MUST go into
       // the UniLRReg register
-      if( isArgInReg ) 
-       AdMI = cpReg2RegMI( UniArgReg, UniLRReg, RegType );
+      //
+      if( isArgInReg ) {
+       if( regClassIDOfArgReg != RegClassID ) {
+          assert(0 && "This could should work but it is not tested yet");
+          
+         // It is a variable argument call: the float reg must go in a %o reg.
+         // We have to move an int reg to a float reg via memory.
+          // 
+          assert(isVarArgs &&
+                 RegClassID == FloatRegClassID && 
+                 regClassIDOfArgReg == IntRegClassID &&
+                 "This should only be an Int register for an FP argument");
+          
+         int TmpOff = MachineFunction::get(Meth).getInfo()->pushTempValue(
+                                                getSpilledRegSize(regType));
+         cpReg2MemMI(InstrnsBefore,
+                      UniArgReg, getFramePointer(), TmpOff, IntRegType);
+          
+         cpMem2RegMI(InstrnsBefore,
+                      getFramePointer(), TmpOff, UniLRReg, regType);
+       }
+       else {  
+         cpReg2RegMI(InstrnsBefore, UniArgReg, UniLRReg, regType);
+       }
+      }
+      else {
 
-      else 
-       assert(0 && "TODO: Color an Incoming arg on stack");
+       // Now the arg is coming on stack. Since the LR received a register,
+       // we just have to load the arg on stack into that register
+       //
+        const TargetFrameInfo& frameInfo = target.getFrameInfo();
+       int offsetFromFP =
+          frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
+                                         argNo);
+
+        // float arguments on stack are right justified so adjust the offset!
+        // int arguments are also right justified but they are always loaded as
+        // a full double-word so the offset does not need to be adjusted.
+        if (regType == FPSingleRegType) {
+          unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
+          unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
+          assert(argSize <= slotSize && "Insufficient slot size!");
+          offsetFromFP += slotSize - argSize;
+        }
+
+       cpMem2RegMI(InstrnsBefore,
+                    getFramePointer(), offsetFromFP, UniLRReg, regType);
+      }
+      
+    } // if LR received a color
+
+    else {                             
+
+      // Now, the LR did not receive a color. But it has a stack offset for
+      // spilling.
+      // So, if the arg is coming in UniArgReg register,  we can just move
+      // that on to the stack pos of LR
+
+      if( isArgInReg ) {
+        
+       if( regClassIDOfArgReg != RegClassID ) {
+          assert(0 &&
+                 "FP arguments to a varargs function should be explicitly "
+                 "copied to/from int registers by instruction selection!");
+          
+         // It must be a float arg for a variable argument call, which
+          // must come in a %o reg.  Move the int reg to the stack.
+          // 
+          assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
+                 "This should only be an Int register for an FP argument");
+          
+          cpReg2MemMI(InstrnsBefore, UniArgReg,
+                      getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
+        }
+        else {
+           cpReg2MemMI(InstrnsBefore, UniArgReg,
+                       getFramePointer(), LR->getSpillOffFromFP(), regType);
+        }
+      }
 
-      // Now add the instruction
-      FirstAI->InstrnsBefore.push_back( AdMI );
+      else {
 
-    }
+       // Now the arg is coming on stack. Since the LR did NOT 
+       // received a register as well, it is allocated a stack position. We
+       // can simply change the stack position of the LR. We can do this,
+       // since this method is called before any other method that makes
+       // uses of the stack pos of the LR (e.g., updateMachineInstr)
+        // 
+        const TargetFrameInfo& frameInfo = target.getFrameInfo();
+       int offsetFromFP =
+          frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
+                                         argNo);
+
+        // FP arguments on stack are right justified so adjust offset!
+        // int arguments are also right justified but they are always loaded as
+        // a full double-word so the offset does not need to be adjusted.
+        if (regType == FPSingleRegType) {
+          unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
+          unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
+          assert(argSize <= slotSize && "Insufficient slot size!");
+          offsetFromFP += slotSize - argSize;
+        }
+        
+       LR->modifySpillOffFromFP( offsetFromFP );
+      }
 
-    else {                                // LR is not colored (i.e., spilled)
-      
-      assert(0 && "TODO: Color a spilled arg ");
-      
     }
 
-
   }  // for each incoming argument
 
 }
 
 
 
-
 //---------------------------------------------------------------------------
 // This method is called before graph coloring to suggest colors to the
 // outgoing call args and the return value of the call.
 //---------------------------------------------------------------------------
-void UltraSparcRegInfo::suggestRegs4CallArgs(const MachineInstr *const CallMI, 
-                                            LiveRangeInfo& LRI,
-                                            vector<RegClass *> RCList) const {
-
-  assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
-
-  suggestReg4CallAddr(CallMI, LRI, RCList);
-
-
-  // First color the return value of the call instruction. The return value
-  // will be in %o0 if the value is an integer type, or in %f0 if the 
-  // value is a float type.
-
-  // the return value cannot have a LR in machine instruction since it is
-  // only defined by the call instruction
-
-  // if type is not void,  create a new live range and set its 
-  // register class and add to LRI
-
-
-  const Value *RetVal = getCallInstRetVal( CallMI );
-
-
-  if( RetVal ) {
+void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI, 
+                                            LiveRangeInfo& LRI) const {
+  assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
 
-    assert( (! LRI.getLiveRangeForValue( RetVal ) ) && 
-           "LR for ret Value of call already definded!");
+  CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
+  
+  suggestReg4CallAddr(CallMI, LRI);
 
+  // First color the return value of the call instruction, if any.
+  // The return value will be in %o0 if the value is an integer type,
+  // or in %f0 if the value is a float type.
+  // 
+  if (const Value *RetVal = argDesc->getReturnValue()) {
+    LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
+    assert(RetValLR && "No LR for return Value of call!");
 
-      // create a new LR for the return value
+    unsigned RegClassID = RetValLR->getRegClassID();
 
-    LiveRange * RetValLR = new LiveRange();  
-    RetValLR->add( RetVal );
-    unsigned RegClassID = getRegClassIDOfValue( RetVal );
-    RetValLR->setRegClass( RCList[RegClassID] );
-    LRI.addLRToMap( RetVal, RetValLR);
-    
     // now suggest a register depending on the register class of ret arg
-
     if( RegClassID == IntRegClassID ) 
-      RetValLR->setSuggestedColor(SparcIntRegOrder::o0);
+      RetValLR->setSuggestedColor(SparcIntRegClass::o0);
     else if (RegClassID == FloatRegClassID ) 
-      RetValLR->setSuggestedColor(SparcFloatRegOrder::f0 );
+      RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
     else assert( 0 && "Unknown reg class for return value of call\n");
-
   }
 
-  
   // Now suggest colors for arguments (operands) of the call instruction.
   // Colors are suggested only if the arg number is smaller than the
   // the number of registers allocated for argument passing.
   // Now, go thru call args - implicit operands of the call MI
 
-  unsigned NumOfCallArgs =  getCallInstNumArgs( CallMI );
+  unsigned NumOfCallArgs = argDesc->getNumArgs();
   
-  for(unsigned argNo=0, i=0; i < NumOfCallArgs; ++i, ++argNo ) {
+  for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
+       i < NumOfCallArgs; ++i, ++argNo) {    
 
-    const Value *CallArg = CallMI->getImplicitRef(i);
+    const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
     
     // get the LR of call operand (parameter)
     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
-
-    // not possible to have a null LR since all args (even consts)  
-    // must be defined before
-    if( !LR ) {          
-      if( DEBUG_RA) {
-       cerr << " ERROR: In call instr, no LR for arg:  " ;
-       printValue(CallArg); cerr << endl;
-      }
-      assert(0 && "NO LR for call arg");  
-      // continue;
-    }
+    if (!LR)
+      continue;                    // no live ranges for constants and labels
+
+    unsigned regType = getRegTypeForLR(LR);
+    unsigned regClassIDOfArgReg = BadRegClass; // chosen reg class (unused)
+
+    // Choose a register for this arg depending on whether it is
+    // an INT or FP value.  Here we ignore whether or not it is a
+    // varargs calls, because FP arguments will be explicitly copied
+    // to an integer Value and handled under (argCopy != NULL) below.
+    int regNum = (regType == IntRegType)
+      ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
+                        argNo, regClassIDOfArgReg)
+      : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
+                       argNo, regClassIDOfArgReg); 
     
-    unsigned RegType = getRegType( LR );
-
-    // if the arg is in int class - allocate a reg for an int arg
-    if( RegType == IntRegType ) {
-
-      if( argNo < NumOfIntArgRegs) 
-       LR->setSuggestedColor( SparcIntRegOrder::o0 + argNo );
-
-      else if (DEBUG_RA) 
-       // Do NOTHING as this will be colored as a normal value.
-       cerr << " Regr not suggested for int call arg" << endl;
-      
-    }
-    else if( RegType == FPSingleRegType &&  (argNo*2 +1)< NumOfFloatArgRegs) 
-      LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2 + 1) );
-    
-    else if( RegType == FPDoubleRegType && (argNo*2) < NumOfFloatArgRegs) 
-      LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2) ); 
-    
-
+    // If a register could be allocated, use it.
+    // If not, do NOTHING as this will be colored as a normal value.
+    if(regNum != getInvalidRegNum())
+      LR->setSuggestedColor(regNum);
   } // for all call arguments
-
 }
 
 
 //---------------------------------------------------------------------------
-// After graph coloring, we have call this method to see whehter the return
-// value and the call args received the correct colors. If not, we have
-// to instert copy instructions.
-//---------------------------------------------------------------------------
-
-
-void UltraSparcRegInfo::colorCallArgs(const MachineInstr *const CallMI,
-                                     LiveRangeInfo& LRI,
-                                     AddedInstrns *const CallAI) const {
-
-  assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
-
-  // First color the return value of the call.
-  // If there is a LR for the return value, it means this
-  // method returns a value
-  
-  MachineInstr *AdMI;
-
-  const Value *RetVal = getCallInstRetVal( CallMI );
-
-  if( RetVal ) {
-
-    LiveRange * RetValLR = LRI.getLiveRangeForValue( RetVal );
-
-    if( !RetValLR ) {
-      cerr << "\nNo LR for:";
-      printValue( RetVal );
-      cerr << endl;
-      assert( RetValLR && "ERR:No LR for non-void return value");
-      //return;
-    }
-
-    unsigned RegClassID = (RetValLR->getRegClass())->getID();    
-    bool recvCorrectColor = false;
-
-    unsigned CorrectCol;                // correct color for ret value
-    if(RegClassID == IntRegClassID)
-      CorrectCol = SparcIntRegOrder::o0;
-    else if(RegClassID == FloatRegClassID)
-      CorrectCol = SparcFloatRegOrder::f0;
-    else 
-      assert( 0 && "Unknown RegClass");
-
-
-    // if the LR received the correct color, NOTHING to do
-
-    if(  RetValLR->hasColor() )
-      if( RetValLR->getColor() == CorrectCol )
-       recvCorrectColor = true;
-
-
-    // if we didn't receive the correct color for some reason, 
-    // put copy instruction
-    
-    if( !recvCorrectColor ) {
-      
-      if( RetValLR->hasColor() ) {
-       
-       unsigned RegType = getRegType( RetValLR );
-
-       unsigned 
-         UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
-
-       // the  reg that LR must be colored with
-       unsigned UniRetReg = getUnifiedRegNum( RegClassID, CorrectCol); 
-       
-       // the return value is coming in UniRetReg but has to go into
-       // the UniRetLRReg
-
-       AdMI = cpReg2RegMI( UniRetReg, UniRetLRReg, RegType );  
-       CallAI->InstrnsAfter.push_back( AdMI );
-       
-       
-      } // if LR has color
-      else {
-       
-       assert(0 && "LR of return value is splilled");
-      }
-      
-      
-    } // the LR didn't receive the suggested color  
-    
-  } // if there a return value
-  
-
-  // Now color all args of the call instruction
-
-  unsigned NumOfCallArgs =  getCallInstNumArgs( CallMI );
-
-  for(unsigned argNo=0, i=0; i < NumOfCallArgs; ++i, ++argNo ) {
-
-    const Value *CallArg = CallMI->getImplicitRef(i);
-
-    // get the LR of call operand (parameter)
-    LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
-
-    unsigned RegType = getRegType( CallArg );
-    unsigned RegClassID =  getRegClassIDOfValue( CallArg);
-    
-    // find whether this argument is coming in a register (if not, on stack)
-
-    bool isArgInReg = false;
-    unsigned UniArgReg = InvalidRegNum;  // reg that LR must be colored with
-
-    if( (RegType== IntRegType && argNo <  NumOfIntArgRegs)) {
-      isArgInReg = true;
-      UniArgReg = getUnifiedRegNum(RegClassID, SparcIntRegOrder::o0 + argNo );
-    }
-    else if(RegType == FPSingleRegType && argNo < NumOfFloatArgRegs)  { 
-      isArgInReg = true;
-      UniArgReg = getUnifiedRegNum(RegClassID, 
-                                  SparcFloatRegOrder::f0 + (argNo*2 + 1) );
-    }
-    else if(RegType == FPDoubleRegType && argNo < NumOfFloatArgRegs)  { 
-      isArgInReg = true;
-      UniArgReg = getUnifiedRegNum(RegClassID, SparcFloatRegOrder::f0+argNo*2);
-    }
-
-
-    // not possible to have a null LR since all args (even consts)  
-    // must be defined before
-    if( !LR ) {          
-      if( DEBUG_RA) {
-       cerr << " ERROR: In call instr, no LR for arg:  " ;
-       printValue(CallArg); cerr << endl;
-      }
-      assert(0 && "NO LR for call arg");  
-      // continue;
-    }
-
-
-    // if the LR received the suggested color, NOTHING to do
-
-
-    if( LR->hasColor() ) {
-
-
-      unsigned UniLRReg = getUnifiedRegNum( RegClassID,  LR->getColor() );
-
-      // if LR received the correct color, nothing to do
-      if( UniLRReg == UniArgReg )
-       continue;
-
-      // We are here because though the LR is allocated a register, it
-      // was not allocated the suggested register. So, we have to copy %ix reg 
-      // (or stack pos of arg) to the register it was colored with
-
-      // the LR is colored with UniLRReg but has to go into  UniArgReg
-      // to pass it as an argument
-
-      if( isArgInReg ) 
-       AdMI = cpReg2RegMI(UniLRReg, UniArgReg, RegType );
-
-      else 
-       assert(0 && "TODO: Push an outgoing arg on stack");
-
-      // Now add the instruction
-      CallAI->InstrnsBefore.push_back( AdMI );
-
-    }
-
-    else {                                // LR is not colored (i.e., spilled)
-      
-      assert(0 && "TODO: Copy a spilled call arg to an output reg ");
-      
-    }
-
-  }  // for each parameter in call instruction
-
-}
-
-//---------------------------------------------------------------------------
-// This method is called for an LLVM return instruction to identify which
+// this method is called for an LLVM return instruction to identify which
 // values will be returned from this method and to suggest colors.
 //---------------------------------------------------------------------------
-void UltraSparcRegInfo::suggestReg4RetValue(const MachineInstr *const RetMI, 
-                                            LiveRangeInfo& LRI) const {
-
-  assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
-
-    suggestReg4RetAddr(RetMI, LRI);
-
-  // if there is an implicit ref, that has to be the ret value
-  if(  RetMI->getNumImplicitRefs() > 0 ) {
-
-    // The first implicit operand is the return value of a return instr
-    const Value *RetVal =  RetMI->getImplicitRef(0);
-
-    MachineInstr *AdMI;
-    LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
+void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI, 
+                                            LiveRangeInfo& LRI) const {
 
-    if( !LR ) {
-     cerr << "\nNo LR for:";
-     printValue( RetVal );
-     cerr << endl;
-     assert( LR && "No LR for return value of non-void method");
-     //return;
-   }
+  assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
 
-    unsigned RegClassID = (LR->getRegClass())->getID();
-      
-    if( RegClassID == IntRegClassID ) 
-      LR->setSuggestedColor(SparcIntRegOrder::i0);
-    
-    else if ( RegClassID == FloatRegClassID ) 
-      LR->setSuggestedColor(SparcFloatRegOrder::f0);
-      
-  }
+  suggestReg4RetAddr(RetMI, LRI);
 
+  // To find the return value (if any), we can get the LLVM return instr.
+  // from the return address register, which is the first operand
+  Value* tmpI = RetMI->getOperand(0).getVRegValue();
+  ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
+  if (const Value *RetVal = retI->getReturnValue())
+    if (LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
+      LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
+                            ? (unsigned) SparcIntRegClass::i0
+                            : (unsigned) SparcFloatRegClass::f0);
 }
 
 //---------------------------------------------------------------------------
-
+// Check if a specified register type needs a scratch register to be
+// copied to/from memory.  If it does, the reg. type that must be used
+// for scratch registers is returned in scratchRegType.
+//
+// Only the int CC register needs such a scratch register.
+// The FP CC registers can (and must) be copied directly to/from memory.
 //---------------------------------------------------------------------------
-void UltraSparcRegInfo::colorRetValue(const  MachineInstr *const RetMI, 
-                                     LiveRangeInfo& LRI,
-                                     AddedInstrns *const RetAI) const {
-
-  assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
-
-  // if there is an implicit ref, that has to be the ret value
-  if(  RetMI->getNumImplicitRefs() > 0 ) {
-
-    // The first implicit operand is the return value of a return instr
-    const Value *RetVal =  RetMI->getImplicitRef(0);
-
-    MachineInstr *AdMI;
-    LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
-
-    if( ! LR ) {
-       cerr << "\nNo LR for:";
-       printValue( RetVal );
-       cerr << endl;
-       // assert( LR && "No LR for return value of non-void method");
-       return;
-   }
-
-    unsigned RegClassID =  getRegClassIDOfValue(RetVal);
-    unsigned RegType = getRegType( RetVal );
-
-
-    unsigned CorrectCol;
-    if(RegClassID == IntRegClassID)
-      CorrectCol = SparcIntRegOrder::i0;
-    else if(RegClassID == FloatRegClassID)
-      CorrectCol = SparcFloatRegOrder::f0;
-    else 
-      assert( 0 && "Unknown RegClass");
-
-
-    // if the LR received the correct color, NOTHING to do
-
-    if(  LR->hasColor() )
-      if( LR->getColor() == CorrectCol )
-       return;
-
-    unsigned UniRetReg =  getUnifiedRegNum( RegClassID, CorrectCol );
-
-    if( LR->hasColor() ) {
-
-      // We are here because the LR was allocted a regiter
-      // It may be the suggested register or not
-
-      // copy the LR of retun value to i0 or f0
-
-      unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
 
-      // the LR received  UniLRReg but must be colored with UniRetReg
-      // to pass as the return value
-
-      AdMI = cpReg2RegMI( UniLRReg, UniRetReg, RegType); 
-      RetAI->InstrnsBefore.push_back( AdMI );
+bool
+UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
+                                          int& scratchRegType) const
+{
+  if (RegType == IntCCRegType)
+    {
+      scratchRegType = IntRegType;
+      return true;
     }
-    else 
-      assert(0 && "TODO: Copy the return value from stack\n");
-
-  } // if there is a return value
-
+  return false;
 }
 
-
 //---------------------------------------------------------------------------
 // Copy from a register to register. Register number must be the unified
-// register number
+// register number.
 //---------------------------------------------------------------------------
 
-
-MachineInstr * UltraSparcRegInfo::cpReg2RegMI(const unsigned SrcReg, 
-                                             const unsigned DestReg,
-                                             const int RegType) const {
-
-  assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
+void
+UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
+                               unsigned SrcReg,
+                               unsigned DestReg,
+                               int RegType) const {
+  assert( ((int)SrcReg != getInvalidRegNum()) && 
+          ((int)DestReg != getInvalidRegNum()) &&
          "Invalid Register");
   
   MachineInstr * MI = NULL;
-
+  
   switch( RegType ) {
     
-  case IntRegType:
   case IntCCRegType:
+    if (getRegType(DestReg) == IntRegType) {
+      // copy intCC reg to int reg
+      MI = (BuildMI(V9::RDCCR, 2)
+            .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
+                                      SparcIntCCRegClass::ccr))
+            .addMReg(DestReg,MOTy::Def));
+    } else {
+      // copy int reg to intCC reg
+      assert(getRegType(SrcReg) == IntRegType
+             && "Can only copy CC reg to/from integer reg");
+      MI = (BuildMI(V9::WRCCRr, 3)
+            .addMReg(SrcReg)
+            .addMReg(SparcIntRegClass::g0)
+            .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
+                                      SparcIntCCRegClass::ccr), MOTy::Def));
+    }
+    break;
+    
   case FloatCCRegType: 
-    MI = new MachineInstr(ADD, 3);
-    MI->SetMachineOperand(0, SrcReg, false);
-    MI->SetMachineOperand(1, SparcIntRegOrder::g0, false);
-    MI->SetMachineOperand(2, DestReg, true);
+    assert(0 && "Cannot copy FPCC register to any other register");
     break;
-
+    
+  case IntRegType:
+    MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
+      .addMReg(DestReg, MOTy::Def);
+    break;
+    
   case FPSingleRegType:
-    MI = new MachineInstr(FMOVS, 2);
-    MI->SetMachineOperand(0, SrcReg, false);
-    MI->SetMachineOperand(1, DestReg, true);
+    MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
     break;
 
   case FPDoubleRegType:
-    MI = new MachineInstr(FMOVD, 2);
-    MI->SetMachineOperand(0, SrcReg, false);    
-    MI->SetMachineOperand(1, DestReg, true);
+    MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
     break;
 
   default:
-    assert(0 && "Unknow RegType");
+    assert(0 && "Unknown RegType");
+    break;
   }
-
-  return MI;
+  
+  if (MI)
+    mvec.push_back(MI);
 }
 
-
 //---------------------------------------------------------------------------
 // Copy from a register to memory (i.e., Store). Register number must 
 // be the unified register number
 //---------------------------------------------------------------------------
 
 
-MachineInstr * UltraSparcRegInfo::cpReg2MemMI(const unsigned SrcReg, 
-                                             const unsigned DestPtrReg,
-                                             const int Offset,
-                                             const int RegType) const {
-
-
+void
+UltraSparcRegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
+                               unsigned SrcReg, 
+                               unsigned PtrReg,
+                               int Offset, int RegType,
+                               int scratchReg) const {
   MachineInstr * MI = NULL;
+  int OffReg = -1;
+
+  // If the Offset will not fit in the signed-immediate field, find an
+  // unused register to hold the offset value.  This takes advantage of
+  // the fact that all the opcodes used below have the same size immed. field.
+  // Use the register allocator, PRA, to find an unused reg. at this MI.
+  // 
+  if (RegType != IntCCRegType)          // does not use offset below
+    if (! target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset)) {
+#ifdef CAN_FIND_FREE_REGISTER_TRANSPARENTLY
+      RegClass* RC = PRA.getRegClassByID(this->getRegClassIDOfRegType(RegType));
+      OffReg = PRA.getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
+#else
+      // Default to using register g2 for holding large offsets
+      OffReg = getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                                SparcIntRegClass::g4);
+#endif
+      assert(OffReg >= 0 && "FIXME: cpReg2MemMI cannot find an unused reg.");
+      mvec.push_back(BuildMI(V9::SETSW, 2).addZImm(Offset).addReg(OffReg));
+    }
 
-  switch( RegType ) {
-    
+  switch (RegType) {
   case IntRegType:
-  case IntCCRegType:
-  case FloatCCRegType: 
-    MI = new MachineInstr(STX, 3);
-    MI->SetMachineOperand(0, SrcReg, false);
-    MI->SetMachineOperand(1, DestPtrReg, false);
-    MI->SetMachineOperand(2, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::STXi, Offset))
+      MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
+    else
+      MI = BuildMI(V9::STXr,3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
     break;
 
   case FPSingleRegType:
-    MI = new MachineInstr(ST, 3);
-    MI->SetMachineOperand(0, SrcReg, false);
-    MI->SetMachineOperand(1, DestPtrReg, false);
-    MI->SetMachineOperand(2, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::STFi, Offset))
+      MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
+    else
+      MI = BuildMI(V9::STFr, 3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
     break;
 
   case FPDoubleRegType:
-    MI = new MachineInstr(STD, 3);
-    MI->SetMachineOperand(0, SrcReg, false);
-    MI->SetMachineOperand(1, DestPtrReg, false);
-    MI->SetMachineOperand(2, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::STDFi, Offset))
+      MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
+    else
+      MI = BuildMI(V9::STDFr,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(OffReg);
     break;
 
+  case IntCCRegType:
+    assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
+    assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
+    MI = (BuildMI(V9::RDCCR, 2)
+          .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
+                                    SparcIntCCRegClass::ccr))
+          .addMReg(scratchReg, MOTy::Def));
+    mvec.push_back(MI);
+    
+    cpReg2MemMI(mvec, scratchReg, PtrReg, Offset, IntRegType);
+    return;
+
+  case FloatCCRegType: {
+    unsigned fsrReg =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
+                                           SparcSpecialRegClass::fsr);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::STXFSRi, Offset))
+      MI=BuildMI(V9::STXFSRi,3).addMReg(fsrReg).addMReg(PtrReg).addSImm(Offset);
+    else
+      MI=BuildMI(V9::STXFSRr,3).addMReg(fsrReg).addMReg(PtrReg).addMReg(OffReg);
+    break;
+  }
   default:
-    assert(0 && "Unknow RegType");
+    assert(0 && "Unknown RegType in cpReg2MemMI");
   }
-
-  return MI;
+  mvec.push_back(MI);
 }
 
 
@@ -830,164 +824,146 @@ MachineInstr * UltraSparcRegInfo::cpReg2MemMI(const unsigned SrcReg,
 //---------------------------------------------------------------------------
 
 
-MachineInstr * UltraSparcRegInfo::cpMem2RegMI(const unsigned SrcPtrReg,        
-                                             const int Offset,
-                                             const unsigned DestReg,
-                                             const int RegType) const {
-  
+void
+UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
+                               unsigned PtrReg,        
+                               int Offset,
+                               unsigned DestReg,
+                               int RegType,
+                               int scratchReg) const {
   MachineInstr * MI = NULL;
+  int OffReg = -1;
+
+  // If the Offset will not fit in the signed-immediate field, find an
+  // unused register to hold the offset value.  This takes advantage of
+  // the fact that all the opcodes used below have the same size immed. field.
+  // Use the register allocator, PRA, to find an unused reg. at this MI.
+  // 
+  if (RegType != IntCCRegType)          // does not use offset below
+    if (! target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset)) {
+#ifdef CAN_FIND_FREE_REGISTER_TRANSPARENTLY
+      RegClass* RC = PRA.getRegClassByID(this->getRegClassIDOfRegType(RegType));
+      OffReg = PRA.getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
+#else
+      // Default to using register g2 for holding large offsets
+      OffReg = getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
+                                SparcIntRegClass::g4);
+#endif
+      assert(OffReg >= 0 && "FIXME: cpReg2MemMI cannot find an unused reg.");
+      mvec.push_back(BuildMI(V9::SETSW, 2).addZImm(Offset).addReg(OffReg));
+    }
 
-  switch( RegType ) {
-    
+  switch (RegType) {
   case IntRegType:
-  case IntCCRegType:
-  case FloatCCRegType: 
-    MI = new MachineInstr(LDX, 3);
-    MI->SetMachineOperand(0, SrcPtrReg, false);
-    MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
-    MI->SetMachineOperand(2, DestReg, false);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset))
+      MI = BuildMI(V9::LDXi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
+                                                                    MOTy::Def);
+    else
+      MI = BuildMI(V9::LDXr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
+                                                                    MOTy::Def);
     break;
 
   case FPSingleRegType:
-    MI = new MachineInstr(LD, 3);
-    MI->SetMachineOperand(0, SrcPtrReg, false);
-    MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
-    MI->SetMachineOperand(2, DestReg, false);
-
+    if (target.getInstrInfo().constantFitsInImmedField(V9::LDFi, Offset))
+      MI = BuildMI(V9::LDFi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
+                                                                    MOTy::Def);
+    else
+      MI = BuildMI(V9::LDFr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
+                                                                    MOTy::Def);
     break;
 
   case FPDoubleRegType:
-    MI = new MachineInstr(LDD, 3);
-    MI->SetMachineOperand(0, SrcPtrReg, false);
-    MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
-                         (int64_t) Offset, false);
-    MI->SetMachineOperand(2, DestReg, false);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::LDDFi, Offset))
+      MI= BuildMI(V9::LDDFi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
+                                                                    MOTy::Def);
+    else
+      MI= BuildMI(V9::LDDFr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
+                                                                    MOTy::Def);
     break;
 
+  case IntCCRegType:
+    assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
+    assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
+    cpMem2RegMI(mvec, PtrReg, Offset, scratchReg, IntRegType);
+    MI = (BuildMI(V9::WRCCRr, 3)
+          .addMReg(scratchReg)
+          .addMReg(SparcIntRegClass::g0)
+          .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
+                                    SparcIntCCRegClass::ccr), MOTy::Def));
+    break;
+    
+  case FloatCCRegType: {
+    unsigned fsrRegNum =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
+                                           SparcSpecialRegClass::fsr);
+    if (target.getInstrInfo().constantFitsInImmedField(V9::LDXFSRi, Offset))
+      MI = BuildMI(V9::LDXFSRi, 3).addMReg(PtrReg).addSImm(Offset)
+        .addMReg(fsrRegNum, MOTy::UseAndDef);
+    else
+      MI = BuildMI(V9::LDXFSRr, 3).addMReg(PtrReg).addMReg(OffReg)
+        .addMReg(fsrRegNum, MOTy::UseAndDef);
+    break;
+  }
   default:
-    assert(0 && "Unknow RegType");
+    assert(0 && "Unknown RegType in cpMem2RegMI");
   }
-
-  return MI;
+  mvec.push_back(MI);
 }
 
 
-
-
-
-
-
-
-
 //---------------------------------------------------------------------------
-// Only  constant/label values are accepted.
-// ***This code is temporary ***
+// Generate a copy instruction to copy a value to another. Temporarily
+// used by PhiElimination code.
 //---------------------------------------------------------------------------
 
 
-MachineInstr * UltraSparcRegInfo::cpValue2RegMI(Value * Val, 
-                                               const unsigned DestReg,
-                                               const int RegType) const {
-
-  assert( ((int)DestReg != InvalidRegNum) && "Invalid Register");
-
-  /*
-  unsigned MReg;
-  int64_t Imm;
-
-  MachineOperand::MachineOperandType MOTypeInt = 
-    ChooseRegOrImmed(Val, ADD,  *UltraSparcInfo, true, MReg, Imm);
-  */
-
-  MachineOperand::MachineOperandType MOType;
-
-  switch( Val->getValueType() ) {
-
-  case Value::ConstantVal: 
-  case Value::GlobalVariableVal:
-    MOType = MachineOperand:: MO_UnextendedImmed;  // TODO**** correct???
-    break;
-
-  case Value::BasicBlockVal:
-  case Value::MethodVal:
-    MOType = MachineOperand::MO_PCRelativeDisp;
-    break;
-
-  default:
-    cerr << "Value Type: " << Val->getValueType() << endl;
-    assert(0 && "Unknown val type - Only constants/globals/labels are valid");
-  }
-
-
-
+void
+UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
+                                 std::vector<MachineInstr*>& mvec) const {
+  int RegType = getRegTypeForDataType(Src->getType());
   MachineInstr * MI = NULL;
 
   switch( RegType ) {
-    
   case IntRegType:
-    MI = new MachineInstr(ADD);
-    MI->SetMachineOperand(0, MOType, Val, false);
-    MI->SetMachineOperand(1, SparcIntRegOrder::g0, false);
-    MI->SetMachineOperand(2, DestReg, true);
+    MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
+      .addRegDef(Dest);
     break;
-
   case FPSingleRegType:
-    assert(0 && "FP const move not yet implemented");
-    MI = new MachineInstr(FMOVS);
-    MI->SetMachineOperand(0, MachineOperand::MO_SignExtendedImmed, Val, false);
-    MI->SetMachineOperand(1, DestReg, true);
+    MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
     break;
-
-  case FPDoubleRegType:    
-    assert(0 && "FP const move not yet implemented");
-    MI = new MachineInstr(FMOVD);
-    MI->SetMachineOperand(0, MachineOperand::MO_SignExtendedImmed, Val, false);
-    MI->SetMachineOperand(1, DestReg, true);
+  case FPDoubleRegType:
+    MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
     break;
-
   default:
-    assert(0 && "Unknow RegType");
+    assert(0 && "Unknow RegType in CpValu2Value");
   }
 
-  return MI;
+  mvec.push_back(MI);
 }
 
 
 
-
-
-
-
 //---------------------------------------------------------------------------
 // Print the register assigned to a LR
 //---------------------------------------------------------------------------
 
-void UltraSparcRegInfo::printReg(const LiveRange *const LR) {
-
-  unsigned RegClassID = (LR->getRegClass())->getID();
+void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
+  unsigned RegClassID = LR->getRegClassID();
+  std::cerr << " Node ";
 
-  cerr << " *Node " << (LR->getUserIGNode())->getIndex();
-
-  if( ! LR->hasColor() ) {
-    cerr << " - could not find a color" << endl;
+  if (!LR->hasColor()) {
+    std::cerr << " - could not find a color\n";
     return;
   }
   
   // if a color is found
 
-  cerr << " colored with color "<< LR->getColor();
-
-  if( RegClassID == IntRegClassID ) {
+  std::cerr << " colored with color "<< LR->getColor();
 
-    cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) ;
-    cerr << "]" << endl;
-  }
-  else if ( RegClassID == FloatRegClassID) {
-    cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
-    if( LR->getTypeID() == Type::DoubleTyID )
-      cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
-    cerr << "]" << endl;
-  }
+  unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
+  
+  std::cerr << "[";
+  std::cerr<< getUnifiedRegName(uRegName);
+  if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
+    std::cerr << "+" << getUnifiedRegName(uRegName+1);
+  std::cerr << "]\n";
 }