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