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/MachineFunction.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), 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 //---------------------------------------------------------------------------
355 UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
356 LiveRangeInfo& LRI) const
358 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
359 const Value *RetAddrVal = argDesc->getReturnAddrReg();
360 assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
362 // A LR must already exist for the return address.
363 LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
364 assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
366 unsigned RegClassID = RetAddrLR->getRegClass()->getID();
367 RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
372 //---------------------------------------------------------------------------
373 // This method will suggest colors to incoming args to a method.
374 // According to the Sparc ABI, the first 6 incoming args are in
375 // %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
376 // If the arg is passed on stack due to the lack of regs, NOTHING will be
377 // done - it will be colored (or spilled) as a normal live range.
378 //---------------------------------------------------------------------------
379 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth,
380 LiveRangeInfo& LRI) const
382 // check if this is a varArgs function. needed for choosing regs.
383 bool isVarArgs = isVarArgsFunction(Meth->getType());
385 // for each argument. count INT and FP arguments separately.
386 unsigned argNo=0, intArgNo=0, fpArgNo=0;
387 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
388 I != E; ++I, ++argNo) {
390 LiveRange *LR = LRI.getLiveRangeForValue(I);
391 assert(LR && "No live range found for method arg");
393 unsigned regType = getRegType(LR);
394 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
396 int regNum = (regType == IntRegType)
397 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
398 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
399 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
400 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
402 if(regNum != InvalidRegNum)
403 LR->setSuggestedColor(regNum);
408 //---------------------------------------------------------------------------
409 // This method is called after graph coloring to move incoming args to
410 // the correct hardware registers if they did not receive the correct
411 // (suggested) color through graph coloring.
412 //---------------------------------------------------------------------------
413 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth,
415 AddedInstrns *FirstAI) const {
417 // check if this is a varArgs function. needed for choosing regs.
418 bool isVarArgs = isVarArgsFunction(Meth->getType());
422 // for each argument. count INT and FP arguments separately.
423 unsigned argNo=0, intArgNo=0, fpArgNo=0;
424 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
425 I != E; ++I, ++argNo) {
427 LiveRange *LR = LRI.getLiveRangeForValue(I);
428 assert( LR && "No live range found for method arg");
430 unsigned regType = getRegType( LR );
431 unsigned RegClassID = (LR->getRegClass())->getID();
433 // Find whether this argument is coming in a register (if not, on stack)
434 // Also find the correct register the argument must use (UniArgReg)
436 bool isArgInReg = false;
437 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
438 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
440 int regNum = (regType == IntRegType)
441 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
442 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
443 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
444 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
446 if(regNum != InvalidRegNum) {
448 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
451 if( LR->hasColor() ) { // if this arg received a register
453 unsigned UniLRReg = getUnifiedRegNum( RegClassID, LR->getColor() );
455 // if LR received the correct color, nothing to do
457 if( UniLRReg == UniArgReg )
460 // We are here because the LR did not receive the suggested
461 // but LR received another register.
462 // Now we have to copy the %i reg (or stack pos of arg)
463 // to the register the LR was colored with.
465 // if the arg is coming in UniArgReg register, it MUST go into
466 // the UniLRReg register
469 if( regClassIDOfArgReg != RegClassID ) {
470 assert(0 && "This could should work but it is not tested yet");
472 // It is a variable argument call: the float reg must go in a %o reg.
473 // We have to move an int reg to a float reg via memory.
476 RegClassID == FloatRegClassID &&
477 regClassIDOfArgReg == IntRegClassID &&
478 "This should only be an Int register for an FP argument");
480 int TmpOff = MachineFunction::get(Meth).pushTempValue(target,
481 getSpilledRegSize(regType));
482 cpReg2MemMI(FirstAI->InstrnsBefore,
483 UniArgReg, getFramePointer(), TmpOff, IntRegType);
485 cpMem2RegMI(FirstAI->InstrnsBefore,
486 getFramePointer(), TmpOff, UniLRReg, regType);
489 cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
494 // Now the arg is coming on stack. Since the LR recieved a register,
495 // we just have to load the arg on stack into that register
497 const MachineFrameInfo& frameInfo = target.getFrameInfo();
499 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
502 cpMem2RegMI(FirstAI->InstrnsBefore,
503 getFramePointer(), offsetFromFP, UniLRReg, regType);
506 } // if LR received a color
510 // Now, the LR did not receive a color. But it has a stack offset for
512 // So, if the arg is coming in UniArgReg register, we can just move
513 // that on to the stack pos of LR
517 if( regClassIDOfArgReg != RegClassID ) {
519 "FP arguments to a varargs function should be explicitly "
520 "copied to/from int registers by instruction selection!");
522 // It must be a float arg for a variable argument call, which
523 // must come in a %o reg. Move the int reg to the stack.
525 assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
526 "This should only be an Int register for an FP argument");
528 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
529 getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
532 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
533 getFramePointer(), LR->getSpillOffFromFP(), regType);
539 // Now the arg is coming on stack. Since the LR did NOT
540 // recieved a register as well, it is allocated a stack position. We
541 // can simply change the stack position of the LR. We can do this,
542 // since this method is called before any other method that makes
543 // uses of the stack pos of the LR (e.g., updateMachineInstr)
545 const MachineFrameInfo& frameInfo = target.getFrameInfo();
547 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
550 LR->modifySpillOffFromFP( offsetFromFP );
555 } // for each incoming argument
561 //---------------------------------------------------------------------------
562 // This method is called before graph coloring to suggest colors to the
563 // outgoing call args and the return value of the call.
564 //---------------------------------------------------------------------------
565 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI,
566 LiveRangeInfo& LRI) const {
567 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
569 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
571 suggestReg4CallAddr(CallMI, LRI);
573 // First color the return value of the call instruction, if any.
574 // The return value will be in %o0 if the value is an integer type,
575 // or in %f0 if the value is a float type.
577 if (const Value *RetVal = argDesc->getReturnValue()) {
578 LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
579 assert(RetValLR && "No LR for return Value of call!");
581 unsigned RegClassID = RetValLR->getRegClass()->getID();
583 // now suggest a register depending on the register class of ret arg
584 if( RegClassID == IntRegClassID )
585 RetValLR->setSuggestedColor(SparcIntRegClass::o0);
586 else if (RegClassID == FloatRegClassID )
587 RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
588 else assert( 0 && "Unknown reg class for return value of call\n");
591 // Now suggest colors for arguments (operands) of the call instruction.
592 // Colors are suggested only if the arg number is smaller than the
593 // the number of registers allocated for argument passing.
594 // Now, go thru call args - implicit operands of the call MI
596 unsigned NumOfCallArgs = argDesc->getNumArgs();
598 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
599 i < NumOfCallArgs; ++i, ++argNo) {
601 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
603 // get the LR of call operand (parameter)
604 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
605 assert (LR && "Must have a LR for all arguments since "
606 "all args (even consts) must be defined before");
608 unsigned regType = getRegType( LR );
609 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
611 // Choose a register for this arg depending on whether it is
612 // an INT or FP value. Here we ignore whether or not it is a
613 // varargs calls, because FP arguments will be explicitly copied
614 // to an integer Value and handled under (argCopy != NULL) below.
615 int regNum = (regType == IntRegType)
616 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
617 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
618 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
619 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
621 // If a register could be allocated, use it.
622 // If not, do NOTHING as this will be colored as a normal value.
623 if(regNum != InvalidRegNum)
624 LR->setSuggestedColor(regNum);
626 // Repeat for the second copy of the argument, which would be
627 // an FP argument being passed to a function with no prototype
628 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
631 assert(regType != IntRegType && argCopy->getType()->isInteger()
632 && "Must be passing copy of FP argument in int register");
633 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
634 argNo, intArgNo, fpArgNo-1,
636 assert(copyRegNum != InvalidRegNum);
637 LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy);
638 copyLR->setSuggestedColor(copyRegNum);
641 } // for all call arguments
646 //---------------------------------------------------------------------------
647 // Helper method for UltraSparcRegInfo::colorCallArgs().
648 //---------------------------------------------------------------------------
651 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
652 AddedInstrns *CallAI,
653 PhyRegAlloc &PRA, LiveRange* LR,
654 unsigned regType, unsigned RegClassID,
655 int UniArgRegOrNone, unsigned int argNo,
656 std::vector<MachineInstr *>& AddedInstrnsBefore)
660 bool isArgInReg = false;
661 unsigned UniArgReg = MAXINT; // unused unless initialized below
662 if (UniArgRegOrNone != InvalidRegNum)
665 UniArgReg = (unsigned) UniArgRegOrNone;
666 CallMI->insertUsedReg(UniArgReg); // mark the reg as used
669 if (LR->hasColor()) {
670 unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
672 // if LR received the correct color, nothing to do
673 if( isArgInReg && UniArgReg == UniLRReg )
676 // The LR is allocated to a register UniLRReg and must be copied
677 // to UniArgReg or to the stack slot.
680 // Copy UniLRReg to UniArgReg
681 cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
684 // Copy UniLRReg to the stack to pass the arg on stack.
685 const MachineFrameInfo& frameInfo = target.getFrameInfo();
686 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
687 cpReg2MemMI(CallAI->InstrnsBefore,
688 UniLRReg, getStackPointer(), argOffset, regType);
691 } else { // LR is not colored (i.e., spilled)
694 // Insert a load instruction to load the LR to UniArgReg
695 cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
696 LR->getSpillOffFromFP(), UniArgReg, regType);
697 // Now add the instruction
701 // Now, we have to pass the arg on stack. Since LR also did NOT
702 // receive a register we have to move an argument in memory to
703 // outgoing parameter on stack.
704 // Use TReg to load and store the value.
705 // Use TmpOff to save TReg, since that may have a live value.
707 int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
708 int TmpOff = PRA.MF.pushTempValue(target,
709 getSpilledRegSize(getRegType(LR)));
710 const MachineFrameInfo& frameInfo = target.getFrameInfo();
711 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
713 MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
716 // (1) Save TReg on stack
717 // (2) Load LR value into TReg from stack pos of LR
718 // (3) Store Treg on outgoing Arg pos on stack
719 // (4) Load the old value of TReg from stack to TReg (restore it)
722 // When reverse pointers in MahineInstr are introduced:
723 // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
724 // needed only if this fails. Currently, we cannot call the
725 // above method since we cannot find LVSetBefore without the BB
727 // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
728 // AddedInstrnsBefore since these instructions must not be reordered.
729 cpReg2MemMI(CallAI->InstrnsBefore,
730 TReg, getFramePointer(), TmpOff, regType);
731 cpMem2RegMI(CallAI->InstrnsBefore,
732 getFramePointer(), LR->getSpillOffFromFP(), TReg, regType);
733 cpReg2MemMI(CallAI->InstrnsBefore,
734 TReg, getStackPointer(), argOffset, regType);
735 cpMem2RegMI(CallAI->InstrnsBefore,
736 getFramePointer(), TmpOff, TReg, regType);
741 //---------------------------------------------------------------------------
742 // After graph coloring, we have call this method to see whehter the return
743 // value and the call args received the correct colors. If not, we have
744 // to instert copy instructions.
745 //---------------------------------------------------------------------------
747 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
749 AddedInstrns *CallAI,
751 const BasicBlock *BB) const {
753 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
755 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
757 // First color the return value of the call.
758 // If there is a LR for the return value, it means this
759 // method returns a value
763 const Value *RetVal = argDesc->getReturnValue();
766 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
769 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
770 assert(RetValLR && "ERR:No LR for non-void return value");
773 unsigned RegClassID = (RetValLR->getRegClass())->getID();
774 bool recvCorrectColor;
775 unsigned CorrectCol; // correct color for ret value
776 unsigned UniRetReg; // unified number for CorrectCol
778 if(RegClassID == IntRegClassID)
779 CorrectCol = SparcIntRegClass::o0;
780 else if(RegClassID == FloatRegClassID)
781 CorrectCol = SparcFloatRegClass::f0;
783 assert( 0 && "Unknown RegClass");
787 // convert to unified number
788 UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
790 // Mark the register as used by this instruction
791 CallMI->insertUsedReg(UniRetReg);
793 // if the LR received the correct color, NOTHING to do
794 recvCorrectColor = RetValLR->hasColor()? RetValLR->getColor() == CorrectCol
797 // if we didn't receive the correct color for some reason,
798 // put copy instruction
799 if( !recvCorrectColor ) {
801 unsigned regType = getRegType( RetValLR );
803 if( RetValLR->hasColor() ) {
805 unsigned UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
807 // the return value is coming in UniRetReg but has to go into
810 cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
815 // if the LR did NOT receive a color, we have to move the return
816 // value coming in UniRetReg to the stack pos of spilled LR
818 cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
819 getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
822 } // the LR didn't receive the suggested color
824 } // if there a return value
827 //-------------------------------------------
828 // Now color all args of the call instruction
829 //-------------------------------------------
831 std::vector<MachineInstr *> AddedInstrnsBefore;
833 unsigned NumOfCallArgs = argDesc->getNumArgs();
835 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
836 i < NumOfCallArgs; ++i, ++argNo) {
838 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
840 // get the LR of call operand (parameter)
841 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
843 unsigned RegClassID = getRegClassIDOfValue( CallArg);
844 unsigned regType = getRegType( RegClassID, CallArg->getType() );
846 // Find whether this argument is coming in a register (if not, on stack)
847 // Also find the correct register the argument must use (UniArgReg)
849 bool isArgInReg = false;
850 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
851 unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
853 // Find the register that must be used for this arg, depending on
854 // whether it is an INT or FP value. Here we ignore whether or not it
855 // is a varargs calls, because FP arguments will be explicitly copied
856 // to an integer Value and handled under (argCopy != NULL) below.
857 int regNum = (regType == IntRegType)
858 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
859 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
860 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
861 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
863 if(regNum != InvalidRegNum) {
865 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
866 assert(regClassIDOfArgReg == RegClassID &&
867 "Moving values between reg classes must happen during selection");
870 // not possible to have a null LR since all args (even consts)
871 // must be defined before
873 cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) <<"\n";
874 assert(LR && "NO LR for call arg");
877 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
878 UniArgReg, argNo, AddedInstrnsBefore);
880 // Repeat for the second copy of the argument, which would be
881 // an FP argument being passed to a function with no prototype.
882 // It may either be passed as a copy in an integer register
883 // (in argCopy), or on the stack (useStackSlot).
884 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
887 assert(regType != IntRegType && argCopy->getType()->isInteger()
888 && "Must be passing copy of FP argument in int register");
890 unsigned copyRegClassID = getRegClassIDOfValue(argCopy);
891 unsigned copyRegType = getRegType(copyRegClassID, argCopy->getType());
893 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
894 argNo, intArgNo, fpArgNo-1,
896 assert(copyRegNum != InvalidRegNum);
897 assert(regClassIDOfArgReg == copyRegClassID &&
898 "Moving values between reg classes must happen during selection");
900 InitializeOutgoingArg(CallMI, CallAI, PRA,
901 LRI.getLiveRangeForValue(argCopy), copyRegType,
902 copyRegClassID, copyRegNum, argNo,
906 if (regNum != InvalidRegNum &&
907 argDesc->getArgInfo(i).usesStackSlot())
909 // Pass the argument via the stack in addition to regNum
910 assert(regType != IntRegType && "Passing an integer arg. twice?");
911 assert(!argCopy && "Passing FP arg in FP reg, INT reg, and stack?");
912 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
913 InvalidRegNum, argNo, AddedInstrnsBefore);
915 } // for each parameter in call instruction
917 // If we added any instruction before the call instruction, verify
918 // that they are in the proper order and if not, reorder them
920 std::vector<MachineInstr *> ReorderedVec;
921 if (!AddedInstrnsBefore.empty()) {
924 cerr << "\nCalling reorder with instrns: \n";
925 for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
926 cerr << *(AddedInstrnsBefore[i]);
929 OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
930 assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
931 && "Dropped some instructions when reordering!");
934 cerr << "\nAfter reordering instrns: \n";
935 for(unsigned i = 0; i < ReorderedVec.size(); i++)
936 cerr << *ReorderedVec[i];
940 // Now insert caller saving code for this call instruction
942 insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
945 // Then insert the final reordered code for the call arguments.
947 for(unsigned i=0; i < ReorderedVec.size(); i++)
948 CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
951 //---------------------------------------------------------------------------
952 // This method is called for an LLVM return instruction to identify which
953 // values will be returned from this method and to suggest colors.
954 //---------------------------------------------------------------------------
955 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI,
956 LiveRangeInfo &LRI) const {
958 assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
960 suggestReg4RetAddr(RetMI, LRI);
962 // if there is an implicit ref, that has to be the ret value
963 if( RetMI->getNumImplicitRefs() > 0 ) {
965 // The first implicit operand is the return value of a return instr
966 const Value *RetVal = RetMI->getImplicitRef(0);
968 LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
971 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
972 assert(0 && "No LR for return value of non-void method");
975 unsigned RegClassID = (LR->getRegClass())->getID();
977 if (RegClassID == IntRegClassID)
978 LR->setSuggestedColor(SparcIntRegClass::i0);
979 else if (RegClassID == FloatRegClassID)
980 LR->setSuggestedColor(SparcFloatRegClass::f0);
986 //---------------------------------------------------------------------------
987 // Colors the return value of a method to %i0 or %f0, if possible. If it is
988 // not possilbe to directly color the LR, insert a copy instruction to move
989 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we
990 // have to put a load instruction.
991 //---------------------------------------------------------------------------
992 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI,
994 AddedInstrns *RetAI) const {
996 assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
998 // if there is an implicit ref, that has to be the ret value
999 if(RetMI->getNumImplicitRefs() > 0) {
1001 // The first implicit operand is the return value of a return instr
1002 const Value *RetVal = RetMI->getImplicitRef(0);
1004 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
1007 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
1008 // assert( LR && "No LR for return value of non-void method");
1012 unsigned RegClassID = getRegClassIDOfValue(RetVal);
1013 unsigned regType = getRegType( RetVal );
1015 unsigned CorrectCol;
1016 if(RegClassID == IntRegClassID)
1017 CorrectCol = SparcIntRegClass::i0;
1018 else if(RegClassID == FloatRegClassID)
1019 CorrectCol = SparcFloatRegClass::f0;
1021 assert (0 && "Unknown RegClass");
1025 // convert to unified number
1026 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1028 // Mark the register as used by this instruction
1029 RetMI->insertUsedReg(UniRetReg);
1031 // if the LR received the correct color, NOTHING to do
1033 if (LR->hasColor() && LR->getColor() == CorrectCol)
1036 if (LR->hasColor()) {
1038 // We are here because the LR was allocted a regiter
1039 // It may be the suggested register or not
1041 // copy the LR of retun value to i0 or f0
1043 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1045 // the LR received UniLRReg but must be colored with UniRetReg
1046 // to pass as the return value
1047 cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1049 else { // if the LR is spilled
1050 cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1051 LR->getSpillOffFromFP(), UniRetReg, regType);
1052 cerr << "\nCopied the return value from stack\n";
1055 } // if there is a return value
1059 //---------------------------------------------------------------------------
1060 // Check if a specified register type needs a scratch register to be
1061 // copied to/from memory. If it does, the reg. type that must be used
1062 // for scratch registers is returned in scratchRegType.
1064 // Only the int CC register needs such a scratch register.
1065 // The FP CC registers can (and must) be copied directly to/from memory.
1066 //---------------------------------------------------------------------------
1069 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1070 int& scratchRegType) const
1072 if (RegType == IntCCRegType)
1074 scratchRegType = IntRegType;
1080 //---------------------------------------------------------------------------
1081 // Copy from a register to register. Register number must be the unified
1083 //---------------------------------------------------------------------------
1086 UltraSparcRegInfo::cpReg2RegMI(vector<MachineInstr*>& mvec,
1089 int RegType) const {
1090 assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1091 "Invalid Register");
1093 MachineInstr * MI = NULL;
1098 if (getRegType(DestReg) == IntRegType)
1099 { // copy intCC reg to int reg
1100 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1101 MI = Create2OperandInstr_Reg(RDCCR, SrcReg+1, DestReg);
1104 { // copy int reg to intCC reg
1105 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1106 assert(getRegType(SrcReg) == IntRegType
1107 && "Can only copy CC reg to/from integer reg");
1108 MI = Create2OperandInstr_Reg(WRCCR, SrcReg, DestReg+1);
1112 case FloatCCRegType:
1113 assert(0 && "Cannot copy FPCC register to any other register");
1117 MI = Create3OperandInstr_Reg(ADD, SrcReg, getZeroRegNum(), DestReg);
1120 case FPSingleRegType:
1121 MI = Create2OperandInstr_Reg(FMOVS, SrcReg, DestReg);
1124 case FPDoubleRegType:
1125 MI = Create2OperandInstr_Reg(FMOVD, SrcReg, DestReg);
1129 assert(0 && "Unknown RegType");
1137 //---------------------------------------------------------------------------
1138 // Copy from a register to memory (i.e., Store). Register number must
1139 // be the unified register number
1140 //---------------------------------------------------------------------------
1144 UltraSparcRegInfo::cpReg2MemMI(vector<MachineInstr*>& mvec,
1146 unsigned DestPtrReg,
1147 int Offset, int RegType,
1148 int scratchReg) const {
1149 MachineInstr * MI = NULL;
1152 assert(target.getInstrInfo().constantFitsInImmedField(STX, Offset));
1153 MI = new MachineInstr(STX, 3);
1154 MI->SetMachineOperandReg(0, SrcReg);
1155 MI->SetMachineOperandReg(1, DestPtrReg);
1156 MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed,
1161 case FPSingleRegType:
1162 assert(target.getInstrInfo().constantFitsInImmedField(ST, Offset));
1163 MI = new MachineInstr(ST, 3);
1164 MI->SetMachineOperandReg(0, SrcReg);
1165 MI->SetMachineOperandReg(1, DestPtrReg);
1166 MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed,
1171 case FPDoubleRegType:
1172 assert(target.getInstrInfo().constantFitsInImmedField(STD, Offset));
1173 MI = new MachineInstr(STD, 3);
1174 MI->SetMachineOperandReg(0, SrcReg);
1175 MI->SetMachineOperandReg(1, DestPtrReg);
1176 MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed,
1182 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1183 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1185 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1186 MI = Create2OperandInstr_Reg(RDCCR, SrcReg+1, scratchReg);
1189 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1192 case FloatCCRegType:
1193 assert(0 && "Tell Vikram if this assertion fails: we may have to mask out the other bits here");
1194 assert(target.getInstrInfo().constantFitsInImmedField(STXFSR, Offset));
1195 MI = new MachineInstr(STXFSR, 3);
1196 MI->SetMachineOperandReg(0, SrcReg);
1197 MI->SetMachineOperandReg(1, DestPtrReg);
1198 MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed,
1204 assert(0 && "Unknown RegType in cpReg2MemMI");
1209 //---------------------------------------------------------------------------
1210 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1212 //---------------------------------------------------------------------------
1216 UltraSparcRegInfo::cpMem2RegMI(vector<MachineInstr*>& mvec,
1221 int scratchReg) const {
1222 MachineInstr * MI = NULL;
1225 assert(target.getInstrInfo().constantFitsInImmedField(LDX, Offset));
1226 MI = new MachineInstr(LDX, 3);
1227 MI->SetMachineOperandReg(0, SrcPtrReg);
1228 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1230 MI->SetMachineOperandReg(2, DestReg, true);
1234 case FPSingleRegType:
1235 assert(target.getInstrInfo().constantFitsInImmedField(LD, Offset));
1236 MI = new MachineInstr(LD, 3);
1237 MI->SetMachineOperandReg(0, SrcPtrReg);
1238 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1240 MI->SetMachineOperandReg(2, DestReg, true);
1244 case FPDoubleRegType:
1245 assert(target.getInstrInfo().constantFitsInImmedField(LDD, Offset));
1246 MI = new MachineInstr(LDD, 3);
1247 MI->SetMachineOperandReg(0, SrcPtrReg);
1248 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1250 MI->SetMachineOperandReg(2, DestReg, true);
1255 assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1256 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1257 cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1259 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1260 MI = Create2OperandInstr_Reg(WRCCR, scratchReg, DestReg+1);
1265 case FloatCCRegType:
1266 assert(0 && "Tell Vikram if this assertion fails: we may have to mask out the other bits here");
1267 assert(target.getInstrInfo().constantFitsInImmedField(LDXFSR, Offset));
1268 MI = new MachineInstr(LDXFSR, 3);
1269 MI->SetMachineOperandReg(0, SrcPtrReg);
1270 MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed,
1272 MI->SetMachineOperandReg(2, DestReg, true);
1277 assert(0 && "Unknown RegType in cpMem2RegMI");
1282 //---------------------------------------------------------------------------
1283 // Generate a copy instruction to copy a value to another. Temporarily
1284 // used by PhiElimination code.
1285 //---------------------------------------------------------------------------
1289 UltraSparcRegInfo::cpValue2Value(Value *Src,
1291 vector<MachineInstr*>& mvec) const {
1292 int RegType = getRegType( Src );
1294 assert( (RegType==getRegType(Src)) && "Src & Dest are diff types");
1296 MachineInstr * MI = NULL;
1300 MI = new MachineInstr(ADD, 3);
1301 MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1302 MI->SetMachineOperandReg(1, getZeroRegNum());
1303 MI->SetMachineOperandVal(2, MachineOperand:: MO_VirtualRegister, Dest, true);
1306 case FPSingleRegType:
1307 MI = new MachineInstr(FMOVS, 2);
1308 MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1309 MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1313 case FPDoubleRegType:
1314 MI = new MachineInstr(FMOVD, 2);
1315 MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1316 MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1320 assert(0 && "Unknow RegType in CpValu2Value");
1332 //----------------------------------------------------------------------------
1333 // This method inserts caller saving/restoring instructons before/after
1334 // a call machine instruction. The caller saving/restoring instructions are
1337 // ** caller saving instructions
1338 // other instructions inserted for the call by ColorCallArg
1340 // other instructions inserted for the call ColorCallArg
1341 // ** caller restoring instructions
1343 //----------------------------------------------------------------------------
1347 UltraSparcRegInfo::insertCallerSavingCode(vector<MachineInstr*>& instrnsBefore,
1348 vector<MachineInstr*>& instrnsAfter,
1349 MachineInstr *CallMI,
1350 const BasicBlock *BB,
1351 PhyRegAlloc &PRA) const
1353 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1355 // has set to record which registers were saved/restored
1357 hash_set<unsigned> PushedRegSet;
1359 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1361 // Now find the LR of the return value of the call
1362 // The last *implicit operand* is the return value of a call
1363 // Insert it to to he PushedRegSet since we must not save that register
1364 // and restore it after the call.
1365 // We do this because, we look at the LV set *after* the instruction
1366 // to determine, which LRs must be saved across calls. The return value
1367 // of the call is live in this set - but we must not save/restore it.
1369 const Value *RetVal = argDesc->getReturnValue();
1372 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1373 assert(RetValLR && "No LR for RetValue of call");
1375 if (RetValLR->hasColor())
1376 PushedRegSet.insert(
1377 getUnifiedRegNum((RetValLR->getRegClass())->getID(),
1378 RetValLR->getColor() ) );
1381 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1382 ValueSet::const_iterator LIt = LVSetAft.begin();
1384 // for each live var in live variable set after machine inst
1385 for( ; LIt != LVSetAft.end(); ++LIt) {
1387 // get the live range corresponding to live var
1388 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1390 // LR can be null if it is a const since a const
1391 // doesn't have a dominating def - see Assumptions above
1394 if( LR->hasColor() ) {
1396 unsigned RCID = (LR->getRegClass())->getID();
1397 unsigned Color = LR->getColor();
1399 if ( isRegVolatile(RCID, Color) ) {
1401 // if the value is in both LV sets (i.e., live before and after
1402 // the call machine instruction)
1404 unsigned Reg = getUnifiedRegNum(RCID, Color);
1406 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1408 // if we haven't already pushed that register
1410 unsigned RegType = getRegType( LR );
1412 // Now get two instructions - to push on stack and pop from stack
1413 // and add them to InstrnsBefore and InstrnsAfter of the
1416 int StackOff = PRA.MF.pushTempValue(target,
1417 getSpilledRegSize(RegType));
1419 vector<MachineInstr*> AdIBef, AdIAft;
1421 //---- Insert code for pushing the reg on stack ----------
1423 // We may need a scratch register to copy the saved value
1424 // to/from memory. This may itself have to insert code to
1425 // free up a scratch register. Any such code should go before
1427 int scratchRegType = -1;
1428 int scratchReg = -1;
1429 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1430 { // Find a register not live in the LVSet before CallMI
1431 const ValueSet &LVSetBef =
1432 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1433 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1434 CallMI, AdIBef, AdIAft);
1435 assert(scratchReg != getInvalidRegNum());
1436 CallMI->insertUsedReg(scratchReg);
1439 if (AdIBef.size() > 0)
1440 instrnsBefore.insert(instrnsBefore.end(),
1441 AdIBef.begin(), AdIBef.end());
1443 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1446 if (AdIAft.size() > 0)
1447 instrnsBefore.insert(instrnsBefore.end(),
1448 AdIAft.begin(), AdIAft.end());
1450 //---- Insert code for popping the reg from the stack ----------
1452 // We may need a scratch register to copy the saved value
1453 // from memory. This may itself have to insert code to
1454 // free up a scratch register. Any such code should go
1455 // after the save code.
1457 scratchRegType = -1;
1459 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1460 { // Find a register not live in the LVSet after CallMI
1461 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1462 CallMI, AdIBef, AdIAft);
1463 assert(scratchReg != getInvalidRegNum());
1464 CallMI->insertUsedReg(scratchReg);
1467 if (AdIBef.size() > 0)
1468 instrnsAfter.insert(instrnsAfter.end(),
1469 AdIBef.begin(), AdIBef.end());
1471 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1474 if (AdIAft.size() > 0)
1475 instrnsAfter.insert(instrnsAfter.end(),
1476 AdIAft.begin(), AdIAft.end());
1478 PushedRegSet.insert(Reg);
1481 cerr << "\nFor call inst:" << *CallMI;
1482 cerr << " -inserted caller saving instrs: Before:\n\t ";
1483 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1484 std::mem_fun(&MachineInstr::dump));
1485 cerr << " -and After:\n\t ";
1486 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1487 std::mem_fun(&MachineInstr::dump));
1489 } // if not already pushed
1491 } // if LR has a volatile color
1493 } // if LR has color
1495 } // if there is a LR for Var
1497 } // for each value in the LV set after instruction
1501 //---------------------------------------------------------------------------
1502 // Print the register assigned to a LR
1503 //---------------------------------------------------------------------------
1505 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1506 unsigned RegClassID = (LR->getRegClass())->getID();
1507 cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1509 if (!LR->hasColor()) {
1510 cerr << " - could not find a color\n";
1514 // if a color is found
1516 cerr << " colored with color "<< LR->getColor();
1518 if (RegClassID == IntRegClassID) {
1519 cerr<< " [" << SparcIntRegClass::getRegName(LR->getColor()) << "]\n";
1521 } else if (RegClassID == FloatRegClassID) {
1522 cerr << "[" << SparcFloatRegClass::getRegName(LR->getColor());
1523 if( LR->getType() == Type::DoubleTy)
1524 cerr << "+" << SparcFloatRegClass::getRegName(LR->getColor()+1);
1529 //---------------------------------------------------------------------------
1530 // This method examines instructions inserted by RegAlloc code before a
1531 // machine instruction to detect invalid orders that destroy values before
1532 // they are used. If it detects such conditions, it reorders the instructions.
1534 // The unordered instructions come in the UnordVec. These instructions are
1535 // instructions inserted by RegAlloc. All such instruction MUST have
1536 // their USES BEFORE THE DEFS after reordering.
1538 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1539 // this method is called.
1541 // This method uses two vectors for efficiency in accessing
1543 // Since instructions are inserted in RegAlloc, this assumes that the
1544 // first operand is the source reg and the last operand is the dest reg.
1545 // It also does not consider operands that are both use and def.
1547 // All the uses are before THE def to a register
1548 //---------------------------------------------------------------------------
1550 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1551 std::vector<MachineInstr*> &OrdVec,
1552 PhyRegAlloc &PRA) const{
1555 Problem: We can have instructions inserted by RegAlloc like
1557 2. add %oy %g0 %oz, where z!=x or z==x
1559 This is wrong since %oy used by 2 is overwritten by 1
1562 We re-order the instructions so that the uses are before the defs
1567 for each instruction 'DefInst' in the UnOrdVec
1568 for each instruction 'UseInst' that follows the DefInst
1569 if the reg defined by DefInst is used by UseInst
1570 mark DefInst as not movable in this iteration
1571 If DefInst is not marked as not-movable, move DefInst to OrdVec
1572 while all instructions in DefInst are moved to OrdVec
1574 For moving, we call the move2OrdVec(). It checks whether there is a def
1575 in it for the uses in the instruction to be added to OrdVec. If there
1576 are no preceding defs, it just appends the instruction. If there is a
1577 preceding def, it puts two instructions to save the reg on stack before
1578 the load and puts a restore at use.
1583 bool DebugPrint = false;
1586 CouldMoveAll = true;
1587 std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1589 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1591 // for each instruction in the UnordVec do ...
1593 MachineInstr *DefInst = *DefIt;
1595 if( DefInst == NULL) continue;
1597 //cerr << "\nInst in UnordVec = " << *DefInst;
1599 // last operand is the def (unless for a store which has no def reg)
1600 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1602 if (DefOp.opIsDef() &&
1603 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1605 // If the operand in DefInst is a def ...
1606 bool DefEqUse = false;
1608 std::vector<MachineInstr *>::iterator UseIt = DefIt;
1611 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1613 MachineInstr *UseInst = *UseIt;
1614 if( UseInst == NULL) continue;
1616 // for each inst (UseInst) that is below the DefInst do ...
1617 MachineOperand& UseOp = UseInst->getOperand(0);
1619 if (!UseOp.opIsDef() &&
1620 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1622 // if use is a register ...
1624 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1626 // if Def and this use are the same, it means that this use
1627 // is destroyed by a def before it is used
1629 // cerr << "\nCouldn't move " << *DefInst;
1632 CouldMoveAll = false;
1635 } // if two registers are equal
1637 } // if use is a register
1639 }// for all use instructions
1643 // after examining all the instructions that follow the DefInst
1644 // if there are no dependencies, we can move it to the OrdVec
1646 // cerr << "Moved to Ord: " << *DefInst;
1648 moveInst2OrdVec(OrdVec, DefInst, PRA);
1650 //OrdVec.push_back(DefInst);
1652 // mark the pos of DefInst with NULL to indicate that it is
1657 } // if Def is a machine register
1659 } // for all instructions in the UnordVec
1662 } while(!CouldMoveAll);
1664 if (DebugPrint && DEBUG_RA) {
1665 cerr << "\nAdded instructions were reordered to:\n";
1666 for(unsigned int i=0; i < OrdVec.size(); i++)
1667 cerr << *(OrdVec[i]);
1675 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1676 MachineInstr *UnordInst,
1677 PhyRegAlloc &PRA) const {
1678 MachineOperand& UseOp = UnordInst->getOperand(0);
1680 if (!UseOp.opIsDef() &&
1681 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1683 // for the use of UnordInst, see whether there is a defining instr
1684 // before in the OrdVec
1685 bool DefEqUse = false;
1687 std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1689 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1691 MachineInstr *OrdInst = *OrdIt ;
1693 MachineOperand& DefOp =
1694 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1696 if( DefOp.opIsDef() &&
1697 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1699 //cerr << "\nDefining Ord Inst: " << *OrdInst;
1701 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1703 // we are here because there is a preceding def in the OrdVec
1704 // for the use in this intr we are going to insert. This
1705 // happened because the original code was like:
1706 // 1. add %ox %g0 %oy
1707 // 2. add %oy %g0 %ox
1708 // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1709 // Now we are processing %ox of 1.
1712 int UReg = DefOp.getMachineRegNum();
1713 int RegType = getRegType(UReg);
1714 MachineInstr *AdIBef, *AdIAft;
1716 const int StackOff = PRA.MF.pushTempValue(target,
1717 getSpilledRegSize(RegType));
1719 // Save the UReg (%ox) on stack before it's destroyed
1720 vector<MachineInstr*> mvec;
1721 cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1722 for (vector<MachineInstr*>::iterator MI=mvec.begin(); MI != mvec.end(); ++MI) {
1723 OrdIt = OrdVec.insert(OrdIt, *MI);
1724 ++OrdIt; // OrdIt must still point to current instr we processed
1727 // Load directly into DReg (%oy)
1728 MachineOperand& DOp=
1729 (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1730 assert(DOp.opIsDef() && "Last operand is not the def");
1731 const int DReg = DOp.getMachineRegNum();
1733 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1736 cerr << "\nFixed CIRCULAR references by reordering:";
1737 cerr << "\nBefore CIRCULAR Reordering:\n";
1741 cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1742 for(unsigned i=0; i < OrdVec.size(); i++)
1743 cerr << *(OrdVec[i]);
1746 // Do not copy the UseInst to OrdVec
1750 }// if two registers are equal
1752 } // if Def is a register
1754 } // for each instr in OrdVec
1758 // We didn't find a def in the OrdVec, so just append this inst
1759 OrdVec.push_back( UnordInst );
1760 //cerr << "Reordered Inst (Moved Dn): " << *UnordInst;
1763 }// if the operand in UnordInst is a use