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