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