* Code Cleanups
[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->insert( 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->insert(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       cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) << "\n";
568       assert(0 && "NO LR for call arg");  
569     }
570     
571     unsigned RegType = getRegType( LR );
572
573     // if the arg is in int class - allocate a reg for an int arg
574     if( RegType == IntRegType ) {
575
576       if( argNo < NumOfIntArgRegs) 
577         LR->setSuggestedColor( SparcIntRegOrder::o0 + argNo );
578
579       else if (DEBUG_RA) 
580         // Do NOTHING as this will be colored as a normal value.
581         cerr << " Regr not suggested for int call arg\n";
582       
583     }
584     else if( RegType == FPSingleRegType &&  (argNo*2 +1)< NumOfFloatArgRegs) 
585       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2 + 1) );
586     
587  
588     else if( RegType == FPDoubleRegType && (argNo*2) < NumOfFloatArgRegs) 
589       LR->setSuggestedColor( SparcFloatRegOrder::f0 + (argNo * 2) ); 
590     
591
592   } // for all call arguments
593
594 }
595
596
597 //---------------------------------------------------------------------------
598 // After graph coloring, we have call this method to see whehter the return
599 // value and the call args received the correct colors. If not, we have
600 // to instert copy instructions.
601 //---------------------------------------------------------------------------
602
603 void UltraSparcRegInfo::colorCallArgs(const MachineInstr *CallMI,
604                                       LiveRangeInfo &LRI,
605                                       AddedInstrns *CallAI,
606                                       PhyRegAlloc &PRA,
607                                       const BasicBlock *BB) const {
608
609   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
610
611   // Reset the optional args area in the stack frame
612   // since that is reused for each call
613   // 
614   PRA.mcInfo.resetOptionalArgs(target);
615   
616   // First color the return value of the call.
617   // If there is a LR for the return value, it means this
618   // method returns a value
619   
620   MachineInstr *AdMI;
621
622   const Value *RetVal = getCallInstRetVal( CallMI );
623
624   if (RetVal) {
625     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
626
627     if (!RetValLR) {
628       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
629       assert(0 && "ERR:No LR for non-void return value");
630     }
631
632     unsigned RegClassID = (RetValLR->getRegClass())->getID();    
633     bool recvCorrectColor = false;
634
635     unsigned CorrectCol;                // correct color for ret value
636     if(RegClassID == IntRegClassID)
637       CorrectCol = SparcIntRegOrder::o0;
638     else if(RegClassID == FloatRegClassID)
639       CorrectCol = SparcFloatRegOrder::f0;
640     else {
641       assert( 0 && "Unknown RegClass");
642       return;
643     }
644
645     // if the LR received the correct color, NOTHING to do
646
647     if(  RetValLR->hasColor() )
648       if( RetValLR->getColor() == CorrectCol )
649         recvCorrectColor = true;
650
651
652     // if we didn't receive the correct color for some reason, 
653     // put copy instruction
654     
655     if( !recvCorrectColor ) {
656
657       unsigned RegType = getRegType( RetValLR );
658
659       // the  reg that LR must be colored with 
660       unsigned UniRetReg = getUnifiedRegNum( RegClassID, CorrectCol);   
661       
662       if( RetValLR->hasColor() ) {
663         
664         unsigned 
665           UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
666         
667         // the return value is coming in UniRetReg but has to go into
668         // the UniRetLRReg
669
670         AdMI = cpReg2RegMI( UniRetReg, UniRetLRReg, RegType );  
671
672       } // if LR has color
673       else {
674
675         // if the LR did NOT receive a color, we have to move the return
676         // value coming in UniRetReg to the stack pos of spilled LR
677         
678         AdMI =  cpReg2MemMI(UniRetReg, getFramePointer(), 
679                             RetValLR->getSpillOffFromFP(), RegType );
680       }
681
682       CallAI->InstrnsAfter.push_back( AdMI );
683       
684     } // the LR didn't receive the suggested color  
685     
686   } // if there a return value
687   
688
689   //-------------------------------------------
690   // Now color all args of the call instruction
691   //-------------------------------------------
692
693   std::vector<MachineInstr *> AddedInstrnsBefore;
694
695   unsigned NumOfCallArgs =  getCallInstNumArgs( CallMI );
696
697   bool VarArgCall = isVarArgCall( CallMI );
698
699   if(VarArgCall) cerr << "\nVar arg call found!!\n";
700
701   for(unsigned argNo=0, i=0; i < NumOfCallArgs; ++i, ++argNo ) {
702
703     const Value *CallArg = CallMI->getImplicitRef(i);
704
705     // get the LR of call operand (parameter)
706     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
707
708     unsigned RegType = getRegType( CallArg );
709     unsigned RegClassID =  getRegClassIDOfValue( CallArg);
710     
711     // find whether this argument is coming in a register (if not, on stack)
712
713     bool isArgInReg = false;
714     unsigned UniArgReg = InvalidRegNum;  // reg that LR must be colored with
715
716     if( (RegType== IntRegType && argNo <  NumOfIntArgRegs)) {
717       isArgInReg = true;
718       UniArgReg = getUnifiedRegNum(RegClassID, SparcIntRegOrder::o0 + argNo );
719     }
720     else if(RegType == FPSingleRegType && argNo < NumOfFloatArgRegs)  { 
721       isArgInReg = true;
722
723       if( !VarArgCall )
724         UniArgReg = getUnifiedRegNum(RegClassID, 
725                                      SparcFloatRegOrder::f0 + (argNo*2 + 1) );
726       else {                   
727         // a variable argument call - must pass float arg in %o's
728         if( argNo <  NumOfIntArgRegs)
729           UniArgReg=getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o0+argNo);
730         else    
731           isArgInReg = false;
732       }   
733
734     }
735     else if(RegType == FPDoubleRegType && argNo < NumOfFloatArgRegs)  { 
736       isArgInReg = true;
737
738       if( !VarArgCall )
739         UniArgReg =getUnifiedRegNum(RegClassID,SparcFloatRegOrder::f0+argNo*2);
740       else {                   
741         // a variable argument call - must pass float arg in %o's
742         if( argNo <  NumOfIntArgRegs)
743           UniArgReg=getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o0+argNo);
744         else    
745           isArgInReg = false;
746       }   
747     }
748
749     // not possible to have a null LR since all args (even consts)  
750     // must be defined before
751     if (!LR) {          
752       cerr << " ERROR: In call instr, no LR for arg:  " << RAV(CallArg) << "\n";
753       assert(0 && "NO LR for call arg");  
754     }
755
756
757     if (LR->hasColor()) {
758       unsigned UniLRReg = getUnifiedRegNum( RegClassID,  LR->getColor() );
759
760       // if LR received the correct color, nothing to do
761       if( UniLRReg == UniArgReg )
762         continue;
763
764       // We are here because though the LR is allocated a register, it
765       // was not allocated the suggested register. So, we have to copy %ix reg 
766       // (or stack pos of arg) to the register it was colored with
767
768       // the LR is colored with UniLRReg but has to go into  UniArgReg
769       // to pass it as an argument
770
771       if( isArgInReg ) {
772
773         if( VarArgCall && RegClassID == FloatRegClassID ) {
774
775   
776           // for a variable argument call, the float reg must go in a %o reg.
777           // We have to move a float reg to an int reg via memory.
778           // The store instruction will be directly added to  
779           // CallAI->InstrnsBefore since it does not need reordering
780           // 
781           int TmpOff = PRA.mcInfo.pushTempValue(target,  
782                                                getSpilledRegSize(RegType));
783
784           AdMI = cpReg2MemMI(UniLRReg, getFramePointer(), TmpOff, RegType );
785           CallAI->InstrnsBefore.push_back( AdMI ); 
786
787           AdMI = cpMem2RegMI(getFramePointer(), TmpOff, UniArgReg, IntRegType);
788           AddedInstrnsBefore.push_back( AdMI ); 
789         }
790
791         else {  
792           AdMI = cpReg2RegMI(UniLRReg, UniArgReg, RegType );
793           AddedInstrnsBefore.push_back( AdMI ); 
794         }
795
796       } else {
797         // Now, we have to pass the arg on stack. Since LR received a register
798         // we just have to move that register to the stack position where
799         // the argument must be passed
800
801         int argOffset = PRA.mcInfo.allocateOptionalArg(target, LR->getType()); 
802
803         AdMI = cpReg2MemMI(UniLRReg, getStackPointer(), argOffset, RegType );
804
805         // Now add the instruction. We can directly add to
806         // CallAI->InstrnsBefore since we are just saving a reg on stack
807         //
808         CallAI->InstrnsBefore.push_back( AdMI ); 
809
810         //cerr << "\nCaution: Passing a reg on stack";
811       }
812
813
814     } else {                          // LR is not colored (i.e., spilled)      
815       
816       if( isArgInReg ) {
817
818         // Now the LR did NOT recieve a register but has a stack poistion.
819         // Since, the outgoing arg goes in a register we just have to insert
820         // a load instruction to load the LR to outgoing register
821
822         if( VarArgCall && RegClassID == FloatRegClassID ) 
823           AdMI = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
824                              UniArgReg, IntRegType );
825         else
826           AdMI = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
827                              UniArgReg, RegType );
828         
829         cerr << "\nCaution: Loading a spilled val to a reg as a call arg";
830         AddedInstrnsBefore.push_back( AdMI );  // Now add the instruction
831       }
832       
833       else {
834         // Now, we have to pass the arg on stack. Since LR  also did NOT
835         // receive a register we have to move an argument in memory to 
836         // outgoing parameter on stack.
837         
838         // Optoimize: Optimize when reverse pointers in MahineInstr are
839         // introduced. 
840         // call PRA.getUnusedRegAtMI(....) to get an unused reg. Only if this
841         // fails, then use the following code. Currently, we cannot call the
842         // above method since we cannot find LVSetBefore without the BB 
843         
844         int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
845
846         int TmpOff = PRA.mcInfo.pushTempValue(target,  
847                                     getSpilledRegSize(getRegType(LR)) );
848
849         
850         int argOffset = PRA.mcInfo.allocateOptionalArg(target, LR->getType()); 
851         
852         MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
853         
854         // Sequence:
855         // (1) Save TReg on stack    
856         // (2) Load LR value into TReg from stack pos of LR
857         // (3) Store Treg on outgoing Arg pos on stack
858         // (4) Load the old value of TReg from stack to TReg (restore it)
859
860         Ad1 = cpReg2MemMI(TReg, getFramePointer(), TmpOff, RegType );
861         Ad2 = cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(), 
862                           TReg, RegType ); 
863         Ad3 = cpReg2MemMI(TReg, getStackPointer(), argOffset, RegType );
864         Ad4 = cpMem2RegMI(getFramePointer(), TmpOff, TReg, RegType ); 
865
866         // We directly add to CallAI->InstrnsBefore instead of adding to
867         // AddedInstrnsBefore since these instructions must not be
868         // reordered.
869         
870         CallAI->InstrnsBefore.push_back( Ad1 );  
871         CallAI->InstrnsBefore.push_back( Ad2 );  
872         CallAI->InstrnsBefore.push_back( Ad3 );  
873         CallAI->InstrnsBefore.push_back( Ad4 );  
874
875         cerr << "\nCaution: Call arg moved from stack2stack for: " << *CallMI ;
876       }
877     }
878   }  // for each parameter in call instruction
879
880
881   // if we added any instruction before the call instruction, verify
882   // that they are in the proper order and if not, reorder them
883
884   if (!AddedInstrnsBefore.empty()) {
885
886     if (DEBUG_RA) {
887       cerr << "\nCalling reorder with instrns: \n";
888       for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
889         cerr  << *(AddedInstrnsBefore[i]);
890     }
891
892     std::vector<MachineInstr *> TmpVec;
893     OrderAddedInstrns(AddedInstrnsBefore, TmpVec, PRA);
894
895     if (DEBUG_RA) {
896       cerr << "\nAfter reordering instrns: \n";
897       for(unsigned i = 0; i < TmpVec.size(); i++)
898         cerr << *TmpVec[i];
899     }
900
901     // copy the results back from TmpVec to InstrnsBefore
902     for(unsigned i=0; i < TmpVec.size(); i++)
903       CallAI->InstrnsBefore.push_back( TmpVec[i] );
904   }
905
906
907   // now insert caller saving code for this call instruction
908   //
909   insertCallerSavingCode(CallMI, BB, PRA);
910
911   // Reset optional args area again to be safe
912   PRA.mcInfo.resetOptionalArgs(target);
913 }
914
915 //---------------------------------------------------------------------------
916 // This method is called for an LLVM return instruction to identify which
917 // values will be returned from this method and to suggest colors.
918 //---------------------------------------------------------------------------
919 void UltraSparcRegInfo::suggestReg4RetValue(const MachineInstr *RetMI, 
920                                             LiveRangeInfo &LRI) const {
921
922   assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
923
924     suggestReg4RetAddr(RetMI, LRI);
925
926   // if there is an implicit ref, that has to be the ret value
927   if(  RetMI->getNumImplicitRefs() > 0 ) {
928
929     // The first implicit operand is the return value of a return instr
930     const Value *RetVal =  RetMI->getImplicitRef(0);
931
932     LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
933
934     if (!LR) {
935       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
936       assert(0 && "No LR for return value of non-void method");
937     }
938
939     unsigned RegClassID = (LR->getRegClass())->getID();
940       
941     if (RegClassID == IntRegClassID) 
942       LR->setSuggestedColor(SparcIntRegOrder::i0);
943     else if (RegClassID == FloatRegClassID) 
944       LR->setSuggestedColor(SparcFloatRegOrder::f0);
945   }
946 }
947
948
949
950 //---------------------------------------------------------------------------
951 // Colors the return value of a method to %i0 or %f0, if possible. If it is
952 // not possilbe to directly color the LR, insert a copy instruction to move
953 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we 
954 // have to put a load instruction.
955 //---------------------------------------------------------------------------
956 void UltraSparcRegInfo::colorRetValue(const MachineInstr *RetMI, 
957                                       LiveRangeInfo &LRI,
958                                       AddedInstrns *RetAI) const {
959
960   assert((UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode()));
961
962   // if there is an implicit ref, that has to be the ret value
963   if(RetMI->getNumImplicitRefs() > 0) {
964
965     // The first implicit operand is the return value of a return instr
966     const Value *RetVal =  RetMI->getImplicitRef(0);
967
968     LiveRange *LR = LRI.getLiveRangeForValue(RetVal); 
969
970     if (!LR) {
971       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
972       // assert( LR && "No LR for return value of non-void method");
973       return;
974     }
975
976     unsigned RegClassID =  getRegClassIDOfValue(RetVal);
977     unsigned RegType = getRegType( RetVal );
978
979     unsigned CorrectCol;
980     if(RegClassID == IntRegClassID)
981       CorrectCol = SparcIntRegOrder::i0;
982     else if(RegClassID == FloatRegClassID)
983       CorrectCol = SparcFloatRegOrder::f0;
984     else {
985       assert (0 && "Unknown RegClass");
986       return;
987     }
988
989     // if the LR received the correct color, NOTHING to do
990
991     if (LR->hasColor() && LR->getColor() == CorrectCol)
992       return;
993
994     unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
995
996     if (LR->hasColor()) {
997
998       // We are here because the LR was allocted a regiter
999       // It may be the suggested register or not
1000
1001       // copy the LR of retun value to i0 or f0
1002
1003       unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1004
1005       // the LR received  UniLRReg but must be colored with UniRetReg
1006       // to pass as the return value
1007       RetAI->InstrnsBefore.push_back(cpReg2RegMI(UniLRReg, UniRetReg, RegType));
1008     }
1009     else {                              // if the LR is spilled
1010       MachineInstr *AdMI = cpMem2RegMI(getFramePointer(),
1011                                        LR->getSpillOffFromFP(), 
1012                                        UniRetReg, RegType); 
1013       RetAI->InstrnsBefore.push_back(AdMI);
1014       cerr << "\nCopied the return value from stack\n";
1015     }
1016   
1017   } // if there is a return value
1018
1019 }
1020
1021
1022 //---------------------------------------------------------------------------
1023 // Copy from a register to register. Register number must be the unified
1024 // register number
1025 //---------------------------------------------------------------------------
1026
1027 MachineInstr * UltraSparcRegInfo::cpReg2RegMI(unsigned SrcReg, unsigned DestReg,
1028                                               int RegType) const {
1029
1030   assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1031           "Invalid Register");
1032   
1033   MachineInstr * MI = NULL;
1034
1035   switch( RegType ) {
1036     
1037   case IntRegType:
1038   case IntCCRegType:
1039   case FloatCCRegType: 
1040     MI = new MachineInstr(ADD, 3);
1041     MI->SetMachineOperand(0, SrcReg, false);
1042     MI->SetMachineOperand(1, SparcIntRegOrder::g0, false);
1043     MI->SetMachineOperand(2, DestReg, true);
1044     break;
1045
1046   case FPSingleRegType:
1047     MI = new MachineInstr(FMOVS, 2);
1048     MI->SetMachineOperand(0, SrcReg, false);
1049     MI->SetMachineOperand(1, DestReg, true);
1050     break;
1051
1052   case FPDoubleRegType:
1053     MI = new MachineInstr(FMOVD, 2);
1054     MI->SetMachineOperand(0, SrcReg, false);    
1055     MI->SetMachineOperand(1, DestReg, true);
1056     break;
1057
1058   default:
1059     assert(0 && "Unknow RegType");
1060   }
1061
1062   return MI;
1063 }
1064
1065
1066 //---------------------------------------------------------------------------
1067 // Copy from a register to memory (i.e., Store). Register number must 
1068 // be the unified register number
1069 //---------------------------------------------------------------------------
1070
1071
1072 MachineInstr * UltraSparcRegInfo::cpReg2MemMI(unsigned SrcReg, 
1073                                               unsigned DestPtrReg,
1074                                               int Offset, int RegType) const {
1075   MachineInstr * MI = NULL;
1076   switch( RegType ) {
1077   case IntRegType:
1078   case FloatCCRegType: 
1079     MI = new MachineInstr(STX, 3);
1080     MI->SetMachineOperand(0, SrcReg, false);
1081     MI->SetMachineOperand(1, DestPtrReg, false);
1082     MI->SetMachineOperand(2, MachineOperand:: MO_SignExtendedImmed, 
1083                           (int64_t) Offset, false);
1084     break;
1085
1086   case FPSingleRegType:
1087     MI = new MachineInstr(ST, 3);
1088     MI->SetMachineOperand(0, SrcReg, false);
1089     MI->SetMachineOperand(1, DestPtrReg, false);
1090     MI->SetMachineOperand(2, MachineOperand:: MO_SignExtendedImmed, 
1091                           (int64_t) Offset, false);
1092     break;
1093
1094   case FPDoubleRegType:
1095     MI = new MachineInstr(STD, 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 IntCCRegType:
1103     assert( 0 && "Cannot directly store %ccr to memory");
1104     
1105   default:
1106     assert(0 && "Unknow RegType in cpReg2MemMI");
1107   }
1108
1109   return MI;
1110 }
1111
1112
1113 //---------------------------------------------------------------------------
1114 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1115 // register number
1116 //---------------------------------------------------------------------------
1117
1118
1119 MachineInstr * UltraSparcRegInfo::cpMem2RegMI(unsigned SrcPtrReg,       
1120                                               int Offset,
1121                                               unsigned DestReg,
1122                                               int RegType) const {
1123   MachineInstr * MI = NULL;
1124   switch (RegType) {
1125   case IntRegType:
1126   case FloatCCRegType: 
1127     MI = new MachineInstr(LDX, 3);
1128     MI->SetMachineOperand(0, SrcPtrReg, false);
1129     MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
1130                           (int64_t) Offset, false);
1131     MI->SetMachineOperand(2, DestReg, true);
1132     break;
1133
1134   case FPSingleRegType:
1135     MI = new MachineInstr(LD, 3);
1136     MI->SetMachineOperand(0, SrcPtrReg, false);
1137     MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
1138                           (int64_t) Offset, false);
1139     MI->SetMachineOperand(2, DestReg, true);
1140
1141     break;
1142
1143   case FPDoubleRegType:
1144     MI = new MachineInstr(LDD, 3);
1145     MI->SetMachineOperand(0, SrcPtrReg, false);
1146     MI->SetMachineOperand(1, MachineOperand:: MO_SignExtendedImmed, 
1147                           (int64_t) Offset, false);
1148     MI->SetMachineOperand(2, DestReg, true);
1149     break;
1150
1151   case IntCCRegType:
1152     assert( 0 && "Cannot directly load into %ccr from memory");
1153
1154   default:
1155     assert(0 && "Unknown RegType in cpMem2RegMI");
1156   }
1157
1158   return MI;
1159 }
1160
1161
1162
1163
1164
1165 //---------------------------------------------------------------------------
1166 // Generate a copy instruction to copy a value to another. Temporarily
1167 // used by PhiElimination code.
1168 //---------------------------------------------------------------------------
1169
1170
1171 MachineInstr *UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest) const {
1172   int RegType = getRegType( Src );
1173
1174   assert( (RegType==getRegType(Src))  && "Src & Dest are diff types");
1175
1176   MachineInstr * MI = NULL;
1177
1178   switch( RegType ) {
1179   case IntRegType:
1180     MI = new MachineInstr(ADD, 3);
1181     MI->SetMachineOperand(0, MachineOperand:: MO_VirtualRegister, Src, false);
1182     MI->SetMachineOperand(1, SparcIntRegOrder::g0, false);
1183     MI->SetMachineOperand(2, MachineOperand:: MO_VirtualRegister, Dest, true);
1184     break;
1185
1186   case FPSingleRegType:
1187     MI = new MachineInstr(FMOVS, 2);
1188     MI->SetMachineOperand(0, MachineOperand:: MO_VirtualRegister, Src, false);
1189     MI->SetMachineOperand(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1190     break;
1191
1192
1193   case FPDoubleRegType:
1194     MI = new MachineInstr(FMOVD, 2);
1195     MI->SetMachineOperand(0, MachineOperand:: MO_VirtualRegister, Src, false);
1196     MI->SetMachineOperand(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1197     break;
1198
1199   default:
1200     assert(0 && "Unknow RegType in CpValu2Value");
1201   }
1202
1203   return MI;
1204 }
1205
1206
1207
1208
1209
1210
1211 //----------------------------------------------------------------------------
1212 // This method inserts caller saving/restoring instructons before/after
1213 // a call machine instruction. The caller saving/restoring instructions are
1214 // inserted like:
1215 //
1216 //    ** caller saving instructions
1217 //    other instructions inserted for the call by ColorCallArg
1218 //    CALL instruction
1219 //    other instructions inserted for the call ColorCallArg
1220 //    ** caller restoring instructions
1221 //
1222 //----------------------------------------------------------------------------
1223
1224
1225 void UltraSparcRegInfo::insertCallerSavingCode(const MachineInstr *MInst, 
1226                                                const BasicBlock *BB,
1227                                                PhyRegAlloc &PRA) const {
1228
1229   // has set to record which registers were saved/restored
1230   //
1231   std::hash_set<unsigned> PushedRegSet;
1232
1233   // Now find the LR of the return value of the call
1234   // The last *implicit operand* is the return value of a call
1235   // Insert it to to he PushedRegSet since we must not save that register
1236   // and restore it after the call.
1237   // We do this because, we look at the LV set *after* the instruction
1238   // to determine, which LRs must be saved across calls. The return value
1239   // of the call is live in this set - but we must not save/restore it.
1240
1241
1242   const Value *RetVal = getCallInstRetVal( MInst );
1243
1244   if (RetVal) {
1245     LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1246     assert(RetValLR && "No LR for RetValue of call");
1247
1248     if (RetValLR->hasColor())
1249       PushedRegSet.insert(
1250          getUnifiedRegNum((RetValLR->getRegClass())->getID(), 
1251                                       RetValLR->getColor() ) );
1252   }
1253
1254
1255   const LiveVarSet *LVSetAft =  PRA.LVI->getLiveVarSetAfterMInst(MInst, BB);
1256   LiveVarSet::const_iterator LIt = LVSetAft->begin();
1257
1258   // for each live var in live variable set after machine inst
1259   for( ; LIt != LVSetAft->end(); ++LIt) {
1260
1261    //  get the live range corresponding to live var
1262     LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );    
1263
1264     // LR can be null if it is a const since a const 
1265     // doesn't have a dominating def - see Assumptions above
1266     if( LR )   {  
1267       
1268       if( LR->hasColor() ) {
1269
1270         unsigned RCID = (LR->getRegClass())->getID();
1271         unsigned Color = LR->getColor();
1272
1273         if ( isRegVolatile(RCID, Color) ) {
1274
1275           // if the value is in both LV sets (i.e., live before and after 
1276           // the call machine instruction)
1277
1278           unsigned Reg = getUnifiedRegNum(RCID, Color);
1279           
1280           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1281             
1282             // if we haven't already pushed that register
1283
1284             unsigned RegType = getRegType( LR );
1285
1286             // Now get two instructions - to push on stack and pop from stack
1287             // and add them to InstrnsBefore and InstrnsAfter of the
1288             // call instruction
1289
1290
1291             int StackOff =  PRA.mcInfo.pushTempValue(target,  
1292                                                getSpilledRegSize(RegType));
1293
1294             
1295             MachineInstr *AdIBefCC, *AdIAftCC, *AdICpCC;
1296             MachineInstr *AdIBef, *AdIAft;
1297
1298
1299             //---- Insert code for pushing the reg on stack ----------
1300                   
1301             if( RegType == IntCCRegType ) {
1302
1303               // Handle IntCCRegType specially since we cannot directly 
1304               // push %ccr on to the stack
1305
1306               const LiveVarSet *LVSetBef = 
1307                 PRA.LVI->getLiveVarSetBeforeMInst(MInst, BB);
1308
1309               // get a free INTEGER register
1310               int FreeIntReg = 
1311                 PRA.getUsableUniRegAtMI(LR->getRegClass(), IntRegType, MInst, 
1312                                      LVSetBef, AdIBefCC, AdIAftCC);
1313
1314               // insert the instructions in reverse order since we are
1315               // adding them to the front of InstrnsBefore
1316
1317               if(AdIAftCC)
1318                 (PRA.AddedInstrMap[MInst]->InstrnsBefore).push_front(AdIAftCC);
1319
1320               AdICpCC = cpCCR2IntMI(FreeIntReg);
1321               (PRA.AddedInstrMap[MInst]->InstrnsBefore).push_front(AdICpCC);
1322
1323               if(AdIBefCC)
1324                 (PRA.AddedInstrMap[MInst]->InstrnsBefore).push_front(AdIBefCC);
1325
1326               if(DEBUG_RA) {
1327                 cerr << "\n!! Inserted caller saving (push) inst for %ccr:";
1328                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1329                 cerr  << "\t" << *AdICpCC;
1330                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1331               }
1332
1333             } else  {  
1334               // for any other register type, just add the push inst
1335               AdIBef = cpReg2MemMI(Reg, getFramePointer(), StackOff, RegType );
1336               ((PRA.AddedInstrMap[MInst])->InstrnsBefore).push_front(AdIBef);
1337             }
1338
1339
1340             //---- Insert code for popping the reg from the stack ----------
1341
1342             if( RegType == IntCCRegType ) {
1343
1344               // Handle IntCCRegType specially since we cannot directly 
1345               // pop %ccr on from the stack
1346               
1347               // get a free INT register
1348               int FreeIntReg = 
1349                 PRA.getUsableUniRegAtMI(LR->getRegClass(), IntRegType, MInst, 
1350                                      LVSetAft, AdIBefCC, AdIAftCC);
1351               
1352               if(AdIBefCC)
1353                 (PRA.AddedInstrMap[MInst]->InstrnsAfter).push_back(AdIBefCC);
1354
1355               AdICpCC = cpInt2CCRMI(FreeIntReg);
1356               (PRA.AddedInstrMap[MInst]->InstrnsAfter).push_back(AdICpCC);
1357             
1358               if(AdIAftCC)
1359                 (PRA.AddedInstrMap[MInst]->InstrnsAfter).push_back(AdIAftCC);
1360
1361               if(DEBUG_RA) {
1362
1363                 cerr << "\n!! Inserted caller saving (pop) inst for %ccr:";
1364                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1365                 cerr  << "\t" << *AdICpCC;
1366                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1367               }
1368
1369             } else {
1370               // for any other register type, just add the pop inst
1371               AdIAft = cpMem2RegMI(getFramePointer(), StackOff, Reg, RegType );
1372               ((PRA.AddedInstrMap[MInst])->InstrnsAfter).push_back(AdIAft);
1373             }
1374             
1375             PushedRegSet.insert( Reg );
1376
1377             if(DEBUG_RA) {
1378               cerr << "\nFor call inst:" << *MInst;
1379               cerr << " -inserted caller saving instrs:\n\t ";
1380               if( RegType == IntCCRegType )
1381                 cerr << *AdIBefCC << "\t" << *AdIAftCC  ;
1382               else
1383                 cerr << *AdIBef   << "\t" << *AdIAft    ;
1384             }       
1385           } // if not already pushed
1386
1387         } // if LR has a volatile color
1388         
1389       } // if LR has color
1390
1391     } // if there is a LR for Var
1392     
1393   } // for each value in the LV set after instruction
1394   
1395 }
1396
1397 //---------------------------------------------------------------------------
1398 // Copies %ccr into an integer register. IntReg is the UNIFIED register
1399 // number.
1400 //---------------------------------------------------------------------------
1401
1402 MachineInstr * UltraSparcRegInfo::cpCCR2IntMI(unsigned IntReg) const {
1403   MachineInstr * MI = new MachineInstr(RDCCR, 2);
1404   MI->SetMachineOperand(0, SparcIntCCRegOrder::ccr, false);
1405   MI->SetMachineOperand(1, IntReg, true);
1406   return MI;
1407 }
1408
1409 //---------------------------------------------------------------------------
1410 // Copies an integer register into  %ccr. IntReg is the UNIFIED register
1411 // number.
1412 //---------------------------------------------------------------------------
1413
1414 MachineInstr *UltraSparcRegInfo::cpInt2CCRMI(unsigned IntReg) const {
1415   MachineInstr *MI = new MachineInstr(WRCCR, 3);
1416   MI->SetMachineOperand(0, IntReg, false);
1417   MI->SetMachineOperand(1, SparcIntRegOrder::g0, false);
1418   MI->SetMachineOperand(2, SparcIntCCRegOrder::ccr, true);
1419   return MI;
1420 }
1421
1422
1423
1424
1425 //---------------------------------------------------------------------------
1426 // Print the register assigned to a LR
1427 //---------------------------------------------------------------------------
1428
1429 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1430   unsigned RegClassID = (LR->getRegClass())->getID();
1431   cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1432
1433   if (!LR->hasColor()) {
1434     cerr << " - could not find a color\n";
1435     return;
1436   }
1437   
1438   // if a color is found
1439
1440   cerr << " colored with color "<< LR->getColor();
1441
1442   if (RegClassID == IntRegClassID) {
1443     cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) << "]\n";
1444
1445   } else if (RegClassID == FloatRegClassID) {
1446     cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
1447     if( LR->getTypeID() == Type::DoubleTyID )
1448       cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
1449     cerr << "]\n";
1450   }
1451 }
1452
1453 //---------------------------------------------------------------------------
1454 // This method examines instructions inserted by RegAlloc code before a
1455 // machine instruction to detect invalid orders that destroy values before
1456 // they are used. If it detects such conditions, it reorders the instructions.
1457 //
1458 // The unordered instructions come in the UnordVec. These instructions are
1459 // instructions inserted by RegAlloc. All such instruction MUST have 
1460 // their USES BEFORE THE DEFS after reordering.
1461
1462 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1463 // this method is called.
1464
1465 // This method uses two vectors for efficiency in accessing
1466
1467 // Since instructions are inserted in RegAlloc, this assumes that the 
1468 // first operand is the source reg and the last operand is the dest reg.
1469
1470 // All the uses are before THE def to a register
1471
1472
1473 //---------------------------------------------------------------------------
1474 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec,
1475                                           std::vector<MachineInstr *> &OrdVec,
1476                                           PhyRegAlloc &PRA) const{
1477
1478   /*
1479     Problem: We can have instructions inserted by RegAlloc like
1480     1. add %ox %g0 %oy
1481     2. add %oy %g0 %oz, where z!=x or z==x
1482
1483     This is wrong since %oy used by 2 is overwritten by 1
1484   
1485     Solution:
1486     We re-order the instructions so that the uses are before the defs
1487
1488     Algorithm:
1489     
1490     do
1491       for each instruction 'DefInst' in the UnOrdVec
1492          for each instruction 'UseInst' that follows the DefInst
1493            if the reg defined by DefInst is used by UseInst
1494              mark DefInst as not movable in this iteration
1495          If DefInst is not marked as not-movable, move DefInst to OrdVec
1496     while all instructions in DefInst are moved to OrdVec
1497     
1498     For moving, we call the move2OrdVec(). It checks whether there is a def
1499     in it for the uses in the instruction to be added to OrdVec. If there
1500     are no preceding defs, it just appends the instruction. If there is a
1501     preceding def, it puts two instructions to save the reg on stack before
1502     the load and puts a restore at use.
1503
1504   */
1505
1506   bool CouldMoveAll;
1507   bool DebugPrint = false;
1508
1509   do {
1510     CouldMoveAll = true;
1511     std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1512
1513     for( ; DefIt !=  UnordVec.end(); ++DefIt ) {
1514
1515       // for each instruction in the UnordVec do ...
1516
1517       MachineInstr *DefInst = *DefIt;
1518
1519       if( DefInst == NULL) continue;
1520
1521       //cerr << "\nInst in UnordVec = " <<  *DefInst;
1522       
1523       // last operand is the def (unless for a store which has no def reg)
1524       MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1525       
1526       if( DefOp.opIsDef() &&  
1527           DefOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1528         
1529         // If the operand in DefInst is a def ...
1530         
1531         bool DefEqUse = false;
1532         
1533         std::vector<MachineInstr *>::iterator UseIt = DefIt;
1534         UseIt++;
1535         
1536         for( ; UseIt !=  UnordVec.end(); ++UseIt ) {
1537
1538           MachineInstr *UseInst = *UseIt;
1539           if( UseInst == NULL) continue;
1540           
1541           // for each inst (UseInst) that is below the DefInst do ...
1542           MachineOperand& UseOp = UseInst->getOperand(0);
1543           
1544           if( ! UseOp.opIsDef() &&  
1545               UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1546             
1547             // if use is a register ...
1548             
1549             if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1550               
1551               // if Def and this use are the same, it means that this use
1552               // is destroyed by a def before it is used
1553               
1554               // cerr << "\nCouldn't move " << *DefInst;
1555
1556               DefEqUse = true;
1557               CouldMoveAll = false;     
1558               DebugPrint = true;
1559               break;
1560             } // if two registers are equal
1561             
1562           } // if use is a register
1563           
1564         }// for all use instructions
1565         
1566         if( ! DefEqUse ) {
1567           
1568           // after examining all the instructions that follow the DefInst
1569           // if there are no dependencies, we can move it to the OrdVec
1570
1571           // cerr << "Moved to Ord: " << *DefInst;
1572
1573           moveInst2OrdVec(OrdVec, DefInst, PRA);
1574
1575           //OrdVec.push_back(DefInst);
1576
1577           // mark the pos of DefInst with NULL to indicate that it is
1578           // empty
1579           *DefIt = NULL;
1580         }
1581     
1582       } // if Def is a machine register
1583       
1584     } // for all instructions in the UnordVec
1585     
1586
1587   } while(!CouldMoveAll);
1588
1589   if (DebugPrint) {
1590     cerr << "\nAdded instructions were reordered to:\n";
1591     for(unsigned int i=0; i < OrdVec.size(); i++)
1592       cerr << *(OrdVec[i]);
1593   }
1594 }
1595
1596
1597
1598
1599
1600 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1601                                         MachineInstr *UnordInst,
1602                                         PhyRegAlloc &PRA) const {
1603   MachineOperand& UseOp = UnordInst->getOperand(0);
1604
1605   if( ! UseOp.opIsDef() &&  
1606       UseOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1607
1608     // for the use of UnordInst, see whether there is a defining instr
1609     // before in the OrdVec
1610     bool DefEqUse = false;
1611
1612     std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1613   
1614     for( ; OrdIt !=  OrdVec.end(); ++OrdIt ) {
1615
1616       MachineInstr *OrdInst = *OrdIt ;
1617
1618       MachineOperand& DefOp = 
1619         OrdInst->getOperand(OrdInst->getNumOperands()-1);
1620
1621       if( DefOp.opIsDef() &&  
1622           DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1623
1624         //cerr << "\nDefining Ord Inst: " <<  *OrdInst;
1625           
1626         if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1627
1628           // we are here because there is a preceding def in the OrdVec 
1629           // for the use in this intr we are going to insert. This
1630           // happened because the original code was like:
1631           // 1. add %ox %g0 %oy
1632           // 2. add %oy %g0 %ox
1633           // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1634           // Now we are processing %ox of 1.
1635           // We have to 
1636               
1637           const int UReg = DefOp.getMachineRegNum();
1638           const int RegType = getRegType(UReg);
1639           MachineInstr *AdIBef, *AdIAft;
1640               
1641           const int StackOff =  PRA.mcInfo.pushTempValue(target,
1642                                          getSpilledRegSize(RegType));
1643           
1644           // Save the UReg (%ox) on stack before it's destroyed
1645           AdIBef=cpReg2MemMI(UReg, getFramePointer(), StackOff, RegType);
1646           OrdIt = OrdVec.insert( OrdIt, AdIBef);
1647           OrdIt++;  // points to current instr we processed
1648           
1649           // Load directly into DReg (%oy)
1650           MachineOperand&  DOp=
1651             (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1652           assert(DOp.opIsDef() && "Last operand is not the def");
1653           const int DReg = DOp.getMachineRegNum();
1654           
1655           AdIAft=cpMem2RegMI(getFramePointer(), StackOff, DReg, RegType);
1656           OrdVec.push_back(AdIAft);
1657             
1658           cerr << "\nFixed CIRCULAR references by reordering";
1659
1660           if( DEBUG_RA ) {
1661             cerr << "\nBefore CIRCULAR Reordering:\n";
1662             cerr << *UnordInst;
1663             cerr << *OrdInst;
1664           
1665             cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1666             for(unsigned i=0; i < OrdVec.size(); i++)
1667               cerr << *(OrdVec[i]);
1668           }
1669           
1670           // Do not copy the UseInst to OrdVec
1671           DefEqUse = true;
1672           break;  
1673           
1674         }// if two registers are equal
1675
1676       } // if Def is a register
1677
1678     } // for each instr in OrdVec
1679
1680     if(!DefEqUse) {  
1681
1682       // We didn't find a def in the OrdVec, so just append this inst
1683       OrdVec.push_back( UnordInst );  
1684       //cerr << "Reordered Inst (Moved Dn): " <<  *UnordInst;
1685     }
1686     
1687   }// if the operand in UnordInst is a use
1688 }