1 //===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
3 // This file contains implementation of Sparc specific helper methods
4 // used for register allocation.
6 //===----------------------------------------------------------------------===//
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"
28 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
29 : MachineRegInfo(tgt), UltraSparcInfo(&tgt), NumOfIntArgRegs(6),
30 NumOfFloatArgRegs(32), InvalidRegNum(1000) {
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));
37 assert(SparcFloatRegClass::StartOfNonVolatileRegs == 32 &&
38 "32 Float regs are used for float arg passing");
42 // getZeroRegNum - returns the register that contains always zero.
43 // this is the unified register number
45 int UltraSparcRegInfo::getZeroRegNum() const {
46 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
47 SparcIntRegClass::g0);
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
53 unsigned UltraSparcRegInfo::getCallAddressReg() const {
54 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
55 SparcIntRegClass::o7);
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.
62 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
63 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
64 SparcIntRegClass::i7);
67 // Register get name implementations...
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",
75 "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
79 const char * const SparcIntRegClass::getRegName(unsigned reg) {
80 assert(reg < NumOfAllRegs);
81 return IntRegNames[reg];
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"
94 const char * const SparcFloatRegClass::getRegName(unsigned reg) {
95 assert (reg < NumOfAllRegs);
96 return FloatRegNames[reg];
100 static const char * const IntCCRegNames[] = {
104 const char * const SparcIntCCRegClass::getRegName(unsigned reg) {
106 return IntCCRegNames[reg];
109 static const char * const FloatCCRegNames[] = {
110 "fcc0", "fcc1", "fcc2", "fcc3"
113 const char * const SparcFloatCCRegClass::getRegName(unsigned reg) {
115 return FloatCCRegNames[reg];
118 // given the unified register number, this gives the name
119 // for generating assembly code or debugging.
121 const char * const UltraSparcRegInfo::getUnifiedRegName(int reg) const {
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 */
133 assert(0 && "Invalid register number");
137 // Get unified reg number for frame pointer
138 unsigned UltraSparcRegInfo::getFramePointer() const {
139 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
140 SparcIntRegClass::i6);
143 // Get unified reg number for stack pointer
144 unsigned UltraSparcRegInfo::getStackPointer() const {
145 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
146 SparcIntRegClass::o6);
150 //---------------------------------------------------------------------------
151 // Finds whether a call is an indirect call
152 //---------------------------------------------------------------------------
155 isVarArgsFunction(const Type *funcType) {
156 return cast<FunctionType>(cast<PointerType>(funcType)
157 ->getElementType())->isVarArg();
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);
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.
176 // InvalidRegNum, if there is no int register available for the arg.
177 // regNum, otherwise (this is NOT the unified reg. num).
180 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
182 unsigned intArgNo, unsigned fpArgNo,
183 unsigned& regClassId) const
185 regClassId = IntRegClassID;
186 if (argNo >= NumOfIntArgRegs)
187 return InvalidRegNum;
189 return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
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.
198 // InvalidRegNum, if there is no int register available for the arg.
199 // regNum, otherwise (this is NOT the unified reg. num).
202 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
203 bool inCallee, bool isVarArgsCall,
205 unsigned intArgNo, unsigned fpArgNo,
206 unsigned& regClassId) const
209 return regNumForIntArg(inCallee, isVarArgsCall, argNo, intArgNo, fpArgNo,
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);
221 assert(0 && "Illegal FP register type");
227 //---------------------------------------------------------------------------
228 // Finds the return address of a call sparc specific call instruction
229 //---------------------------------------------------------------------------
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.
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");
245 case IntCCRegClassID: return IntCCRegType;
246 case FloatCCRegClassID: return FloatCCRegType;
247 default: assert( 0 && "Unknown reg class ID"); return 0;
251 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const {
252 return getRegType(LR->getRegClass()->getID(), LR->getType());
255 int UltraSparcRegInfo::getRegType(const Value *Val) const {
256 return getRegType(getRegClassIDOfValue(Val), Val->getType());
259 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const {
260 if (unifiedRegNum < 32)
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))
271 assert(0 && "Invalid unified register number in getRegType");
276 // To find the register class used for a specified Type
278 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
279 bool isCCReg) const {
280 Type::PrimitiveID ty = type->getPrimitiveID();
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
290 //std::cerr << "TypeID: " << ty << "\n";
291 assert(0 && "Cannot resolve register class for type");
296 return res + 2; // corresponidng condition code regiser
301 // To find the register class to which a specified register belongs
303 unsigned UltraSparcRegInfo::getRegClassIDOfReg(int unifiedRegNum) const {
304 unsigned classId = 0;
305 (void) getClassRegNum(unifiedRegNum, classId);
309 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
311 case IntRegType: return IntRegClassID;
312 case FPSingleRegType:
313 case FPDoubleRegType: return FloatRegClassID;
314 case IntCCRegType: return IntCCRegClassID;
315 case FloatCCRegType: return FloatCCRegClassID;
317 assert(0 && "Invalid register type in getRegClassIDOfRegType");
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 {
329 assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
331 // return address is always mapped to i7 so set it immediately
332 RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
333 SparcIntRegClass::i7));
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):
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) );
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,
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");
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);
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
384 // check if this is a varArgs function. needed for choosing regs.
385 bool isVarArgs = isVarArgsFunction(Meth->getType());
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) {
392 LiveRange *LR = LRI.getLiveRangeForValue(I);
393 assert(LR && "No live range found for method arg");
395 unsigned regType = getRegType(LR);
396 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
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);
404 if(regNum != InvalidRegNum)
405 LR->setSuggestedColor(regNum);
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,
417 AddedInstrns *FirstAI) const {
419 // check if this is a varArgs function. needed for choosing regs.
420 bool isVarArgs = isVarArgsFunction(Meth->getType());
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) {
429 LiveRange *LR = LRI.getLiveRangeForValue(I);
430 assert( LR && "No live range found for method arg");
432 unsigned regType = getRegType( LR );
433 unsigned RegClassID = (LR->getRegClass())->getID();
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)
438 bool isArgInReg = false;
439 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
440 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
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);
448 if(regNum != InvalidRegNum) {
450 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
453 if( LR->hasColor() ) { // if this arg received a register
455 unsigned UniLRReg = getUnifiedRegNum( RegClassID, LR->getColor() );
457 // if LR received the correct color, nothing to do
459 if( UniLRReg == UniArgReg )
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.
467 // if the arg is coming in UniArgReg register, it MUST go into
468 // the UniLRReg register
471 if( regClassIDOfArgReg != RegClassID ) {
472 assert(0 && "This could should work but it is not tested yet");
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.
478 RegClassID == FloatRegClassID &&
479 regClassIDOfArgReg == IntRegClassID &&
480 "This should only be an Int register for an FP argument");
482 int TmpOff = MachineCodeForMethod::get(Meth).pushTempValue(target,
483 getSpilledRegSize(regType));
484 cpReg2MemMI(FirstAI->InstrnsBefore,
485 UniArgReg, getFramePointer(), TmpOff, IntRegType);
487 cpMem2RegMI(FirstAI->InstrnsBefore,
488 getFramePointer(), TmpOff, UniLRReg, regType);
491 cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
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
499 const MachineFrameInfo& frameInfo = target.getFrameInfo();
501 frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
504 cpMem2RegMI(FirstAI->InstrnsBefore,
505 getFramePointer(), offsetFromFP, UniLRReg, regType);
508 } // if LR received a color
512 // Now, the LR did not receive a color. But it has a stack offset for
514 // So, if the arg is coming in UniArgReg register, we can just move
515 // that on to the stack pos of LR
519 if( regClassIDOfArgReg != RegClassID ) {
521 "FP arguments to a varargs function should be explicitly "
522 "copied to/from int registers by instruction selection!");
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.
527 assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
528 "This should only be an Int register for an FP argument");
530 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
531 getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
534 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
535 getFramePointer(), LR->getSpillOffFromFP(), regType);
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)
547 const MachineFrameInfo& frameInfo = target.getFrameInfo();
549 frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
552 LR->modifySpillOffFromFP( offsetFromFP );
557 } // for each incoming argument
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,
569 std::vector<RegClass *> RCList) const {
570 assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
572 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
574 suggestReg4CallAddr(CallMI, LRI, RCList);
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.
580 // the return value cannot have a LR in machine instruction since it is
581 // only defined by the call instruction
583 // if type is not void, create a new live range and set its
584 // register class and add to LRI
586 const Value *RetVal = argDesc->getReturnValue();
589 assert ((!LRI.getLiveRangeForValue(RetVal)) &&
590 "LR for ret Value of call already definded!");
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);
599 // now suggest a register depending on the register class of ret arg
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");
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
614 unsigned NumOfCallArgs = argDesc->getNumArgs();
616 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
617 i < NumOfCallArgs; ++i, ++argNo) {
619 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
621 // get the LR of call operand (parameter)
622 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
624 // not possible to have a null LR since all args (even consts)
625 // must be defined before
627 cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) << "\n";
628 assert(0 && "NO LR for call arg");
631 unsigned regType = getRegType( LR );
632 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
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);
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);
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();
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,
659 assert(copyRegNum != InvalidRegNum);
660 LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy);
661 copyLR->setSuggestedColor(copyRegNum);
664 } // for all call arguments
669 //---------------------------------------------------------------------------
670 // Helper method for UltraSparcRegInfo::colorCallArgs().
671 //---------------------------------------------------------------------------
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)
683 bool isArgInReg = false;
684 unsigned UniArgReg = MAXINT; // unused unless initialized below
685 if (UniArgRegOrNone != InvalidRegNum)
688 UniArgReg = (unsigned) UniArgRegOrNone;
689 CallMI->getRegsUsed().insert(UniArgReg); // mark the reg as used
692 if (LR->hasColor()) {
693 unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
695 // if LR received the correct color, nothing to do
696 if( isArgInReg && UniArgReg == UniLRReg )
699 // The LR is allocated to a register UniLRReg and must be copied
700 // to UniArgReg or to the stack slot.
703 // Copy UniLRReg to UniArgReg
704 cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
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);
714 } else { // LR is not colored (i.e., spilled)
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
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.
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);
736 MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
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)
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
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);
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 //---------------------------------------------------------------------------
770 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
772 AddedInstrns *CallAI,
774 const BasicBlock *BB) const {
776 assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
778 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
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
786 const Value *RetVal = argDesc->getReturnValue();
789 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
792 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
793 assert(RetValLR && "ERR:No LR for non-void return value");
796 unsigned RegClassID = (RetValLR->getRegClass())->getID();
797 bool recvCorrectColor;
798 unsigned CorrectCol; // correct color for ret value
799 unsigned UniRetReg; // unified number for CorrectCol
801 if(RegClassID == IntRegClassID)
802 CorrectCol = SparcIntRegClass::o0;
803 else if(RegClassID == FloatRegClassID)
804 CorrectCol = SparcFloatRegClass::f0;
806 assert( 0 && "Unknown RegClass");
810 // convert to unified number
811 UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
813 // Mark the register as used by this instruction
814 CallMI->getRegsUsed().insert(UniRetReg);
816 // if the LR received the correct color, NOTHING to do
817 recvCorrectColor = RetValLR->hasColor()? RetValLR->getColor() == CorrectCol
820 // if we didn't receive the correct color for some reason,
821 // put copy instruction
822 if( !recvCorrectColor ) {
824 unsigned regType = getRegType( RetValLR );
826 if( RetValLR->hasColor() ) {
828 unsigned UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
830 // the return value is coming in UniRetReg but has to go into
833 cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
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
841 cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
842 getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
845 } // the LR didn't receive the suggested color
847 } // if there a return value
850 //-------------------------------------------
851 // Now color all args of the call instruction
852 //-------------------------------------------
854 std::vector<MachineInstr *> AddedInstrnsBefore;
856 unsigned NumOfCallArgs = argDesc->getNumArgs();
858 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
859 i < NumOfCallArgs; ++i, ++argNo) {
861 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
863 // get the LR of call operand (parameter)
864 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
866 unsigned RegClassID = getRegClassIDOfValue( CallArg);
867 unsigned regType = getRegType( RegClassID, CallArg->getType() );
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)
872 bool isArgInReg = false;
873 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
874 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
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);
886 if(regNum != InvalidRegNum) {
888 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
889 assert(regClassIDOfArgReg == RegClassID &&
890 "Moving values between reg classes must happen during selection");
893 // not possible to have a null LR since all args (even consts)
894 // must be defined before
896 cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) <<"\n";
897 assert(LR && "NO LR for call arg");
900 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
901 UniArgReg, argNo, AddedInstrnsBefore);
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();
910 assert(regType != IntRegType && argCopy->getType()->isInteger()
911 && "Must be passing copy of FP argument in int register");
913 unsigned copyRegClassID = getRegClassIDOfValue(argCopy);
914 unsigned copyRegType = getRegType(copyRegClassID, argCopy->getType());
916 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
917 argNo, intArgNo, fpArgNo-1,
919 assert(copyRegNum != InvalidRegNum);
920 assert(regClassIDOfArgReg == copyRegClassID &&
921 "Moving values between reg classes must happen during selection");
923 InitializeOutgoingArg(CallMI, CallAI, PRA,
924 LRI.getLiveRangeForValue(argCopy), copyRegType,
925 copyRegClassID, copyRegNum, argNo,
929 if (regNum != InvalidRegNum &&
930 argDesc->getArgInfo(i).usesStackSlot())
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);
938 } // for each parameter in call instruction
940 // If we added any instruction before the call instruction, verify
941 // that they are in the proper order and if not, reorder them
943 std::vector<MachineInstr *> ReorderedVec;
944 if (!AddedInstrnsBefore.empty()) {
947 cerr << "\nCalling reorder with instrns: \n";
948 for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
949 cerr << *(AddedInstrnsBefore[i]);
952 OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
953 assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
954 && "Dropped some instructions when reordering!");
957 cerr << "\nAfter reordering instrns: \n";
958 for(unsigned i = 0; i < ReorderedVec.size(); i++)
959 cerr << *ReorderedVec[i];
963 // Now insert caller saving code for this call instruction
965 insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
968 // Then insert the final reordered code for the call arguments.
970 for(unsigned i=0; i < ReorderedVec.size(); i++)
971 CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
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 {
981 assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
983 suggestReg4RetAddr(RetMI, LRI);
985 // if there is an implicit ref, that has to be the ret value
986 if( RetMI->getNumImplicitRefs() > 0 ) {
988 // The first implicit operand is the return value of a return instr
989 const Value *RetVal = RetMI->getImplicitRef(0);
991 LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
994 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
995 assert(0 && "No LR for return value of non-void method");
998 unsigned RegClassID = (LR->getRegClass())->getID();
1000 if (RegClassID == IntRegClassID)
1001 LR->setSuggestedColor(SparcIntRegClass::i0);
1002 else if (RegClassID == FloatRegClassID)
1003 LR->setSuggestedColor(SparcFloatRegClass::f0);
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,
1017 AddedInstrns *RetAI) const {
1019 assert((UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode()));
1021 // if there is an implicit ref, that has to be the ret value
1022 if(RetMI->getNumImplicitRefs() > 0) {
1024 // The first implicit operand is the return value of a return instr
1025 const Value *RetVal = RetMI->getImplicitRef(0);
1027 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
1030 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
1031 // assert( LR && "No LR for return value of non-void method");
1035 unsigned RegClassID = getRegClassIDOfValue(RetVal);
1036 unsigned regType = getRegType( RetVal );
1038 unsigned CorrectCol;
1039 if(RegClassID == IntRegClassID)
1040 CorrectCol = SparcIntRegClass::i0;
1041 else if(RegClassID == FloatRegClassID)
1042 CorrectCol = SparcFloatRegClass::f0;
1044 assert (0 && "Unknown RegClass");
1048 // convert to unified number
1049 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1051 // Mark the register as used by this instruction
1052 RetMI->getRegsUsed().insert(UniRetReg);
1054 // if the LR received the correct color, NOTHING to do
1056 if (LR->hasColor() && LR->getColor() == CorrectCol)
1059 if (LR->hasColor()) {
1061 // We are here because the LR was allocted a regiter
1062 // It may be the suggested register or not
1064 // copy the LR of retun value to i0 or f0
1066 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
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);
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";
1078 } // if there is a return value
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.
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 //---------------------------------------------------------------------------
1092 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1093 int& scratchRegType) const
1095 if (RegType == IntCCRegType)
1097 scratchRegType = IntRegType;
1103 //---------------------------------------------------------------------------
1104 // Copy from a register to register. Register number must be the unified
1106 //---------------------------------------------------------------------------
1109 UltraSparcRegInfo::cpReg2RegMI(vector<MachineInstr*>& mvec,
1112 int RegType) const {
1113 assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1114 "Invalid Register");
1116 MachineInstr * MI = NULL;
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);
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);
1135 case FloatCCRegType:
1136 assert(0 && "Cannot copy FPCC register to any other register");
1140 MI = Create3OperandInstr_Reg(ADD, SrcReg, getZeroRegNum(), DestReg);
1143 case FPSingleRegType:
1144 MI = Create2OperandInstr_Reg(FMOVS, SrcReg, DestReg);
1147 case FPDoubleRegType:
1148 MI = Create2OperandInstr_Reg(FMOVD, SrcReg, DestReg);
1152 assert(0 && "Unknown RegType");
1160 //---------------------------------------------------------------------------
1161 // Copy from a register to memory (i.e., Store). Register number must
1162 // be the unified register number
1163 //---------------------------------------------------------------------------
1167 UltraSparcRegInfo::cpReg2MemMI(vector<MachineInstr*>& mvec,
1169 unsigned DestPtrReg,
1170 int Offset, int RegType,
1171 int scratchReg) const {
1172 MachineInstr * MI = NULL;
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,
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,
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,
1202 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1203 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1205 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1206 MI = Create2OperandInstr_Reg(RDCCR, SrcReg+1, scratchReg);
1209 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
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,
1223 assert(0 && "Unknown RegType in cpReg2MemMI");
1228 //---------------------------------------------------------------------------
1229 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1231 //---------------------------------------------------------------------------
1235 UltraSparcRegInfo::cpMem2RegMI(vector<MachineInstr*>& mvec,
1240 int scratchReg) const {
1241 MachineInstr * MI = NULL;
1244 MI = new MachineInstr(LDX, 3);
1245 MI->SetMachineOperandReg(0, SrcPtrReg, false);
1246 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1248 MI->SetMachineOperandReg(2, DestReg, true);
1252 case FPSingleRegType:
1253 MI = new MachineInstr(LD, 3);
1254 MI->SetMachineOperandReg(0, SrcPtrReg, false);
1255 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1257 MI->SetMachineOperandReg(2, DestReg, true);
1261 case FPDoubleRegType:
1262 MI = new MachineInstr(LDD, 3);
1263 MI->SetMachineOperandReg(0, SrcPtrReg, false);
1264 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1266 MI->SetMachineOperandReg(2, DestReg, true);
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);
1275 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1276 MI = Create2OperandInstr_Reg(WRCCR, scratchReg, DestReg+1);
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,
1287 MI->SetMachineOperandReg(2, DestReg, true);
1292 assert(0 && "Unknown RegType in cpMem2RegMI");
1297 //---------------------------------------------------------------------------
1298 // Generate a copy instruction to copy a value to another. Temporarily
1299 // used by PhiElimination code.
1300 //---------------------------------------------------------------------------
1304 UltraSparcRegInfo::cpValue2Value(Value *Src,
1306 vector<MachineInstr*>& mvec) const {
1307 int RegType = getRegType( Src );
1309 assert( (RegType==getRegType(Src)) && "Src & Dest are diff types");
1311 MachineInstr * MI = NULL;
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);
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);
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);
1335 assert(0 && "Unknow RegType in CpValu2Value");
1347 //----------------------------------------------------------------------------
1348 // This method inserts caller saving/restoring instructons before/after
1349 // a call machine instruction. The caller saving/restoring instructions are
1352 // ** caller saving instructions
1353 // other instructions inserted for the call by ColorCallArg
1355 // other instructions inserted for the call ColorCallArg
1356 // ** caller restoring instructions
1358 //----------------------------------------------------------------------------
1362 UltraSparcRegInfo::insertCallerSavingCode(vector<MachineInstr*>& instrnsBefore,
1363 vector<MachineInstr*>& instrnsAfter,
1364 MachineInstr *CallMI,
1365 const BasicBlock *BB,
1366 PhyRegAlloc &PRA) const
1368 assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
1370 // has set to record which registers were saved/restored
1372 hash_set<unsigned> PushedRegSet;
1374 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
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.
1384 const Value *RetVal = argDesc->getReturnValue();
1387 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1388 assert(RetValLR && "No LR for RetValue of call");
1390 if (RetValLR->hasColor())
1391 PushedRegSet.insert(
1392 getUnifiedRegNum((RetValLR->getRegClass())->getID(),
1393 RetValLR->getColor() ) );
1396 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1397 ValueSet::const_iterator LIt = LVSetAft.begin();
1399 // for each live var in live variable set after machine inst
1400 for( ; LIt != LVSetAft.end(); ++LIt) {
1402 // get the live range corresponding to live var
1403 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1405 // LR can be null if it is a const since a const
1406 // doesn't have a dominating def - see Assumptions above
1409 if( LR->hasColor() ) {
1411 unsigned RCID = (LR->getRegClass())->getID();
1412 unsigned Color = LR->getColor();
1414 if ( isRegVolatile(RCID, Color) ) {
1416 // if the value is in both LV sets (i.e., live before and after
1417 // the call machine instruction)
1419 unsigned Reg = getUnifiedRegNum(RCID, Color);
1421 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1423 // if we haven't already pushed that register
1425 unsigned RegType = getRegType( LR );
1427 // Now get two instructions - to push on stack and pop from stack
1428 // and add them to InstrnsBefore and InstrnsAfter of the
1431 int StackOff = PRA.mcInfo.pushTempValue(target,
1432 getSpilledRegSize(RegType));
1434 vector<MachineInstr*> AdIBef, AdIAft;
1436 //---- Insert code for pushing the reg on stack ----------
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
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);
1454 if (AdIBef.size() > 0)
1455 instrnsBefore.insert(instrnsBefore.end(),
1456 AdIBef.begin(), AdIBef.end());
1458 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1461 if (AdIAft.size() > 0)
1462 instrnsBefore.insert(instrnsBefore.end(),
1463 AdIAft.begin(), AdIAft.end());
1465 //---- Insert code for popping the reg from the stack ----------
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.
1472 scratchRegType = -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);
1482 if (AdIBef.size() > 0)
1483 instrnsAfter.insert(instrnsAfter.end(),
1484 AdIBef.begin(), AdIBef.end());
1486 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1489 if (AdIAft.size() > 0)
1490 instrnsAfter.insert(instrnsAfter.end(),
1491 AdIAft.begin(), AdIAft.end());
1493 PushedRegSet.insert(Reg);
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));
1504 } // if not already pushed
1506 } // if LR has a volatile color
1508 } // if LR has color
1510 } // if there is a LR for Var
1512 } // for each value in the LV set after instruction
1516 //---------------------------------------------------------------------------
1517 // Print the register assigned to a LR
1518 //---------------------------------------------------------------------------
1520 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1521 unsigned RegClassID = (LR->getRegClass())->getID();
1522 cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1524 if (!LR->hasColor()) {
1525 cerr << " - could not find a color\n";
1529 // if a color is found
1531 cerr << " colored with color "<< LR->getColor();
1533 if (RegClassID == IntRegClassID) {
1534 cerr<< " [" << SparcIntRegClass::getRegName(LR->getColor()) << "]\n";
1536 } else if (RegClassID == FloatRegClassID) {
1537 cerr << "[" << SparcFloatRegClass::getRegName(LR->getColor());
1538 if( LR->getType() == Type::DoubleTy)
1539 cerr << "+" << SparcFloatRegClass::getRegName(LR->getColor()+1);
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.
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.
1553 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1554 // this method is called.
1556 // This method uses two vectors for efficiency in accessing
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.
1562 // All the uses are before THE def to a register
1563 //---------------------------------------------------------------------------
1565 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1566 std::vector<MachineInstr*> &OrdVec,
1567 PhyRegAlloc &PRA) const{
1570 Problem: We can have instructions inserted by RegAlloc like
1572 2. add %oy %g0 %oz, where z!=x or z==x
1574 This is wrong since %oy used by 2 is overwritten by 1
1577 We re-order the instructions so that the uses are before the defs
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
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.
1598 bool DebugPrint = false;
1601 CouldMoveAll = true;
1602 std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1604 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1606 // for each instruction in the UnordVec do ...
1608 MachineInstr *DefInst = *DefIt;
1610 if( DefInst == NULL) continue;
1612 //cerr << "\nInst in UnordVec = " << *DefInst;
1614 // last operand is the def (unless for a store which has no def reg)
1615 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1617 if( DefOp.opIsDef() &&
1618 DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1620 // If the operand in DefInst is a def ...
1622 bool DefEqUse = false;
1624 std::vector<MachineInstr *>::iterator UseIt = DefIt;
1627 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1629 MachineInstr *UseInst = *UseIt;
1630 if( UseInst == NULL) continue;
1632 // for each inst (UseInst) that is below the DefInst do ...
1633 MachineOperand& UseOp = UseInst->getOperand(0);
1635 if( ! UseOp.opIsDef() &&
1636 UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1638 // if use is a register ...
1640 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1642 // if Def and this use are the same, it means that this use
1643 // is destroyed by a def before it is used
1645 // cerr << "\nCouldn't move " << *DefInst;
1648 CouldMoveAll = false;
1651 } // if two registers are equal
1653 } // if use is a register
1655 }// for all use instructions
1659 // after examining all the instructions that follow the DefInst
1660 // if there are no dependencies, we can move it to the OrdVec
1662 // cerr << "Moved to Ord: " << *DefInst;
1664 moveInst2OrdVec(OrdVec, DefInst, PRA);
1666 //OrdVec.push_back(DefInst);
1668 // mark the pos of DefInst with NULL to indicate that it is
1673 } // if Def is a machine register
1675 } // for all instructions in the UnordVec
1678 } while(!CouldMoveAll);
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]);
1691 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1692 MachineInstr *UnordInst,
1693 PhyRegAlloc &PRA) const {
1694 MachineOperand& UseOp = UnordInst->getOperand(0);
1696 if( ! UseOp.opIsDef() &&
1697 UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1699 // for the use of UnordInst, see whether there is a defining instr
1700 // before in the OrdVec
1701 bool DefEqUse = false;
1703 std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1705 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1707 MachineInstr *OrdInst = *OrdIt ;
1709 MachineOperand& DefOp =
1710 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1712 if( DefOp.opIsDef() &&
1713 DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1715 //cerr << "\nDefining Ord Inst: " << *OrdInst;
1717 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
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.
1728 const int UReg = DefOp.getMachineRegNum();
1729 const int RegType = getRegType(UReg);
1730 MachineInstr *AdIBef, *AdIAft;
1732 const int StackOff = PRA.mcInfo.pushTempValue(target,
1733 getSpilledRegSize(RegType));
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
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();
1749 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1751 cerr << "\nFixed CIRCULAR references by reordering";
1754 cerr << "\nBefore CIRCULAR Reordering:\n";
1758 cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1759 for(unsigned i=0; i < OrdVec.size(); i++)
1760 cerr << *(OrdVec[i]);
1763 // Do not copy the UseInst to OrdVec
1767 }// if two registers are equal
1769 } // if Def is a register
1771 } // for each instr in OrdVec
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;
1780 }// if the operand in UnordInst is a use