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