Several fixes to handling of int CC register:
[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",  "icc",  "ccr"
102 };
103
104 const char * const SparcIntCCRegClass::getRegName(unsigned reg) const {
105   assert(reg < 3);
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->isMarkedForSpill() ) {    // 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   } // for all call arguments
622 }
623
624
625 //---------------------------------------------------------------------------
626 // Helper method for UltraSparcRegInfo::colorCallArgs().
627 //---------------------------------------------------------------------------
628     
629 void
630 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
631                              AddedInstrns *CallAI,
632                              PhyRegAlloc &PRA, LiveRange* LR,
633                              unsigned regType, unsigned RegClassID,
634                              int UniArgRegOrNone, unsigned argNo,
635                              std::vector<MachineInstr*> &AddedInstrnsBefore)
636   const
637 {
638   assert(0 && "Should never get here because we are now using precopying!");
639
640   MachineInstr *AdMI;
641   bool isArgInReg = false;
642   unsigned UniArgReg = BadRegClass;          // unused unless initialized below
643   if (UniArgRegOrNone != getInvalidRegNum())
644     {
645       isArgInReg = true;
646       UniArgReg = (unsigned) UniArgRegOrNone;
647     }
648   
649   if (! LR->isMarkedForSpill()) {
650     unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
651     
652     // if LR received the correct color, nothing to do
653     if( isArgInReg && UniArgReg == UniLRReg )
654       return;
655     
656     // The LR is allocated to a register UniLRReg and must be copied
657     // to UniArgReg or to the stack slot.
658     // 
659     if( isArgInReg ) {
660       // Copy UniLRReg to UniArgReg
661       cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
662     }
663     else {
664       // Copy UniLRReg to the stack to pass the arg on stack.
665       const TargetFrameInfo& frameInfo = target.getFrameInfo();
666       int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
667       cpReg2MemMI(CallAI->InstrnsBefore,
668                   UniLRReg, getStackPointer(), argOffset, regType);
669     }
670
671   } else {                          // LR is not colored (i.e., spilled)      
672     
673     if( isArgInReg ) {
674       // Insert a load instruction to load the LR to UniArgReg
675       cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
676                   LR->getSpillOffFromFP(), UniArgReg, regType);
677                                         // Now add the instruction
678     }
679       
680     else {
681       // Now, we have to pass the arg on stack. Since LR  also did NOT
682       // receive a register we have to move an argument in memory to 
683       // outgoing parameter on stack.
684       // Use TReg to load and store the value.
685       // Use TmpOff to save TReg, since that may have a live value.
686       // 
687       int TReg = PRA.getUniRegNotUsedByThisInst(LR->getRegClass(), CallMI);
688       int TmpOff = PRA.MF.getInfo()->
689                      pushTempValue(getSpilledRegSize(getRegType(LR)));
690       const TargetFrameInfo& frameInfo = target.getFrameInfo();
691       int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
692       
693       MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
694         
695       // Sequence:
696       // (1) Save TReg on stack    
697       // (2) Load LR value into TReg from stack pos of LR
698       // (3) Store Treg on outgoing Arg pos on stack
699       // (4) Load the old value of TReg from stack to TReg (restore it)
700       // 
701       // OPTIMIZE THIS:
702       // When reverse pointers in MahineInstr are introduced: 
703       // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
704       // needed only if this fails. Currently, we cannot call the
705       // above method since we cannot find LVSetBefore without the BB 
706       // 
707       // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
708       // AddedInstrnsBefore since these instructions must not be reordered.
709       cpReg2MemMI(CallAI->InstrnsBefore,
710                   TReg, getFramePointer(), TmpOff, regType);
711       cpMem2RegMI(CallAI->InstrnsBefore,
712                   getFramePointer(), LR->getSpillOffFromFP(), TReg, regType); 
713       cpReg2MemMI(CallAI->InstrnsBefore,
714                   TReg, getStackPointer(), argOffset, regType);
715       cpMem2RegMI(CallAI->InstrnsBefore,
716                   getFramePointer(), TmpOff, TReg, regType); 
717     }
718   }
719 }
720
721 //---------------------------------------------------------------------------
722 // After graph coloring, we have call this method to see whehter the return
723 // value and the call args received the correct colors. If not, we have
724 // to instert copy instructions.
725 //---------------------------------------------------------------------------
726
727 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
728                                       LiveRangeInfo &LRI,
729                                       AddedInstrns *CallAI,
730                                       PhyRegAlloc &PRA,
731                                       const BasicBlock *BB) const {
732
733   assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
734
735   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
736   
737   // First color the return value of the call.
738   // If there is a LR for the return value, it means this
739   // method returns a value
740   
741   MachineInstr *AdMI;
742
743   const Value *RetVal = argDesc->getReturnValue();
744
745   if (RetVal) {
746     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
747     assert(RetValLR && "ERROR: No LR for non-void return value");
748
749     // Mark the return value register as used by this instruction
750     unsigned RegClassID = RetValLR->getRegClassID();
751     unsigned CorrectCol = (RegClassID == IntRegClassID
752                            ? (unsigned) SparcIntRegClass::o0
753                            : (unsigned) SparcFloatRegClass::f0);
754     
755     CallMI->insertUsedReg(getUnifiedRegNum(RegClassID, CorrectCol));    
756     
757   } // if there a return value
758   
759
760   //-------------------------------------------
761   // Now color all args of the call instruction
762   //-------------------------------------------
763
764   std::vector<MachineInstr*> AddedInstrnsBefore;
765   
766   unsigned NumOfCallArgs = argDesc->getNumArgs();
767   
768   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
769       i < NumOfCallArgs; ++i, ++argNo) {    
770     
771     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
772     unsigned regType = getRegType(CallArg->getType());
773
774     // Find whether this argument is coming in a register (if not, on stack)
775     // Also find the correct register the argument must use (UniArgReg)
776     //
777     bool isArgInReg = false;
778     int UniArgReg = getInvalidRegNum();   // reg that LR MUST be colored with
779     unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
780     
781     // Find the register that must be used for this arg, depending on
782     // whether it is an INT or FP value.  Here we ignore whether or not it
783     // is a varargs calls, because FP arguments will be explicitly copied
784     // to an integer Value and handled under (argCopy != NULL) below.
785     // 
786     int regNum = (regType == IntRegType)
787       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
788                         argNo, regClassIDOfArgReg)
789       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
790                        argNo, regClassIDOfArgReg); 
791     
792     if (regNum != getInvalidRegNum()) {
793       isArgInReg = true;
794       UniArgReg = getUnifiedRegNum(regClassIDOfArgReg, regNum);
795       CallMI->insertUsedReg(UniArgReg);         // mark the reg as used
796     }
797
798     // Repeat for the second copy of the argument, which would be
799     // an FP argument being passed to a function with no prototype.
800     // It may either be passed as a copy in an integer register
801     // (in argCopy), or on the stack (useStackSlot).
802     int argCopyReg = argDesc->getArgInfo(i).getArgCopy();
803     if (argCopyReg != TargetRegInfo::getInvalidRegNum())
804       {
805         CallMI->insertUsedReg(argCopyReg); // mark the reg as used
806       }
807   }  // for each parameter in call instruction
808
809   // If we added any instruction before the call instruction, verify
810   // that they are in the proper order and if not, reorder them
811   // 
812   std::vector<MachineInstr*> ReorderedVec;
813   if (!AddedInstrnsBefore.empty()) {
814
815     if (DEBUG_RA) {
816       std::cerr << "\nCalling reorder with instrns: \n";
817       for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
818         std::cerr  << *(AddedInstrnsBefore[i]);
819     }
820
821     OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
822     assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
823            && "Dropped some instructions when reordering!");
824     
825     if (DEBUG_RA) {
826       std::cerr << "\nAfter reordering instrns: \n";
827       for(unsigned i = 0; i < ReorderedVec.size(); i++)
828         std::cerr << *ReorderedVec[i];
829     }
830   }
831   
832   // Now insert caller saving code for this call instruction
833   //
834   insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
835                          CallMI, BB, PRA);
836   
837   // Then insert the final reordered code for the call arguments.
838   // 
839   for(unsigned i=0; i < ReorderedVec.size(); i++)
840     CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
841
842 #ifndef NDEBUG
843   // Temporary sanity checking code to detect whether the same machine
844   // instruction is ever inserted twice before/after a call.
845   // I suspect this is happening but am not sure. --Vikram, 7/1/03.
846   // 
847   std::set<const MachineInstr*> instrsSeen;
848   for (int i = 0, N = CallAI->InstrnsBefore.size(); i < N; ++i) {
849     assert(instrsSeen.find(CallAI->InstrnsBefore[i]) == instrsSeen.end() &&
850            "Duplicate machine instruction in InstrnsBefore!");
851     instrsSeen.insert(CallAI->InstrnsBefore[i]);
852   } 
853   for (int i = 0, N = CallAI->InstrnsAfter.size(); i < N; ++i) {
854     assert(instrsSeen.find(CallAI->InstrnsAfter[i]) == instrsSeen.end() &&
855            "Duplicate machine instruction in InstrnsBefore/After!");
856     instrsSeen.insert(CallAI->InstrnsAfter[i]);
857   } 
858 #endif
859 }
860
861 //---------------------------------------------------------------------------
862 // this method is called for an LLVM return instruction to identify which
863 // values will be returned from this method and to suggest colors.
864 //---------------------------------------------------------------------------
865 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI, 
866                                             LiveRangeInfo &LRI) const {
867
868   assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
869
870   suggestReg4RetAddr(RetMI, LRI);
871
872   // To find the return value (if any), we can get the LLVM return instr.
873   // from the return address register, which is the first operand
874   Value* tmpI = RetMI->getOperand(0).getVRegValue();
875   ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
876   if (const Value *RetVal = retI->getReturnValue())
877     if (LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
878       LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
879                             ? (unsigned) SparcIntRegClass::i0
880                             : (unsigned) SparcFloatRegClass::f0);
881 }
882
883
884
885 //---------------------------------------------------------------------------
886 // Colors the return value of a method to %i0 or %f0, if possible. If it is
887 // not possilbe to directly color the LR, insert a copy instruction to move
888 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we 
889 // have to put a load instruction.
890 //---------------------------------------------------------------------------
891 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI, 
892                                       LiveRangeInfo &LRI,
893                                       AddedInstrns *RetAI) const {
894
895   assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
896
897   // To find the return value (if any), we can get the LLVM return instr.
898   // from the return address register, which is the first operand
899   Value* tmpI = RetMI->getOperand(0).getVRegValue();
900   ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
901   if (const Value *RetVal = retI->getReturnValue()) {
902
903     unsigned RegClassID = getRegClassIDOfType(RetVal->getType());
904     unsigned regType = getRegType(RetVal->getType());
905     unsigned CorrectCol = (RegClassID == IntRegClassID
906                            ? (unsigned) SparcIntRegClass::i0
907                            : (unsigned) SparcFloatRegClass::f0);
908
909     // convert to unified number
910     unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
911
912     // Mark the register as used by this instruction
913     RetMI->insertUsedReg(UniRetReg);
914   } // if there is a return value
915
916 }
917
918 //---------------------------------------------------------------------------
919 // Check if a specified register type needs a scratch register to be
920 // copied to/from memory.  If it does, the reg. type that must be used
921 // for scratch registers is returned in scratchRegType.
922 //
923 // Only the int CC register needs such a scratch register.
924 // The FP CC registers can (and must) be copied directly to/from memory.
925 //---------------------------------------------------------------------------
926
927 bool
928 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
929                                           int& scratchRegType) const
930 {
931   if (RegType == IntCCRegType)
932     {
933       scratchRegType = IntRegType;
934       return true;
935     }
936   return false;
937 }
938
939 //---------------------------------------------------------------------------
940 // Copy from a register to register. Register number must be the unified
941 // register number.
942 //---------------------------------------------------------------------------
943
944 void
945 UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
946                                unsigned SrcReg,
947                                unsigned DestReg,
948                                int RegType) const {
949   assert( ((int)SrcReg != getInvalidRegNum()) && 
950           ((int)DestReg != getInvalidRegNum()) &&
951           "Invalid Register");
952   
953   MachineInstr * MI = NULL;
954   
955   switch( RegType ) {
956     
957   case IntCCRegType:
958     if (getRegType(DestReg) == IntRegType) {
959       // copy intCC reg to int reg
960       MI = (BuildMI(V9::RDCCR, 2)
961             .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
962                                       SparcIntCCRegClass::ccr))
963             .addMReg(DestReg,MOTy::Def));
964     } else {
965       // copy int reg to intCC reg
966       assert(getRegType(SrcReg) == IntRegType
967              && "Can only copy CC reg to/from integer reg");
968       MI = (BuildMI(V9::WRCCRr, 3)
969             .addMReg(SrcReg)
970             .addMReg(SparcIntRegClass::g0)
971             .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
972                                       SparcIntCCRegClass::ccr), MOTy::Def));
973     }
974     break;
975     
976   case FloatCCRegType: 
977     assert(0 && "Cannot copy FPCC register to any other register");
978     break;
979     
980   case IntRegType:
981     MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
982       .addMReg(DestReg, MOTy::Def);
983     break;
984     
985   case FPSingleRegType:
986     MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
987     break;
988
989   case FPDoubleRegType:
990     MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
991     break;
992
993   default:
994     assert(0 && "Unknown RegType");
995     break;
996   }
997   
998   if (MI)
999     mvec.push_back(MI);
1000 }
1001
1002 //---------------------------------------------------------------------------
1003 // Copy from a register to memory (i.e., Store). Register number must 
1004 // be the unified register number
1005 //---------------------------------------------------------------------------
1006
1007
1008 void
1009 UltraSparcRegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
1010                                unsigned SrcReg, 
1011                                unsigned DestPtrReg,
1012                                int Offset, int RegType,
1013                                int scratchReg) const {
1014   MachineInstr * MI = NULL;
1015   switch (RegType) {
1016   case IntRegType:
1017     assert(target.getInstrInfo().constantFitsInImmedField(V9::STXi, Offset));
1018     MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1019       .addSImm(Offset);
1020     break;
1021
1022   case FPSingleRegType:
1023     assert(target.getInstrInfo().constantFitsInImmedField(V9::STFi, Offset));
1024     MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(DestPtrReg)
1025       .addSImm(Offset);
1026     break;
1027
1028   case FPDoubleRegType:
1029     assert(target.getInstrInfo().constantFitsInImmedField(V9::STDFi, Offset));
1030     MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1031       .addSImm(Offset);
1032     break;
1033
1034   case IntCCRegType:
1035     assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1036     assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1037     MI = (BuildMI(V9::RDCCR, 2)
1038           .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
1039                                     SparcIntCCRegClass::ccr))
1040           .addMReg(scratchReg, MOTy::Def));
1041     mvec.push_back(MI);
1042     
1043     cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1044     return;
1045     
1046   case FloatCCRegType: {
1047     assert(target.getInstrInfo().constantFitsInImmedField(V9::STXFSRi, Offset));
1048     unsigned fsrRegNum =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1049                                            SparcSpecialRegClass::fsr);
1050     MI = BuildMI(V9::STXFSRi, 3)
1051       .addMReg(fsrRegNum).addMReg(DestPtrReg).addSImm(Offset);
1052     break;
1053   }
1054   default:
1055     assert(0 && "Unknown RegType in cpReg2MemMI");
1056   }
1057   mvec.push_back(MI);
1058 }
1059
1060
1061 //---------------------------------------------------------------------------
1062 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1063 // register number
1064 //---------------------------------------------------------------------------
1065
1066
1067 void
1068 UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
1069                                unsigned SrcPtrReg,      
1070                                int Offset,
1071                                unsigned DestReg,
1072                                int RegType,
1073                                int scratchReg) const {
1074   MachineInstr * MI = NULL;
1075   switch (RegType) {
1076   case IntRegType:
1077     assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset));
1078     MI = BuildMI(V9::LDXi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1079       .addMReg(DestReg, MOTy::Def);
1080     break;
1081
1082   case FPSingleRegType:
1083     assert(target.getInstrInfo().constantFitsInImmedField(V9::LDFi, Offset));
1084     MI = BuildMI(V9::LDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1085       .addMReg(DestReg, MOTy::Def);
1086     break;
1087
1088   case FPDoubleRegType:
1089     assert(target.getInstrInfo().constantFitsInImmedField(V9::LDDFi, Offset));
1090     MI = BuildMI(V9::LDDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1091       .addMReg(DestReg, MOTy::Def);
1092     break;
1093
1094   case IntCCRegType:
1095     assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1096     assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1097     cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1098     MI = (BuildMI(V9::WRCCRr, 3)
1099           .addMReg(scratchReg)
1100           .addMReg(SparcIntRegClass::g0)
1101           .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
1102                                     SparcIntCCRegClass::ccr), MOTy::Def));
1103     break;
1104     
1105   case FloatCCRegType: {
1106     assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXFSRi, Offset));
1107     unsigned fsrRegNum =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1108                                            SparcSpecialRegClass::fsr);
1109     MI = BuildMI(V9::LDXFSRi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1110       .addMReg(fsrRegNum, MOTy::UseAndDef);
1111     break;
1112   }
1113   default:
1114     assert(0 && "Unknown RegType in cpMem2RegMI");
1115   }
1116   mvec.push_back(MI);
1117 }
1118
1119
1120 //---------------------------------------------------------------------------
1121 // Generate a copy instruction to copy a value to another. Temporarily
1122 // used by PhiElimination code.
1123 //---------------------------------------------------------------------------
1124
1125
1126 void
1127 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
1128                                  std::vector<MachineInstr*>& mvec) const {
1129   int RegType = getRegType(Src->getType());
1130   MachineInstr * MI = NULL;
1131
1132   switch( RegType ) {
1133   case IntRegType:
1134     MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
1135       .addRegDef(Dest);
1136     break;
1137   case FPSingleRegType:
1138     MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
1139     break;
1140   case FPDoubleRegType:
1141     MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
1142     break;
1143   default:
1144     assert(0 && "Unknow RegType in CpValu2Value");
1145   }
1146
1147   mvec.push_back(MI);
1148 }
1149
1150
1151
1152
1153
1154
1155 //----------------------------------------------------------------------------
1156 // This method inserts caller saving/restoring instructons before/after
1157 // a call machine instruction. The caller saving/restoring instructions are
1158 // inserted like:
1159 //
1160 //    ** caller saving instructions
1161 //    other instructions inserted for the call by ColorCallArg
1162 //    CALL instruction
1163 //    other instructions inserted for the call ColorCallArg
1164 //    ** caller restoring instructions
1165 //
1166 //----------------------------------------------------------------------------
1167
1168
1169 void
1170 UltraSparcRegInfo::insertCallerSavingCode
1171 (std::vector<MachineInstr*> &instrnsBefore,
1172  std::vector<MachineInstr*> &instrnsAfter,
1173  MachineInstr *CallMI, 
1174  const BasicBlock *BB,
1175  PhyRegAlloc &PRA) const
1176 {
1177   assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1178   
1179   // has set to record which registers were saved/restored
1180   //
1181   hash_set<unsigned> PushedRegSet;
1182
1183   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1184   
1185   // Now check if the call has a return value (using argDesc) and if so,
1186   // find the LR of the TmpInstruction representing the return value register.
1187   // (using the last or second-last *implicit operand* of the call MI).
1188   // Insert it to to the PushedRegSet since we must not save that register
1189   // and restore it after the call.
1190   // We do this because, we look at the LV set *after* the instruction
1191   // to determine, which LRs must be saved across calls. The return value
1192   // of the call is live in this set - but we must not save/restore it.
1193   // 
1194   if (const Value *origRetVal = argDesc->getReturnValue()) {
1195     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
1196                              (argDesc->getIndirectFuncPtr()? 1 : 2));
1197     const TmpInstruction* tmpRetVal =
1198       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
1199     assert(tmpRetVal->getOperand(0) == origRetVal &&
1200            tmpRetVal->getType() == origRetVal->getType() &&
1201            "Wrong implicit ref?");
1202     LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( tmpRetVal );
1203     assert(RetValLR && "No LR for RetValue of call");
1204
1205     if (! RetValLR->isMarkedForSpill())
1206       PushedRegSet.insert(getUnifiedRegNum(RetValLR->getRegClassID(),
1207                                            RetValLR->getColor()));
1208   }
1209
1210   const ValueSet &LVSetAft =  PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1211   ValueSet::const_iterator LIt = LVSetAft.begin();
1212
1213   // for each live var in live variable set after machine inst
1214   for( ; LIt != LVSetAft.end(); ++LIt) {
1215
1216    //  get the live range corresponding to live var
1217     LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );    
1218
1219     // LR can be null if it is a const since a const 
1220     // doesn't have a dominating def - see Assumptions above
1221     if( LR )   {  
1222       
1223       if(! LR->isMarkedForSpill()) {
1224
1225         assert(LR->hasColor() && "LR is neither spilled nor colored?");
1226         unsigned RCID = LR->getRegClassID();
1227         unsigned Color = LR->getColor();
1228
1229         if ( isRegVolatile(RCID, Color) ) {
1230
1231           // if the value is in both LV sets (i.e., live before and after 
1232           // the call machine instruction)
1233           
1234           unsigned Reg = getUnifiedRegNum(RCID, Color);
1235           
1236           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1237             
1238             // if we haven't already pushed that register
1239
1240             unsigned RegType = getRegType(LR);
1241
1242             // Now get two instructions - to push on stack and pop from stack
1243             // and add them to InstrnsBefore and InstrnsAfter of the
1244             // call instruction
1245             // 
1246             int StackOff =
1247               PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1248             
1249             //---- Insert code for pushing the reg on stack ----------
1250             
1251             std::vector<MachineInstr*> AdIBef, AdIAft;
1252             
1253             // We may need a scratch register to copy the saved value
1254             // to/from memory.  This may itself have to insert code to
1255             // free up a scratch register.  Any such code should go before
1256             // the save code.  The scratch register, if any, is by default
1257             // temporary and not "used" by the instruction unless the
1258             // copy code itself decides to keep the value in the scratch reg.
1259             int scratchRegType = -1;
1260             int scratchReg = -1;
1261             if (regTypeNeedsScratchReg(RegType, scratchRegType))
1262               { // Find a register not live in the LVSet before CallMI
1263                 const ValueSet &LVSetBef =
1264                   PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1265                 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1266                                                    CallMI, AdIBef, AdIAft);
1267                 assert(scratchReg != getInvalidRegNum());
1268               }
1269             
1270             if (AdIBef.size() > 0)
1271               instrnsBefore.insert(instrnsBefore.end(),
1272                                    AdIBef.begin(), AdIBef.end());
1273             
1274             cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1275                         scratchReg);
1276             
1277             if (AdIAft.size() > 0)
1278               instrnsBefore.insert(instrnsBefore.end(),
1279                                    AdIAft.begin(), AdIAft.end());
1280             
1281             //---- Insert code for popping the reg from the stack ----------
1282
1283             AdIBef.clear();
1284             AdIAft.clear();
1285             
1286             // We may need a scratch register to copy the saved value
1287             // from memory.  This may itself have to insert code to
1288             // free up a scratch register.  Any such code should go
1289             // after the save code.  As above, scratch is not marked "used".
1290             // 
1291             scratchRegType = -1;
1292             scratchReg = -1;
1293             if (regTypeNeedsScratchReg(RegType, scratchRegType))
1294               { // Find a register not live in the LVSet after CallMI
1295                 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1296                                                  CallMI, AdIBef, AdIAft);
1297                 assert(scratchReg != getInvalidRegNum());
1298               }
1299             
1300             if (AdIBef.size() > 0)
1301               instrnsAfter.insert(instrnsAfter.end(),
1302                                   AdIBef.begin(), AdIBef.end());
1303             
1304             cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1305                         scratchReg);
1306             
1307             if (AdIAft.size() > 0)
1308               instrnsAfter.insert(instrnsAfter.end(),
1309                                   AdIAft.begin(), AdIAft.end());
1310             
1311             PushedRegSet.insert(Reg);
1312             
1313             if(DEBUG_RA) {
1314               std::cerr << "\nFor call inst:" << *CallMI;
1315               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1316               for_each(instrnsBefore.begin(), instrnsBefore.end(),
1317                        std::mem_fun(&MachineInstr::dump));
1318               std::cerr << " -and After:\n\t ";
1319               for_each(instrnsAfter.begin(), instrnsAfter.end(),
1320                        std::mem_fun(&MachineInstr::dump));
1321             }       
1322           } // if not already pushed
1323
1324         } // if LR has a volatile color
1325         
1326       } // if LR has color
1327
1328     } // if there is a LR for Var
1329     
1330   } // for each value in the LV set after instruction
1331 }
1332
1333
1334 //---------------------------------------------------------------------------
1335 // Print the register assigned to a LR
1336 //---------------------------------------------------------------------------
1337
1338 void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
1339   unsigned RegClassID = LR->getRegClassID();
1340   std::cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1341
1342   if (!LR->hasColor()) {
1343     std::cerr << " - could not find a color\n";
1344     return;
1345   }
1346   
1347   // if a color is found
1348
1349   std::cerr << " colored with color "<< LR->getColor();
1350
1351   unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
1352   
1353   std::cerr << "[";
1354   std::cerr<< getUnifiedRegName(uRegName);
1355   if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
1356     std::cerr << "+" << getUnifiedRegName(uRegName+1);
1357   std::cerr << "]\n";
1358 }
1359
1360 //---------------------------------------------------------------------------
1361 // This method examines instructions inserted by RegAlloc code before a
1362 // machine instruction to detect invalid orders that destroy values before
1363 // they are used. If it detects such conditions, it reorders the instructions.
1364 //
1365 // The unordered instructions come in the UnordVec. These instructions are
1366 // instructions inserted by RegAlloc. All such instruction MUST have 
1367 // their USES BEFORE THE DEFS after reordering.
1368 // 
1369 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1370 // this method is called.
1371 // 
1372 // This method uses two vectors for efficiency in accessing
1373 // 
1374 // Since instructions are inserted in RegAlloc, this assumes that the 
1375 // first operand is the source reg and the last operand is the dest reg.
1376 // It also does not consider operands that are both use and def.
1377 // 
1378 // All the uses are before THE def to a register
1379 //---------------------------------------------------------------------------
1380
1381 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1382                                           std::vector<MachineInstr*> &OrdVec,
1383                                           PhyRegAlloc &PRA) const{
1384
1385   /*
1386     Problem: We can have instructions inserted by RegAlloc like
1387     1. add %ox %g0 %oy
1388     2. add %oy %g0 %oz, where z!=x or z==x
1389
1390     This is wrong since %oy used by 2 is overwritten by 1
1391   
1392     Solution:
1393     We re-order the instructions so that the uses are before the defs
1394
1395     Algorithm:
1396     
1397     do
1398       for each instruction 'DefInst' in the UnOrdVec
1399          for each instruction 'UseInst' that follows the DefInst
1400            if the reg defined by DefInst is used by UseInst
1401              mark DefInst as not movable in this iteration
1402          If DefInst is not marked as not-movable, move DefInst to OrdVec
1403     while all instructions in DefInst are moved to OrdVec
1404     
1405     For moving, we call the move2OrdVec(). It checks whether there is a def
1406     in it for the uses in the instruction to be added to OrdVec. If there
1407     are no preceding defs, it just appends the instruction. If there is a
1408     preceding def, it puts two instructions to save the reg on stack before
1409     the load and puts a restore at use.
1410
1411   */
1412
1413   bool CouldMoveAll;
1414   bool DebugPrint = false;
1415
1416   do {
1417     CouldMoveAll = true;
1418     std::vector<MachineInstr*>::iterator DefIt = UnordVec.begin();
1419
1420     for( ; DefIt !=  UnordVec.end(); ++DefIt ) {
1421
1422       // for each instruction in the UnordVec do ...
1423
1424       MachineInstr *DefInst = *DefIt;
1425
1426       if( DefInst == NULL) continue;
1427
1428       //std::cerr << "\nInst in UnordVec = " <<  *DefInst;
1429       
1430       // last operand is the def (unless for a store which has no def reg)
1431       MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1432       
1433       if ((DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1434           DefOp.getType() == MachineOperand::MO_MachineRegister) {
1435         
1436         // If the operand in DefInst is a def ...
1437         bool DefEqUse = false;
1438         
1439         std::vector<MachineInstr*>::iterator UseIt = DefIt;
1440         UseIt++;
1441         
1442         for( ; UseIt !=  UnordVec.end(); ++UseIt ) {
1443
1444           MachineInstr *UseInst = *UseIt;
1445           if( UseInst == NULL) continue;
1446           
1447           // for each inst (UseInst) that is below the DefInst do ...
1448           MachineOperand& UseOp = UseInst->getOperand(0);
1449           
1450           if (!UseOp.opIsDefOnly() &&  
1451               UseOp.getType() == MachineOperand::MO_MachineRegister) {
1452             
1453             // if use is a register ...
1454             
1455             if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1456               
1457               // if Def and this use are the same, it means that this use
1458               // is destroyed by a def before it is used
1459               
1460               // std::cerr << "\nCouldn't move " << *DefInst;
1461
1462               DefEqUse = true;
1463               CouldMoveAll = false;     
1464               DebugPrint = true;
1465               break;
1466             } // if two registers are equal
1467             
1468           } // if use is a register
1469           
1470         }// for all use instructions
1471         
1472         if( ! DefEqUse ) {
1473           
1474           // after examining all the instructions that follow the DefInst
1475           // if there are no dependencies, we can move it to the OrdVec
1476
1477           // std::cerr << "Moved to Ord: " << *DefInst;
1478
1479           moveInst2OrdVec(OrdVec, DefInst, PRA);
1480
1481           //OrdVec.push_back(DefInst);
1482
1483           // mark the pos of DefInst with NULL to indicate that it is
1484           // empty
1485           *DefIt = NULL;
1486         }
1487     
1488       } // if Def is a machine register
1489       
1490     } // for all instructions in the UnordVec
1491     
1492
1493   } while(!CouldMoveAll);
1494
1495   if (DebugPrint && DEBUG_RA) {
1496     std::cerr << "\nAdded instructions were reordered to:\n";
1497     for(unsigned i=0; i < OrdVec.size(); i++)
1498       std::cerr << *OrdVec[i];
1499   }
1500 }
1501
1502
1503
1504
1505
1506 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr*> &OrdVec,
1507                                         MachineInstr *UnordInst,
1508                                         PhyRegAlloc &PRA) const {
1509   MachineOperand& UseOp = UnordInst->getOperand(0);
1510
1511   if (!UseOp.opIsDefOnly() &&
1512       UseOp.getType() ==  MachineOperand::MO_MachineRegister) {
1513
1514     // for the use of UnordInst, see whether there is a defining instr
1515     // before in the OrdVec
1516     bool DefEqUse = false;
1517
1518     std::vector<MachineInstr*>::iterator OrdIt = OrdVec.begin();
1519   
1520     for( ; OrdIt !=  OrdVec.end(); ++OrdIt ) {
1521
1522       MachineInstr *OrdInst = *OrdIt ;
1523
1524       MachineOperand& DefOp = 
1525         OrdInst->getOperand(OrdInst->getNumOperands()-1);
1526
1527       if( (DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&  
1528           DefOp.getType() == MachineOperand::MO_MachineRegister) {
1529
1530         //std::cerr << "\nDefining Ord Inst: " <<  *OrdInst;
1531           
1532         if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1533
1534           // we are here because there is a preceding def in the OrdVec 
1535           // for the use in this intr we are going to insert. This
1536           // happened because the original code was like:
1537           // 1. add %ox %g0 %oy
1538           // 2. add %oy %g0 %ox
1539           // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1540           // Now we are processing %ox of 1.
1541           // We have to 
1542               
1543           int UReg = DefOp.getMachineRegNum();
1544           int RegType = getRegType(UReg);
1545           MachineInstr *AdIBef, *AdIAft;
1546               
1547           int StackOff =
1548             PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1549           
1550           // Save the UReg (%ox) on stack before it's destroyed
1551           std::vector<MachineInstr*> mvec;
1552           cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1553           for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
1554                MI != mvec.end(); ++MI)
1555             OrdIt = 1+OrdVec.insert(OrdIt, *MI);
1556           
1557           // Load directly into DReg (%oy)
1558           MachineOperand&  DOp=
1559             (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1560           assert((DOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1561                  "Last operand is not the def");
1562           const int DReg = DOp.getMachineRegNum();
1563           
1564           cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1565             
1566           if( DEBUG_RA ) {
1567             std::cerr << "\nFixed CIRCULAR references by reordering:";
1568             std::cerr << "\nBefore CIRCULAR Reordering:\n";
1569             std::cerr << *UnordInst;
1570             std::cerr << *OrdInst;
1571           
1572             std::cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1573             for(unsigned i=0; i < OrdVec.size(); i++)
1574               std::cerr << *(OrdVec[i]);
1575           }
1576           
1577           // Do not copy the UseInst to OrdVec
1578           DefEqUse = true;
1579           break;  
1580           
1581         }// if two registers are equal
1582
1583       } // if Def is a register
1584
1585     } // for each instr in OrdVec
1586
1587     if(!DefEqUse) {  
1588
1589       // We didn't find a def in the OrdVec, so just append this inst
1590       OrdVec.push_back( UnordInst );  
1591       //std::cerr << "Reordered Inst (Moved Dn): " <<  *UnordInst;
1592     }
1593     
1594   }// if the operand in UnordInst is a use
1595 }