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