Significant changes to correctly spill CC registers and to correctly
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9RegInfo.cpp
1 //===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
2 //
3 // This file contains implementation of Sparc specific helper methods
4 // used for register allocation.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "SparcInternals.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/Target/Sparc.h"
11 #include "llvm/CodeGen/MachineCodeForMethod.h"
12 #include "llvm/CodeGen/PhyRegAlloc.h"
13 #include "llvm/CodeGen/InstrSelection.h"
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineInstrAnnot.h"
17 #include "llvm/CodeGen/RegAllocCommon.h"
18 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Function.h"
22 #include "llvm/DerivedTypes.h"
23 #include <iostream>
24 #include <values.h>
25 using std::cerr;
26 using std::vector;
27
28 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
29   : MachineRegInfo(tgt), UltraSparcInfo(&tgt), NumOfIntArgRegs(6), 
30     NumOfFloatArgRegs(32), InvalidRegNum(1000) {
31    
32   MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
33   MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
34   MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
35   MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
36   
37   assert(SparcFloatRegOrder::StartOfNonVolatileRegs == 32 && 
38          "32 Float regs are used for float arg passing");
39 }
40
41
42 // getZeroRegNum - returns the register that contains always zero.
43 // this is the unified register number
44 //
45 int UltraSparcRegInfo::getZeroRegNum() const {
46   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
47                                 SparcIntRegOrder::g0);
48 }
49
50 // getCallAddressReg - returns the reg used for pushing the address when a
51 // method is called. This can be used for other purposes between calls
52 //
53 unsigned UltraSparcRegInfo::getCallAddressReg() const {
54   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
55                                 SparcIntRegOrder::o7);
56 }
57
58 // Returns the register containing the return address.
59 // It should be made sure that this  register contains the return 
60 // value when a return instruction is reached.
61 //
62 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
63   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
64                                 SparcIntRegOrder::i7);
65 }
66
67 // given the unified register number, this gives the name
68 // for generating assembly code or debugging.
69 //
70 const std::string UltraSparcRegInfo::getUnifiedRegName(int reg) const {
71   if( reg < 32 ) 
72     return SparcIntRegOrder::getRegName(reg);
73   else if ( reg < (64 + 32) )
74     return SparcFloatRegOrder::getRegName( reg  - 32);                  
75   else if( reg < (64+32+4) )
76     return SparcFloatCCRegOrder::getRegName( reg -32 - 64);
77   else if( reg < (64+32+4+2) )    // two names: %xcc and %ccr
78     return SparcIntCCRegOrder::getRegName( reg -32 - 64 - 4);             
79   else if (reg== InvalidRegNum)       //****** TODO: Remove */
80     return "<*NoReg*>";
81   else 
82     assert(0 && "Invalid register number");
83   return "";
84 }
85
86 // Get unified reg number for frame pointer
87 unsigned UltraSparcRegInfo::getFramePointer() const {
88   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
89                                 SparcIntRegOrder::i6);
90 }
91
92 // Get unified reg number for stack pointer
93 unsigned UltraSparcRegInfo::getStackPointer() const {
94   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
95                                 SparcIntRegOrder::o6);
96 }
97
98
99 //---------------------------------------------------------------------------
100 // Finds whether a call is an indirect call
101 //---------------------------------------------------------------------------
102
103 inline bool
104 isVarArgsFunction(const Type *funcType) {
105   return cast<FunctionType>(cast<PointerType>(funcType)
106                             ->getElementType())->isVarArg();
107 }
108
109 inline bool
110 isVarArgsCall(const MachineInstr *CallMI) {
111   Value* callee = CallMI->getOperand(0).getVRegValue();
112   // const Type* funcType = isa<Function>(callee)? callee->getType()
113   //   : cast<PointerType>(callee->getType())->getElementType();
114   const Type* funcType = callee->getType();
115   return isVarArgsFunction(funcType);
116 }
117
118
119 // Get the register number for the specified integer arg#,
120 // assuming there are argNum total args, intArgNum int args,
121 // and fpArgNum FP args preceding (and not including) this one.
122 // Use INT regs for FP args if this is a varargs call.
123 // 
124 // Return value:
125 //      InvalidRegNum,  if there is no int register available for the arg. 
126 //      regNum,         otherwise (this is NOT the unified reg. num).
127 // 
128 inline int
129 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
130                                    unsigned argNo,
131                                    unsigned intArgNo, unsigned fpArgNo,
132                                    unsigned& regClassId) const
133 {
134   regClassId = IntRegClassID;
135   if (argNo >= NumOfIntArgRegs)
136     return InvalidRegNum;
137   else
138     return argNo + (inCallee? SparcIntRegOrder::i0 : SparcIntRegOrder::o0);
139 }
140
141 // Get the register number for the specified FP arg#,
142 // assuming there are argNum total args, intArgNum int args,
143 // and fpArgNum FP args preceding (and not including) this one.
144 // Use INT regs for FP args if this is a varargs call.
145 // 
146 // Return value:
147 //      InvalidRegNum,  if there is no int register available for the arg. 
148 //      regNum,         otherwise (this is NOT the unified reg. num).
149 // 
150 inline int
151 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
152                                   bool inCallee, bool isVarArgsCall,
153                                   unsigned argNo,
154                                   unsigned intArgNo, unsigned fpArgNo,
155                                   unsigned& regClassId) const
156 {
157   if (isVarArgsCall)
158     return regNumForIntArg(inCallee, isVarArgsCall, argNo, intArgNo, fpArgNo,
159                            regClassId);
160   else
161     {
162       regClassId = FloatRegClassID;
163       if (regType == FPSingleRegType)
164         return (argNo*2+1 >= NumOfFloatArgRegs)?
165           InvalidRegNum : SparcFloatRegOrder::f0 + (argNo * 2 + 1);
166       else if (regType == FPDoubleRegType)
167         return (argNo*2 >= NumOfFloatArgRegs)?
168           InvalidRegNum : SparcFloatRegOrder::f0 + (argNo * 2);
169       else
170         assert(0 && "Illegal FP register type");
171     }
172 }
173
174
175 //---------------------------------------------------------------------------
176 // Finds the return address of a call sparc specific call instruction
177 //---------------------------------------------------------------------------
178
179 // The following 4  methods are used to find the RegType (SparcInternals.h)
180 // of a LiveRange, a Value, and for a given register unified reg number.
181 //
182 int UltraSparcRegInfo::getRegType(unsigned regClassID,
183                                   const Type* type) const {
184   switch (regClassID) {
185   case IntRegClassID: return IntRegType; 
186   case FloatRegClassID: {
187     if (type == Type::FloatTy) 
188       return FPSingleRegType;
189     else if (type == Type::DoubleTy)
190       return FPDoubleRegType;
191     assert(0 && "Unknown type in FloatRegClass");
192   }
193   case IntCCRegClassID:   return IntCCRegType; 
194   case FloatCCRegClassID: return FloatCCRegType; 
195   default: assert( 0 && "Unknown reg class ID"); return 0;
196   }
197 }
198
199 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const {
200   return getRegType(LR->getRegClass()->getID(), LR->getType());
201 }
202
203 int UltraSparcRegInfo::getRegType(const Value *Val) const {
204   return getRegType(getRegClassIDOfValue(Val), Val->getType());
205 }
206
207 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const {
208   if (unifiedRegNum < 32) 
209     return IntRegType;
210   else if (unifiedRegNum < (32 + 32))
211     return FPSingleRegType;
212   else if (unifiedRegNum < (64 + 32))
213     return FPDoubleRegType;
214   else if (unifiedRegNum < (64+32+4))
215     return FloatCCRegType;
216   else if (unifiedRegNum < (64+32+4+2))  
217     return IntCCRegType;             
218   else 
219     assert(0 && "Invalid unified register number in getRegType");
220   return 0;
221 }
222
223
224 // To find the register class used for a specified Type
225 //
226 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
227                                                 bool isCCReg = false) const {
228   Type::PrimitiveID ty = type->getPrimitiveID();
229   unsigned res;
230     
231   // FIXME: Comparing types like this isn't very safe...
232   if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
233       (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
234     res = IntRegClassID;             // sparc int reg (ty=0: void)
235   else if (ty <= Type::DoubleTyID)
236     res = FloatRegClassID;           // sparc float reg class
237   else { 
238     //std::cerr << "TypeID: " << ty << "\n";
239     assert(0 && "Cannot resolve register class for type");
240     return 0;
241   }
242   
243   if(isCCReg)
244     return res + 2;      // corresponidng condition code regiser 
245   else 
246     return res;
247 }
248
249 // To find the register class to which a specified register belongs
250 //
251 unsigned UltraSparcRegInfo::getRegClassIDOfReg(int unifiedRegNum) const {
252   unsigned classId = 0;
253   (void) getClassRegNum(unifiedRegNum, classId);
254   return classId;
255 }
256
257 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
258   switch(regType) {
259   case IntRegType:      return IntRegClassID;
260   case FPSingleRegType:
261   case FPDoubleRegType: return FloatRegClassID;
262   case IntCCRegType:    return IntCCRegClassID;
263   case FloatCCRegType:  return FloatCCRegClassID;
264   default:
265     assert(0 && "Invalid register type in getRegClassIDOfRegType");
266     return 0;
267   }
268 }
269
270 //---------------------------------------------------------------------------
271 // Suggests a register for the ret address in the RET machine instruction.
272 // We always suggest %i7 by convention.
273 //---------------------------------------------------------------------------
274 void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI, 
275                                            LiveRangeInfo& LRI) const {
276
277   assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
278   
279   // return address is always mapped to i7 so set it immediately
280   RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
281                                               SparcIntRegOrder::i7));
282   
283   // Possible Optimization: 
284   // Instead of setting the color, we can suggest one. In that case,
285   // we have to test later whether it received the suggested color.
286   // In that case, a LR has to be created at the start of method.
287   // It has to be done as follows (remove the setRegVal above):
288
289   // MachineOperand & MO  = RetMI->getOperand(0);
290   // const Value *RetAddrVal = MO.getVRegValue();
291   // assert( RetAddrVal && "LR for ret address must be created at start");
292   // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
293   // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
294   //                              SparcIntRegOrdr::i7) );
295 }
296
297
298 //---------------------------------------------------------------------------
299 // Suggests a register for the ret address in the JMPL/CALL machine instr.
300 // Sparc ABI dictates that %o7 be used for this purpose.
301 //---------------------------------------------------------------------------
302 void UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
303                                             LiveRangeInfo& LRI,
304                                          std::vector<RegClass *> RCList) const {
305   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
306   const Value *RetAddrVal = argDesc->getReturnAddrReg();
307   assert(RetAddrVal && "Return address value is required");
308   
309   // create a new LR for the return address and color it
310   LiveRange * RetAddrLR = new LiveRange();  
311   RetAddrLR->insert( RetAddrVal );
312   unsigned RegClassID = getRegClassIDOfValue( RetAddrVal );
313   RetAddrLR->setRegClass( RCList[RegClassID] );
314   RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o7));
315   LRI.addLRToMap( RetAddrVal, RetAddrLR);
316   
317 }
318
319
320
321
322 //---------------------------------------------------------------------------
323 //  This method will suggest colors to incoming args to a method. 
324 //  According to the Sparc ABI, the first 6 incoming args are in 
325 //  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
326 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
327 //  done - it will be colored (or spilled) as a normal live range.
328 //---------------------------------------------------------------------------
329 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth, 
330                                                LiveRangeInfo& LRI) const 
331 {
332   // check if this is a varArgs function. needed for choosing regs.
333   bool isVarArgs = isVarArgsFunction(Meth->getType());
334   
335   // for each argument.  count INT and FP arguments separately.
336   unsigned argNo=0, intArgNo=0, fpArgNo=0;
337   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
338       I != E; ++I, ++argNo) {
339     // get the LR of arg
340     LiveRange *LR = LRI.getLiveRangeForValue(I);
341     assert(LR && "No live range found for method arg");
342     
343     unsigned regType = getRegType(LR);
344     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
345     
346     int regNum = (regType == IntRegType)
347       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
348                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
349       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
350                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
351     
352     if(regNum != InvalidRegNum)
353       LR->setSuggestedColor(regNum);
354   }
355 }
356
357
358 //---------------------------------------------------------------------------
359 // This method is called after graph coloring to move incoming args to
360 // the correct hardware registers if they did not receive the correct
361 // (suggested) color through graph coloring.
362 //---------------------------------------------------------------------------
363 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth, 
364                                         LiveRangeInfo &LRI,
365                                         AddedInstrns *FirstAI) const {
366
367   // check if this is a varArgs function. needed for choosing regs.
368   bool isVarArgs = isVarArgsFunction(Meth->getType());
369   MachineInstr *AdMI;
370
371   // for each argument
372   // for each argument.  count INT and FP arguments separately.
373   unsigned argNo=0, intArgNo=0, fpArgNo=0;
374   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
375       I != E; ++I, ++argNo) {
376     // get the LR of arg
377     LiveRange *LR = LRI.getLiveRangeForValue(I);
378     assert( LR && "No live range found for method arg");
379
380     unsigned regType = getRegType( LR );
381     unsigned RegClassID = (LR->getRegClass())->getID();
382     
383     // Find whether this argument is coming in a register (if not, on stack)
384     // Also find the correct register the argument must use (UniArgReg)
385     //
386     bool isArgInReg = false;
387     unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
388     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
389     
390     int regNum = (regType == IntRegType)
391       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
392                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
393       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
394                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
395     
396     if(regNum != InvalidRegNum) {
397       isArgInReg = true;
398       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
399     }
400     
401     if( LR->hasColor() ) {              // if this arg received a register
402
403       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
404
405       // if LR received the correct color, nothing to do
406       //
407       if( UniLRReg == UniArgReg )
408         continue;
409
410       // We are here because the LR did not receive the suggested 
411       // but LR received another register.
412       // Now we have to copy the %i reg (or stack pos of arg) 
413       // to the register the LR was colored with.
414       
415       // if the arg is coming in UniArgReg register, it MUST go into
416       // the UniLRReg register
417       //
418       if( isArgInReg ) {
419         if( regClassIDOfArgReg != RegClassID ) {
420           assert(0 && "This could should work but it is not tested yet");
421           
422           // It is a variable argument call: the float reg must go in a %o reg.
423           // We have to move an int reg to a float reg via memory.
424           // 
425           assert(isVarArgs &&
426                  RegClassID == FloatRegClassID && 
427                  regClassIDOfArgReg == IntRegClassID &&
428                  "This should only be an Int register for an FP argument");
429           
430           int TmpOff = MachineCodeForMethod::get(Meth).pushTempValue(target,  
431                                                 getSpilledRegSize(regType));
432           cpReg2MemMI(FirstAI->InstrnsBefore,
433                       UniArgReg, getFramePointer(), TmpOff, IntRegType);
434           
435           cpMem2RegMI(FirstAI->InstrnsBefore,
436                       getFramePointer(), TmpOff, UniLRReg, regType);
437         }
438         else {  
439           cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
440         }
441       }
442       else {
443
444         // Now the arg is coming on stack. Since the LR recieved a register,
445         // we just have to load the arg on stack into that register
446         //
447         const MachineFrameInfo& frameInfo = target.getFrameInfo();
448         int offsetFromFP =
449           frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
450                                          argNo);
451         
452         cpMem2RegMI(FirstAI->InstrnsBefore,
453                     getFramePointer(), offsetFromFP, UniLRReg, regType);
454       }
455       
456     } // if LR received a color
457
458     else {                             
459
460       // Now, the LR did not receive a color. But it has a stack offset for
461       // spilling.
462       // So, if the arg is coming in UniArgReg register,  we can just move
463       // that on to the stack pos of LR
464
465       if( isArgInReg ) {
466         
467         if( regClassIDOfArgReg != RegClassID ) {
468           assert(0 &&
469                  "FP arguments to a varargs function should be explicitly "
470                  "copied to/from int registers by instruction selection!");
471           
472           // It must be a float arg for a variable argument call, which
473           // must come in a %o reg.  Move the int reg to the stack.
474           // 
475           assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
476                  "This should only be an Int register for an FP argument");
477           
478           cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
479                       getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
480         }
481         else {
482            cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
483                        getFramePointer(), LR->getSpillOffFromFP(), regType);
484         }
485       }
486
487       else {
488
489         // Now the arg is coming on stack. Since the LR did NOT 
490         // recieved a register as well, it is allocated a stack position. We
491         // can simply change the stack position of the LR. We can do this,
492         // since this method is called before any other method that makes
493         // uses of the stack pos of the LR (e.g., updateMachineInstr)
494
495         const MachineFrameInfo& frameInfo = target.getFrameInfo();
496         int offsetFromFP =
497           frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
498                                          argNo);
499         
500         LR->modifySpillOffFromFP( offsetFromFP );
501       }
502
503     }
504
505   }  // for each incoming argument
506
507 }
508
509
510
511 //---------------------------------------------------------------------------
512 // This method is called before graph coloring to suggest colors to the
513 // outgoing call args and the return value of the call.
514 //---------------------------------------------------------------------------
515 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI, 
516                                              LiveRangeInfo& LRI,
517                                          std::vector<RegClass *> RCList) const {
518   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
519
520   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
521   
522   suggestReg4CallAddr(CallMI, LRI, RCList);
523
524   // First color the return value of the call instruction. The return value
525   // will be in %o0 if the value is an integer type, or in %f0 if the 
526   // value is a float type.
527
528   // the return value cannot have a LR in machine instruction since it is
529   // only defined by the call instruction
530
531   // if type is not void,  create a new live range and set its 
532   // register class and add to LRI
533
534   const Value *RetVal = argDesc->getReturnValue();
535
536   if (RetVal) {
537     assert ((!LRI.getLiveRangeForValue(RetVal)) && 
538             "LR for ret Value of call already definded!");
539
540     // create a new LR for the return value
541     LiveRange *RetValLR = new LiveRange();  
542     RetValLR->insert(RetVal);
543     unsigned RegClassID = getRegClassIDOfValue(RetVal);
544     RetValLR->setRegClass(RCList[RegClassID]);
545     LRI.addLRToMap(RetVal, RetValLR);
546     
547     // now suggest a register depending on the register class of ret arg
548
549     if( RegClassID == IntRegClassID ) 
550       RetValLR->setSuggestedColor(SparcIntRegOrder::o0);
551     else if (RegClassID == FloatRegClassID ) 
552       RetValLR->setSuggestedColor(SparcFloatRegOrder::f0 );
553     else assert( 0 && "Unknown reg class for return value of call\n");
554   }
555
556   
557   // Now suggest colors for arguments (operands) of the call instruction.
558   // Colors are suggested only if the arg number is smaller than the
559   // the number of registers allocated for argument passing.
560   // Now, go thru call args - implicit operands of the call MI
561
562   unsigned NumOfCallArgs = argDesc->getNumArgs();
563   
564   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
565        i < NumOfCallArgs; ++i, ++argNo) {    
566
567     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
568     
569     // get the LR of call operand (parameter)
570     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
571     
572     // not possible to have a null LR since all args (even consts)  
573     // must be defined before
574     if (!LR) {          
575       cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) << "\n";
576       assert(0 && "NO LR for call arg");  
577     }
578     
579     unsigned regType = getRegType( LR );
580     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
581     
582     // Choose a register for this arg depending on whether it is
583     // an INT or FP value.  Here we ignore whether or not it is a
584     // varargs calls, because FP arguments will be explicitly copied
585     // to an integer Value and handled under (argCopy != NULL) below.
586     int regNum = (regType == IntRegType)
587       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
588                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
589       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
590                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
591     
592     // If a register could be allocated, use it.
593     // If not, do NOTHING as this will be colored as a normal value.
594     if(regNum != InvalidRegNum)
595       LR->setSuggestedColor(regNum);
596     
597     // Repeat for the second copy of the argument, which would be
598     // an FP argument being passed to a function with no prototype
599     const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
600     if (argCopy != NULL)
601       {
602         assert(regType != IntRegType && argCopy->getType()->isIntegral()
603                && "Must be passing copy of FP argument in int register");
604         int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
605                                          argNo, intArgNo, fpArgNo-1,
606                                          regClassIDOfArgReg);
607         assert(copyRegNum != InvalidRegNum); 
608         LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy); 
609         copyLR->setSuggestedColor(copyRegNum);
610       }
611     
612   } // for all call arguments
613
614 }
615
616
617 //---------------------------------------------------------------------------
618 // Helper method for UltraSparcRegInfo::colorCallArgs().
619 //---------------------------------------------------------------------------
620     
621 void
622 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
623                              AddedInstrns *CallAI,
624                              PhyRegAlloc &PRA, LiveRange* LR,
625                              unsigned regType, unsigned RegClassID,
626                              int UniArgRegOrNone, unsigned int argNo,
627                              std::vector<MachineInstr *>& AddedInstrnsBefore)
628   const
629 {
630   MachineInstr *AdMI;
631   bool isArgInReg = false;
632   unsigned UniArgReg = MAXINT;          // unused unless initialized below
633   if (UniArgRegOrNone != InvalidRegNum)
634     {
635       isArgInReg = true;
636       UniArgReg = (unsigned) UniArgRegOrNone;
637       CallMI->getRegsUsed().insert(UniArgReg); // mark the reg as used
638     }
639   
640   if (LR->hasColor()) {
641     unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
642     
643     // if LR received the correct color, nothing to do
644     if( isArgInReg && UniArgReg == UniLRReg )
645       return;
646     
647     // The LR is allocated to a register UniLRReg and must be copied
648     // to UniArgReg or to the stack slot.
649     // 
650     if( isArgInReg ) {
651       // Copy UniLRReg to UniArgReg
652       cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
653     }
654     else {
655       // Copy UniLRReg to the stack to pass the arg on stack.
656       const MachineFrameInfo& frameInfo = target.getFrameInfo();
657       int argOffset = frameInfo.getOutgoingArgOffset(PRA.mcInfo, argNo);
658       cpReg2MemMI(CallAI->InstrnsBefore,
659                   UniLRReg, getStackPointer(), argOffset, regType);
660     }
661
662   } else {                          // LR is not colored (i.e., spilled)      
663     
664     if( isArgInReg ) {
665       // Insert a load instruction to load the LR to UniArgReg
666       cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
667                   LR->getSpillOffFromFP(), UniArgReg, regType);
668                                         // Now add the instruction
669     }
670       
671     else {
672       // Now, we have to pass the arg on stack. Since LR  also did NOT
673       // receive a register we have to move an argument in memory to 
674       // outgoing parameter on stack.
675       // Use TReg to load and store the value.
676       // Use TmpOff to save TReg, since that may have a live value.
677       // 
678       int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
679       int TmpOff = PRA.mcInfo.pushTempValue(target,  
680                                             getSpilledRegSize(getRegType(LR)));
681       const MachineFrameInfo& frameInfo = target.getFrameInfo();
682       int argOffset = frameInfo.getOutgoingArgOffset(PRA.mcInfo, argNo);
683       
684       MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
685         
686       // Sequence:
687       // (1) Save TReg on stack    
688       // (2) Load LR value into TReg from stack pos of LR
689       // (3) Store Treg on outgoing Arg pos on stack
690       // (4) Load the old value of TReg from stack to TReg (restore it)
691       // 
692       // OPTIMIZE THIS:
693       // When reverse pointers in MahineInstr are introduced: 
694       // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
695       // needed only if this fails. Currently, we cannot call the
696       // above method since we cannot find LVSetBefore without the BB 
697       // 
698       // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
699       // AddedInstrnsBefore since these instructions must not be reordered.
700       cpReg2MemMI(CallAI->InstrnsBefore,
701                   TReg, getFramePointer(), TmpOff, regType);
702       cpMem2RegMI(CallAI->InstrnsBefore,
703                   getFramePointer(), LR->getSpillOffFromFP(), TReg, regType); 
704       cpReg2MemMI(CallAI->InstrnsBefore,
705                   TReg, getStackPointer(), argOffset, regType);
706       cpMem2RegMI(CallAI->InstrnsBefore,
707                   getFramePointer(), TmpOff, TReg, regType); 
708     }
709   }
710 }
711
712 //---------------------------------------------------------------------------
713 // After graph coloring, we have call this method to see whehter the return
714 // value and the call args received the correct colors. If not, we have
715 // to instert copy instructions.
716 //---------------------------------------------------------------------------
717
718 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
719                                       LiveRangeInfo &LRI,
720                                       AddedInstrns *CallAI,
721                                       PhyRegAlloc &PRA,
722                                       const BasicBlock *BB) const {
723
724   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
725
726   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
727   
728   // First color the return value of the call.
729   // If there is a LR for the return value, it means this
730   // method returns a value
731   
732   MachineInstr *AdMI;
733
734   const Value *RetVal = argDesc->getReturnValue();
735
736   if (RetVal) {
737     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
738
739     if (!RetValLR) {
740       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
741       assert(RetValLR && "ERR:No LR for non-void return value");
742     }
743
744     unsigned RegClassID = (RetValLR->getRegClass())->getID();    
745     bool recvCorrectColor = false;
746
747     unsigned CorrectCol;                // correct color for ret value
748     if(RegClassID == IntRegClassID)
749       CorrectCol = SparcIntRegOrder::o0;
750     else if(RegClassID == FloatRegClassID)
751       CorrectCol = SparcFloatRegOrder::f0;
752     else {
753       assert( 0 && "Unknown RegClass");
754       return;
755     }
756
757     // Mark the register as used by this instruction
758     CallMI->getRegsUsed().insert(this->getUnifiedRegNum(RegClassID,CorrectCol));
759     
760     // if the LR received the correct color, NOTHING to do
761     if(  RetValLR->hasColor() )
762       if( RetValLR->getColor() == CorrectCol )
763         recvCorrectColor = true;
764
765     // if we didn't receive the correct color for some reason, 
766     // put copy instruction
767     if( !recvCorrectColor ) {
768
769       unsigned regType = getRegType( RetValLR );
770
771       // the  reg that LR must be colored with 
772       unsigned UniRetReg = getUnifiedRegNum( RegClassID, CorrectCol);   
773       
774       if( RetValLR->hasColor() ) {
775         
776         unsigned 
777           UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
778         
779         // the return value is coming in UniRetReg but has to go into
780         // the UniRetLRReg
781
782         cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
783
784       } // if LR has color
785       else {
786
787         // if the LR did NOT receive a color, we have to move the return
788         // value coming in UniRetReg to the stack pos of spilled LR
789         
790         cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
791                     getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
792       }
793
794     } // the LR didn't receive the suggested color  
795     
796   } // if there a return value
797   
798
799   //-------------------------------------------
800   // Now color all args of the call instruction
801   //-------------------------------------------
802
803   std::vector<MachineInstr *> AddedInstrnsBefore;
804   
805   unsigned NumOfCallArgs = argDesc->getNumArgs();
806   
807   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
808       i < NumOfCallArgs; ++i, ++argNo) {    
809
810     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
811     
812     // get the LR of call operand (parameter)
813     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
814
815     unsigned RegClassID = getRegClassIDOfValue( CallArg);
816     unsigned regType = getRegType( RegClassID, CallArg->getType() );
817     
818     // Find whether this argument is coming in a register (if not, on stack)
819     // Also find the correct register the argument must use (UniArgReg)
820     //
821     bool isArgInReg = false;
822     unsigned UniArgReg = InvalidRegNum;   // reg that LR MUST be colored with
823     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
824     
825     // Find the register that must be used for this arg, depending on
826     // whether it is an INT or FP value.  Here we ignore whether or not it
827     // is a varargs calls, because FP arguments will be explicitly copied
828     // to an integer Value and handled under (argCopy != NULL) below.
829     int regNum = (regType == IntRegType)
830       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
831                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
832       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
833                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
834     
835     if(regNum != InvalidRegNum) {
836       isArgInReg = true;
837       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
838       assert(regClassIDOfArgReg == RegClassID &&
839              "Moving values between reg classes must happen during selection");
840     }
841     
842     // not possible to have a null LR since all args (even consts)  
843     // must be defined before
844     if (!LR) {          
845       cerr << " ERROR: In call instr, no LR for arg:  " << RAV(CallArg) <<"\n";
846       assert(LR && "NO LR for call arg");  
847     }
848     
849     InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
850                           UniArgReg, argNo, AddedInstrnsBefore);
851     
852     // Repeat for the second copy of the argument, which would be
853     // an FP argument being passed to a function with no prototype.
854     const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
855     if (argCopy != NULL)
856       {
857         assert(regType != IntRegType && argCopy->getType()->isIntegral()
858                && "Must be passing copy of FP argument in int register");
859         
860         unsigned copyRegClassID = getRegClassIDOfValue(argCopy);
861         unsigned copyRegType = getRegType(copyRegClassID, argCopy->getType());
862         
863         int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
864                                          argNo, intArgNo, fpArgNo-1,
865                                          regClassIDOfArgReg);
866         assert(copyRegNum != InvalidRegNum); 
867         assert(regClassIDOfArgReg == copyRegClassID &&
868            "Moving values between reg classes must happen during selection");
869         
870         InitializeOutgoingArg(CallMI, CallAI, PRA,
871                               LRI.getLiveRangeForValue(argCopy), copyRegType,
872                               copyRegClassID, copyRegNum, argNo,
873                               AddedInstrnsBefore);
874       }
875   }  // for each parameter in call instruction
876
877   // If we added any instruction before the call instruction, verify
878   // that they are in the proper order and if not, reorder them
879   // 
880   if (!AddedInstrnsBefore.empty()) {
881
882     if (DEBUG_RA) {
883       cerr << "\nCalling reorder with instrns: \n";
884       for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
885         cerr  << *(AddedInstrnsBefore[i]);
886     }
887
888     std::vector<MachineInstr *> TmpVec;
889     OrderAddedInstrns(AddedInstrnsBefore, TmpVec, PRA);
890
891     if (DEBUG_RA) {
892       cerr << "\nAfter reordering instrns: \n";
893       for(unsigned i = 0; i < TmpVec.size(); i++)
894         cerr << *TmpVec[i];
895     }
896
897     // copy the results back from TmpVec to InstrnsBefore
898     for(unsigned i=0; i < TmpVec.size(); i++)
899       CallAI->InstrnsBefore.push_back( TmpVec[i] );
900   }
901   
902   // now insert caller saving code for this call instruction
903   //
904   insertCallerSavingCode(CallMI, BB, PRA);
905 }
906
907 //---------------------------------------------------------------------------
908 // This method is called for an LLVM return instruction to identify which
909 // values will be returned from this method and to suggest colors.
910 //---------------------------------------------------------------------------
911 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI, 
912                                             LiveRangeInfo &LRI) const {
913
914   assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
915
916   suggestReg4RetAddr(RetMI, LRI);
917
918   // if there is an implicit ref, that has to be the ret value
919   if(  RetMI->getNumImplicitRefs() > 0 ) {
920
921     // The first implicit operand is the return value of a return instr
922     const Value *RetVal =  RetMI->getImplicitRef(0);
923
924     LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
925
926     if (!LR) {
927       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
928       assert(0 && "No LR for return value of non-void method");
929     }
930
931     unsigned RegClassID = (LR->getRegClass())->getID();
932       
933     if (RegClassID == IntRegClassID) 
934       LR->setSuggestedColor(SparcIntRegOrder::i0);
935     else if (RegClassID == FloatRegClassID) 
936       LR->setSuggestedColor(SparcFloatRegOrder::f0);
937   }
938 }
939
940
941
942 //---------------------------------------------------------------------------
943 // Colors the return value of a method to %i0 or %f0, if possible. If it is
944 // not possilbe to directly color the LR, insert a copy instruction to move
945 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we 
946 // have to put a load instruction.
947 //---------------------------------------------------------------------------
948 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI, 
949                                       LiveRangeInfo &LRI,
950                                       AddedInstrns *RetAI) const {
951
952   assert((UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode()));
953
954   // if there is an implicit ref, that has to be the ret value
955   if(RetMI->getNumImplicitRefs() > 0) {
956
957     // The first implicit operand is the return value of a return instr
958     const Value *RetVal =  RetMI->getImplicitRef(0);
959
960     LiveRange *LR = LRI.getLiveRangeForValue(RetVal); 
961
962     if (!LR) {
963       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
964       // assert( LR && "No LR for return value of non-void method");
965       return;
966     }
967
968     unsigned RegClassID =  getRegClassIDOfValue(RetVal);
969     unsigned regType = getRegType( RetVal );
970
971     unsigned CorrectCol;
972     if(RegClassID == IntRegClassID)
973       CorrectCol = SparcIntRegOrder::i0;
974     else if(RegClassID == FloatRegClassID)
975       CorrectCol = SparcFloatRegOrder::f0;
976     else {
977       assert (0 && "Unknown RegClass");
978       return;
979     }
980
981     // Mark the register as used by this instruction
982     RetMI->getRegsUsed().insert(this->getUnifiedRegNum(RegClassID, CorrectCol));
983     
984     // if the LR received the correct color, NOTHING to do
985
986     if (LR->hasColor() && LR->getColor() == CorrectCol)
987       return;
988
989     unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
990
991     if (LR->hasColor()) {
992
993       // We are here because the LR was allocted a regiter
994       // It may be the suggested register or not
995
996       // copy the LR of retun value to i0 or f0
997
998       unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
999
1000       // the LR received  UniLRReg but must be colored with UniRetReg
1001       // to pass as the return value
1002       cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1003     }
1004     else {                              // if the LR is spilled
1005       cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1006                   LR->getSpillOffFromFP(), UniRetReg, regType);
1007       cerr << "\nCopied the return value from stack\n";
1008     }
1009   
1010   } // if there is a return value
1011
1012 }
1013
1014 //---------------------------------------------------------------------------
1015 // Check if a specified register type needs a scratch register to be
1016 // copied to/from memory.  If it does, the reg. type that must be used
1017 // for scratch registers is returned in scratchRegType.
1018 //
1019 // Only the int CC register needs such a scratch register.
1020 // The FP CC registers can (and must) be copied directly to/from memory.
1021 //---------------------------------------------------------------------------
1022
1023 bool
1024 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1025                                           int& scratchRegType) const
1026 {
1027   if (RegType == IntCCRegType)
1028     {
1029       scratchRegType = IntRegType;
1030       return true;
1031     }
1032   return false;
1033 }
1034
1035 //---------------------------------------------------------------------------
1036 // Copy from a register to register. Register number must be the unified
1037 // register number.
1038 //---------------------------------------------------------------------------
1039
1040 void
1041 UltraSparcRegInfo::cpReg2RegMI(vector<MachineInstr*>& mvec,
1042                                unsigned SrcReg,
1043                                unsigned DestReg,
1044                                int RegType) const {
1045   assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1046           "Invalid Register");
1047   
1048   MachineInstr * MI = NULL;
1049   
1050   switch( RegType ) {
1051     
1052   case IntCCRegType:
1053     if (this->getRegType(DestReg) == IntRegType)
1054       { // copy intCC reg to int reg
1055         // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1056         MI = Create2OperandInstr_Reg(RDCCR, SrcReg+1, DestReg);
1057       }
1058     else 
1059       { // copy int reg to intCC reg
1060         // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1061         assert(this->getRegType(SrcReg) == IntRegType
1062                && "Can only copy CC reg to/from integer reg");
1063         MI = Create2OperandInstr_Reg(WRCCR, SrcReg, DestReg+1);
1064       }
1065     break;
1066     
1067   case FloatCCRegType: 
1068     assert(0 && "Cannot copy FPCC register to any other register");
1069     break;
1070     
1071   case IntRegType:
1072     MI = Create3OperandInstr_Reg(ADD, SrcReg, this->getZeroRegNum(), DestReg);
1073     break;
1074     
1075   case FPSingleRegType:
1076     MI = Create2OperandInstr_Reg(FMOVS, SrcReg, DestReg);
1077     break;
1078
1079   case FPDoubleRegType:
1080     MI = Create2OperandInstr_Reg(FMOVD, SrcReg, DestReg);
1081     break;
1082
1083   default:
1084     assert(0 && "Unknown RegType");
1085     break;
1086   }
1087   
1088   if (MI)
1089     mvec.push_back(MI);
1090 }
1091
1092 //---------------------------------------------------------------------------
1093 // Copy from a register to memory (i.e., Store). Register number must 
1094 // be the unified register number
1095 //---------------------------------------------------------------------------
1096
1097
1098 void
1099 UltraSparcRegInfo::cpReg2MemMI(vector<MachineInstr*>& mvec,
1100                                unsigned SrcReg, 
1101                                unsigned DestPtrReg,
1102                                int Offset, int RegType,
1103                                int scratchReg = -1) const {
1104   MachineInstr * MI = NULL;
1105   switch( RegType ) {
1106   case IntRegType:
1107     MI = new MachineInstr(STX, 3);
1108     MI->SetMachineOperandReg(0, SrcReg, false);
1109     MI->SetMachineOperandReg(1, DestPtrReg, false);
1110     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1111                                (int64_t) Offset);
1112     mvec.push_back(MI);
1113     break;
1114
1115   case FPSingleRegType:
1116     MI = new MachineInstr(ST, 3);
1117     MI->SetMachineOperandReg(0, SrcReg, false);
1118     MI->SetMachineOperandReg(1, DestPtrReg, false);
1119     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1120                                (int64_t) Offset);
1121     mvec.push_back(MI);
1122     break;
1123
1124   case FPDoubleRegType:
1125     MI = new MachineInstr(STD, 3);
1126     MI->SetMachineOperandReg(0, SrcReg, false);
1127     MI->SetMachineOperandReg(1, DestPtrReg, false);
1128     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1129                                (int64_t) Offset);
1130     mvec.push_back(MI);
1131     break;
1132
1133   case IntCCRegType:
1134     assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1135     assert(this->getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1136     
1137     // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1138     MI = Create2OperandInstr_Reg(RDCCR, SrcReg+1, scratchReg);
1139     mvec.push_back(MI);
1140     
1141     this->cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1142     break;
1143     
1144   case FloatCCRegType: 
1145     assert(0 && "Tell Vikram if this assertion fails: we may have to mask out the other bits here");
1146     MI = new MachineInstr(STXFSR, 3);
1147     MI->SetMachineOperandReg(0, SrcReg, false);
1148     MI->SetMachineOperandReg(1, DestPtrReg, false);
1149     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1150                                (int64_t) Offset);
1151     mvec.push_back(MI);
1152     break;
1153     
1154   default:
1155     assert(0 && "Unknown RegType in cpReg2MemMI");
1156   }
1157 }
1158
1159
1160 //---------------------------------------------------------------------------
1161 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1162 // register number
1163 //---------------------------------------------------------------------------
1164
1165
1166 void
1167 UltraSparcRegInfo::cpMem2RegMI(vector<MachineInstr*>& mvec,
1168                                unsigned SrcPtrReg,      
1169                                int Offset,
1170                                unsigned DestReg,
1171                                int RegType,
1172                                int scratchReg = -1) const {
1173   MachineInstr * MI = NULL;
1174   switch (RegType) {
1175   case IntRegType:
1176     MI = new MachineInstr(LDX, 3);
1177     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1178     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1179                                (int64_t) Offset);
1180     MI->SetMachineOperandReg(2, DestReg, true);
1181     mvec.push_back(MI);
1182     break;
1183
1184   case FPSingleRegType:
1185     MI = new MachineInstr(LD, 3);
1186     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1187     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1188                                (int64_t) Offset);
1189     MI->SetMachineOperandReg(2, DestReg, true);
1190     mvec.push_back(MI);
1191     break;
1192
1193   case FPDoubleRegType:
1194     MI = new MachineInstr(LDD, 3);
1195     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1196     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1197                                (int64_t) Offset);
1198     MI->SetMachineOperandReg(2, DestReg, true);
1199     mvec.push_back(MI);
1200     break;
1201
1202   case IntCCRegType:
1203     assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1204     assert(this->getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1205     this->cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1206     
1207     // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1208     MI = Create2OperandInstr_Reg(WRCCR, scratchReg, DestReg+1);
1209     mvec.push_back(MI);
1210
1211     break;
1212     
1213   case FloatCCRegType: 
1214     assert(0 && "Tell Vikram if this assertion fails: we may have to mask out the other bits here");
1215     MI = new MachineInstr(LDXFSR, 3);
1216     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1217     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1218                                (int64_t) Offset);
1219     MI->SetMachineOperandReg(2, DestReg, true);
1220     mvec.push_back(MI);
1221     break;
1222
1223   default:
1224     assert(0 && "Unknown RegType in cpMem2RegMI");
1225   }
1226 }
1227
1228
1229 //---------------------------------------------------------------------------
1230 // Generate a copy instruction to copy a value to another. Temporarily
1231 // used by PhiElimination code.
1232 //---------------------------------------------------------------------------
1233
1234
1235 void
1236 UltraSparcRegInfo::cpValue2Value(Value *Src,
1237                                  Value *Dest,
1238                                  vector<MachineInstr*>& mvec) const {
1239   int RegType = getRegType( Src );
1240
1241   assert( (RegType==getRegType(Src))  && "Src & Dest are diff types");
1242
1243   MachineInstr * MI = NULL;
1244
1245   switch( RegType ) {
1246   case IntRegType:
1247     MI = new MachineInstr(ADD, 3);
1248     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1249     MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1250     MI->SetMachineOperandVal(2, MachineOperand:: MO_VirtualRegister, Dest, true);
1251     break;
1252
1253   case FPSingleRegType:
1254     MI = new MachineInstr(FMOVS, 2);
1255     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1256     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1257     break;
1258
1259
1260   case FPDoubleRegType:
1261     MI = new MachineInstr(FMOVD, 2);
1262     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1263     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1264     break;
1265
1266   default:
1267     assert(0 && "Unknow RegType in CpValu2Value");
1268   }
1269
1270   if (MI)
1271     mvec.push_back(MI);
1272 }
1273
1274
1275
1276
1277
1278
1279 //----------------------------------------------------------------------------
1280 // This method inserts caller saving/restoring instructons before/after
1281 // a call machine instruction. The caller saving/restoring instructions are
1282 // inserted like:
1283 //
1284 //    ** caller saving instructions
1285 //    other instructions inserted for the call by ColorCallArg
1286 //    CALL instruction
1287 //    other instructions inserted for the call ColorCallArg
1288 //    ** caller restoring instructions
1289 //
1290 //----------------------------------------------------------------------------
1291
1292
1293 void UltraSparcRegInfo::insertCallerSavingCode(MachineInstr *CallMI, 
1294                                                const BasicBlock *BB,
1295                                                PhyRegAlloc &PRA) const {
1296
1297   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
1298   
1299   // has set to record which registers were saved/restored
1300   //
1301   std::hash_set<unsigned> PushedRegSet;
1302
1303   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1304   
1305   // Now find the LR of the return value of the call
1306   // The last *implicit operand* is the return value of a call
1307   // Insert it to to he PushedRegSet since we must not save that register
1308   // and restore it after the call.
1309   // We do this because, we look at the LV set *after* the instruction
1310   // to determine, which LRs must be saved across calls. The return value
1311   // of the call is live in this set - but we must not save/restore it.
1312
1313   const Value *RetVal = argDesc->getReturnValue();
1314
1315   if (RetVal) {
1316     LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1317     assert(RetValLR && "No LR for RetValue of call");
1318
1319     if (RetValLR->hasColor())
1320       PushedRegSet.insert(
1321          getUnifiedRegNum((RetValLR->getRegClass())->getID(), 
1322                                       RetValLR->getColor() ) );
1323   }
1324
1325
1326   const ValueSet &LVSetAft =  PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1327   ValueSet::const_iterator LIt = LVSetAft.begin();
1328
1329   // for each live var in live variable set after machine inst
1330   for( ; LIt != LVSetAft.end(); ++LIt) {
1331
1332    //  get the live range corresponding to live var
1333     LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );    
1334
1335     // LR can be null if it is a const since a const 
1336     // doesn't have a dominating def - see Assumptions above
1337     if( LR )   {  
1338       
1339       if( LR->hasColor() ) {
1340
1341         unsigned RCID = (LR->getRegClass())->getID();
1342         unsigned Color = LR->getColor();
1343
1344         if ( isRegVolatile(RCID, Color) ) {
1345
1346           // if the value is in both LV sets (i.e., live before and after 
1347           // the call machine instruction)
1348           
1349           unsigned Reg = getUnifiedRegNum(RCID, Color);
1350           
1351           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1352             
1353             // if we haven't already pushed that register
1354
1355             unsigned RegType = getRegType( LR );
1356
1357             // Now get two instructions - to push on stack and pop from stack
1358             // and add them to InstrnsBefore and InstrnsAfter of the
1359             // call instruction
1360             // 
1361             int StackOff =  PRA.mcInfo.pushTempValue(target,  
1362                                                getSpilledRegSize(RegType));
1363             
1364             vector<MachineInstr*>& instrnsBefore =
1365               PRA.AddedInstrMap[CallMI].InstrnsBefore;
1366             vector<MachineInstr*>& instrnsAfter =
1367               PRA.AddedInstrMap[CallMI].InstrnsAfter;
1368             
1369             vector<MachineInstr*> AdIBef, AdIAft;
1370             
1371             //---- Insert code for pushing the reg on stack ----------
1372             
1373             // We may need a scratch register to copy the saved value
1374             // to/from memory.  This may itself have to insert code to
1375             // free up a scratch register.  Any such code should go before
1376             // the save code.
1377             int scratchRegType = -1;
1378             int scratchReg = -1;
1379             if (this->regTypeNeedsScratchReg(RegType, scratchRegType))
1380               { // Find a register not live in the LVSet before CallMI
1381                 const ValueSet &LVSetBef =
1382                   PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1383                 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1384                                                    CallMI, AdIBef, AdIAft);
1385                 assert(scratchReg != this->getInvalidRegNum());
1386                 CallMI->getRegsUsed().insert(scratchReg); 
1387               }
1388             
1389             if (AdIBef.size() > 0)
1390               instrnsBefore.insert(instrnsBefore.end(),
1391                                    AdIBef.begin(), AdIBef.end());
1392             
1393             cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1394                         scratchReg);
1395             
1396             if (AdIBef.size() > 0)
1397               instrnsBefore.insert(instrnsBefore.end(),
1398                                    AdIAft.begin(), AdIAft.end());
1399             
1400             //---- Insert code for popping the reg from the stack ----------
1401
1402             // We may need a scratch register to copy the saved value
1403             // from memory.  This may itself have to insert code to
1404             // free up a scratch register.  Any such code should go
1405             // after the save code.
1406             // 
1407             scratchRegType = -1;
1408             scratchReg = -1;
1409             if (this->regTypeNeedsScratchReg(RegType, scratchRegType))
1410               { // Find a register not live in the LVSet after CallMI
1411                 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1412                                                  CallMI, AdIBef, AdIAft);
1413                 assert(scratchReg != this->getInvalidRegNum());
1414                 CallMI->getRegsUsed().insert(scratchReg); 
1415               }
1416             
1417             if (AdIBef.size() > 0)
1418               instrnsAfter.insert(instrnsAfter.end(),
1419                                   AdIBef.begin(), AdIBef.end());
1420             
1421             cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1422                         scratchReg);
1423             
1424             if (AdIAft.size() > 0)
1425               instrnsAfter.insert(instrnsAfter.end(),
1426                                   AdIAft.begin(), AdIAft.end());
1427             
1428             PushedRegSet.insert(Reg);
1429             
1430             if(DEBUG_RA) {
1431               cerr << "\nFor call inst:" << *CallMI;
1432               cerr << " -inserted caller saving instrs: Before:\n\t ";
1433               for_each(instrnsBefore.begin(), instrnsBefore.end(),
1434                        mem_fun(&MachineInstr::dump));
1435               cerr << " -and After:\n\t ";
1436               for_each(instrnsAfter.begin(), instrnsAfter.end(),
1437                        mem_fun(&MachineInstr::dump));
1438             }       
1439           } // if not already pushed
1440
1441         } // if LR has a volatile color
1442         
1443       } // if LR has color
1444
1445     } // if there is a LR for Var
1446     
1447   } // for each value in the LV set after instruction
1448 }
1449
1450
1451 //---------------------------------------------------------------------------
1452 // Print the register assigned to a LR
1453 //---------------------------------------------------------------------------
1454
1455 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1456   unsigned RegClassID = (LR->getRegClass())->getID();
1457   cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1458
1459   if (!LR->hasColor()) {
1460     cerr << " - could not find a color\n";
1461     return;
1462   }
1463   
1464   // if a color is found
1465
1466   cerr << " colored with color "<< LR->getColor();
1467
1468   if (RegClassID == IntRegClassID) {
1469     cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) << "]\n";
1470
1471   } else if (RegClassID == FloatRegClassID) {
1472     cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
1473     if( LR->getType() == Type::DoubleTy)
1474       cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
1475     cerr << "]\n";
1476   }
1477 }
1478
1479 //---------------------------------------------------------------------------
1480 // This method examines instructions inserted by RegAlloc code before a
1481 // machine instruction to detect invalid orders that destroy values before
1482 // they are used. If it detects such conditions, it reorders the instructions.
1483 //
1484 // The unordered instructions come in the UnordVec. These instructions are
1485 // instructions inserted by RegAlloc. All such instruction MUST have 
1486 // their USES BEFORE THE DEFS after reordering.
1487 // 
1488 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1489 // this method is called.
1490 // 
1491 // This method uses two vectors for efficiency in accessing
1492 // 
1493 // Since instructions are inserted in RegAlloc, this assumes that the 
1494 // first operand is the source reg and the last operand is the dest reg.
1495 // It also does not consider operands that are both use and def.
1496 // 
1497 // All the uses are before THE def to a register
1498 //---------------------------------------------------------------------------
1499
1500 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1501                                           std::vector<MachineInstr*> &OrdVec,
1502                                           PhyRegAlloc &PRA) const{
1503
1504   /*
1505     Problem: We can have instructions inserted by RegAlloc like
1506     1. add %ox %g0 %oy
1507     2. add %oy %g0 %oz, where z!=x or z==x
1508
1509     This is wrong since %oy used by 2 is overwritten by 1
1510   
1511     Solution:
1512     We re-order the instructions so that the uses are before the defs
1513
1514     Algorithm:
1515     
1516     do
1517       for each instruction 'DefInst' in the UnOrdVec
1518          for each instruction 'UseInst' that follows the DefInst
1519            if the reg defined by DefInst is used by UseInst
1520              mark DefInst as not movable in this iteration
1521          If DefInst is not marked as not-movable, move DefInst to OrdVec
1522     while all instructions in DefInst are moved to OrdVec
1523     
1524     For moving, we call the move2OrdVec(). It checks whether there is a def
1525     in it for the uses in the instruction to be added to OrdVec. If there
1526     are no preceding defs, it just appends the instruction. If there is a
1527     preceding def, it puts two instructions to save the reg on stack before
1528     the load and puts a restore at use.
1529
1530   */
1531
1532   bool CouldMoveAll;
1533   bool DebugPrint = false;
1534
1535   do {
1536     CouldMoveAll = true;
1537     std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1538
1539     for( ; DefIt !=  UnordVec.end(); ++DefIt ) {
1540
1541       // for each instruction in the UnordVec do ...
1542
1543       MachineInstr *DefInst = *DefIt;
1544
1545       if( DefInst == NULL) continue;
1546
1547       //cerr << "\nInst in UnordVec = " <<  *DefInst;
1548       
1549       // last operand is the def (unless for a store which has no def reg)
1550       MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1551       
1552       if( DefOp.opIsDef() &&  
1553           DefOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1554         
1555         // If the operand in DefInst is a def ...
1556         
1557         bool DefEqUse = false;
1558         
1559         std::vector<MachineInstr *>::iterator UseIt = DefIt;
1560         UseIt++;
1561         
1562         for( ; UseIt !=  UnordVec.end(); ++UseIt ) {
1563
1564           MachineInstr *UseInst = *UseIt;
1565           if( UseInst == NULL) continue;
1566           
1567           // for each inst (UseInst) that is below the DefInst do ...
1568           MachineOperand& UseOp = UseInst->getOperand(0);
1569           
1570           if( ! UseOp.opIsDef() &&  
1571               UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1572             
1573             // if use is a register ...
1574             
1575             if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1576               
1577               // if Def and this use are the same, it means that this use
1578               // is destroyed by a def before it is used
1579               
1580               // cerr << "\nCouldn't move " << *DefInst;
1581
1582               DefEqUse = true;
1583               CouldMoveAll = false;     
1584               DebugPrint = true;
1585               break;
1586             } // if two registers are equal
1587             
1588           } // if use is a register
1589           
1590         }// for all use instructions
1591         
1592         if( ! DefEqUse ) {
1593           
1594           // after examining all the instructions that follow the DefInst
1595           // if there are no dependencies, we can move it to the OrdVec
1596
1597           // cerr << "Moved to Ord: " << *DefInst;
1598
1599           moveInst2OrdVec(OrdVec, DefInst, PRA);
1600
1601           //OrdVec.push_back(DefInst);
1602
1603           // mark the pos of DefInst with NULL to indicate that it is
1604           // empty
1605           *DefIt = NULL;
1606         }
1607     
1608       } // if Def is a machine register
1609       
1610     } // for all instructions in the UnordVec
1611     
1612
1613   } while(!CouldMoveAll);
1614
1615   if (DebugPrint && DEBUG_RA) {
1616     cerr << "\nAdded instructions were reordered to:\n";
1617     for(unsigned int i=0; i < OrdVec.size(); i++)
1618       cerr << *(OrdVec[i]);
1619   }
1620 }
1621
1622
1623
1624
1625
1626 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1627                                         MachineInstr *UnordInst,
1628                                         PhyRegAlloc &PRA) const {
1629   MachineOperand& UseOp = UnordInst->getOperand(0);
1630
1631   if( ! UseOp.opIsDef() &&  
1632       UseOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1633
1634     // for the use of UnordInst, see whether there is a defining instr
1635     // before in the OrdVec
1636     bool DefEqUse = false;
1637
1638     std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1639   
1640     for( ; OrdIt !=  OrdVec.end(); ++OrdIt ) {
1641
1642       MachineInstr *OrdInst = *OrdIt ;
1643
1644       MachineOperand& DefOp = 
1645         OrdInst->getOperand(OrdInst->getNumOperands()-1);
1646
1647       if( DefOp.opIsDef() &&  
1648           DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1649
1650         //cerr << "\nDefining Ord Inst: " <<  *OrdInst;
1651           
1652         if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1653
1654           // we are here because there is a preceding def in the OrdVec 
1655           // for the use in this intr we are going to insert. This
1656           // happened because the original code was like:
1657           // 1. add %ox %g0 %oy
1658           // 2. add %oy %g0 %ox
1659           // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1660           // Now we are processing %ox of 1.
1661           // We have to 
1662               
1663           const int UReg = DefOp.getMachineRegNum();
1664           const int RegType = getRegType(UReg);
1665           MachineInstr *AdIBef, *AdIAft;
1666               
1667           const int StackOff =  PRA.mcInfo.pushTempValue(target,
1668                                          getSpilledRegSize(RegType));
1669           
1670           // Save the UReg (%ox) on stack before it's destroyed
1671           vector<MachineInstr*> mvec;
1672           cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1673           for (vector<MachineInstr*>::iterator MI=mvec.begin(); MI != mvec.end(); ++MI) {
1674             OrdIt = OrdVec.insert(OrdIt, *MI);
1675             ++OrdIt; // OrdIt must still point to current instr we processed
1676           }
1677           
1678           // Load directly into DReg (%oy)
1679           MachineOperand&  DOp=
1680             (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1681           assert(DOp.opIsDef() && "Last operand is not the def");
1682           const int DReg = DOp.getMachineRegNum();
1683           
1684           cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1685             
1686           cerr << "\nFixed CIRCULAR references by reordering";
1687
1688           if( DEBUG_RA ) {
1689             cerr << "\nBefore CIRCULAR Reordering:\n";
1690             cerr << *UnordInst;
1691             cerr << *OrdInst;
1692           
1693             cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1694             for(unsigned i=0; i < OrdVec.size(); i++)
1695               cerr << *(OrdVec[i]);
1696           }
1697           
1698           // Do not copy the UseInst to OrdVec
1699           DefEqUse = true;
1700           break;  
1701           
1702         }// if two registers are equal
1703
1704       } // if Def is a register
1705
1706     } // for each instr in OrdVec
1707
1708     if(!DefEqUse) {  
1709
1710       // We didn't find a def in the OrdVec, so just append this inst
1711       OrdVec.push_back( UnordInst );  
1712       //cerr << "Reordered Inst (Moved Dn): " <<  *UnordInst;
1713     }
1714     
1715   }// if the operand in UnordInst is a use
1716 }