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