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