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