2 //***************************************************************************
7 // Register allocation for LLVM.
10 // 9/10/01 - Ruchira Sasanka - created.
11 //**************************************************************************/
13 #include "llvm/CodeGen/RegisterAllocation.h"
14 #include "llvm/CodeGen/PhyRegAlloc.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineCodeForMethod.h"
17 #include "llvm/Analysis/LiveVar/MethodLiveVarInfo.h"
18 #include "llvm/Analysis/LiveVar/ValueSet.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/MachineFrameInfo.h"
22 #include "llvm/Method.h"
23 #include "llvm/Type.h"
29 // ***TODO: There are several places we add instructions. Validate the order
30 // of adding these instructions.
32 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
33 "enable register allocation debugging information",
34 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
35 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
36 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
39 //----------------------------------------------------------------------------
40 // RegisterAllocation pass front end...
41 //----------------------------------------------------------------------------
43 class RegisterAllocator : public MethodPass {
44 TargetMachine &Target;
46 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
48 bool runOnMethod(Method *M) {
50 cerr << "\n******************** Method "<< M->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
54 &getAnalysis<cfg::LoopInfo>());
55 PRA.allocateRegisters();
57 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
62 Pass::AnalysisSet &Destroyed,
63 Pass::AnalysisSet &Provided) {
64 Requires.push_back(cfg::LoopInfo::ID);
65 Requires.push_back(MethodLiveVarInfo::ID);
70 MethodPass *getRegisterAllocator(TargetMachine &T) {
71 return new RegisterAllocator(T);
74 //----------------------------------------------------------------------------
75 // Constructor: Init local composite objects and create register classes.
76 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Method *M,
78 const TargetMachine& tm,
79 MethodLiveVarInfo *Lvi,
82 mcInfo(MachineCodeForMethod::get(M)),
83 LVI(Lvi), LRI(M, tm, RegClassList),
84 MRI( tm.getRegInfo() ),
85 NumOfRegClasses(MRI.getNumOfRegClasses()),
88 // create each RegisterClass and put in RegClassList
90 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
91 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
96 //----------------------------------------------------------------------------
97 // Destructor: Deletes register classes
98 //----------------------------------------------------------------------------
99 PhyRegAlloc::~PhyRegAlloc() {
100 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
101 delete RegClassList[rc];
104 //----------------------------------------------------------------------------
105 // This method initally creates interference graphs (one in each reg class)
106 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
107 //----------------------------------------------------------------------------
108 void PhyRegAlloc::createIGNodeListsAndIGs() {
109 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
112 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
115 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
117 for (; HMI != HMIEnd ; ++HMI ) {
119 LiveRange *L = HMI->second; // get the LiveRange
122 cerr << "\n*?!?Warning: Null liver range found for: "
123 << RAV(HMI->first) << "\n";
127 // if the Value * is not null, and LR
128 // is not yet written to the IGNodeList
129 if( !(L->getUserIGNode()) ) {
130 RegClass *const RC = // RegClass of first value in the LR
131 RegClassList[ L->getRegClass()->getID() ];
133 RC->addLRToIG(L); // add this LR to an IG
139 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
140 RegClassList[rc]->createInterferenceGraph();
143 cerr << "LRLists Created!\n";
149 //----------------------------------------------------------------------------
150 // This method will add all interferences at for a given instruction.
151 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
152 // class as that of live var. The live var passed to this function is the
153 // LVset AFTER the instruction
154 //----------------------------------------------------------------------------
155 void PhyRegAlloc::addInterference(const Value *Def,
156 const ValueSet *LVSet,
159 ValueSet::const_iterator LIt = LVSet->begin();
161 // get the live range of instruction
163 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
165 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
166 assert( IGNodeOfDef );
168 RegClass *const RCOfDef = LROfDef->getRegClass();
170 // for each live var in live variable set
172 for( ; LIt != LVSet->end(); ++LIt) {
175 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
177 // get the live range corresponding to live var
179 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
181 // LROfVar can be null if it is a const since a const
182 // doesn't have a dominating def - see Assumptions above
185 if(LROfDef == LROfVar) // do not set interf for same LR
188 // if 2 reg classes are the same set interference
190 if (RCOfDef == LROfVar->getRegClass()) {
191 RCOfDef->setInterference( LROfDef, LROfVar);
192 } else if (DEBUG_RA > 1) {
193 // we will not have LRs for values not explicitly allocated in the
194 // instruction stream (e.g., constants)
195 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
203 //----------------------------------------------------------------------------
204 // For a call instruction, this method sets the CallInterference flag in
205 // the LR of each variable live int the Live Variable Set live after the
206 // call instruction (except the return value of the call instruction - since
207 // the return value does not interfere with that call itself).
208 //----------------------------------------------------------------------------
210 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
211 const ValueSet *LVSetAft) {
213 // Now find the LR of the return value of the call
214 // We do this because, we look at the LV set *after* the instruction
215 // to determine, which LRs must be saved across calls. The return value
216 // of the call is live in this set - but it does not interfere with call
217 // (i.e., we can allocate a volatile register to the return value)
219 LiveRange *RetValLR = NULL;
220 const Value *RetVal = MRI.getCallInstRetVal( MInst );
223 RetValLR = LRI.getLiveRangeForValue( RetVal );
224 assert( RetValLR && "No LR for RetValue of call");
228 cerr << "\n For call inst: " << *MInst;
230 ValueSet::const_iterator LIt = LVSetAft->begin();
232 // for each live var in live variable set after machine inst
234 for( ; LIt != LVSetAft->end(); ++LIt) {
236 // get the live range corresponding to live var
238 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
240 if( LR && DEBUG_RA) {
241 cerr << "\n\tLR Aft Call: ";
246 // LR can be null if it is a const since a const
247 // doesn't have a dominating def - see Assumptions above
249 if( LR && (LR != RetValLR) ) {
250 LR->setCallInterference();
252 cerr << "\n ++Added call interf for LR: " ;
264 //----------------------------------------------------------------------------
265 // This method will walk thru code and create interferences in the IG of
266 // each RegClass. Also, this method calculates the spill cost of each
267 // Live Range (it is done in this method to save another pass over the code).
268 //----------------------------------------------------------------------------
269 void PhyRegAlloc::buildInterferenceGraphs()
272 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
274 unsigned BBLoopDepthCost;
275 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
277 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
279 // find the 10^(loop_depth) of this BB
281 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
283 // get the iterator for machine instructions
285 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
286 MachineCodeForBasicBlock::const_iterator
287 MInstIterator = MIVec.begin();
289 // iterate over all the machine instructions in BB
291 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
293 const MachineInstr *MInst = *MInstIterator;
295 // get the LV set after the instruction
297 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
299 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
302 // set the isCallInterference flag of each live range wich extends
303 // accross this call instruction. This information is used by graph
304 // coloring algo to avoid allocating volatile colors to live ranges
305 // that span across calls (since they have to be saved/restored)
307 setCallInterferences(MInst, &LVSetAI);
311 // iterate over all MI operands to find defs
313 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
316 // create a new LR iff this operand is a def
318 addInterference(*OpI, &LVSetAI, isCallInst);
321 // Calculate the spill cost of each live range
323 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
325 LR->addSpillCost(BBLoopDepthCost);
329 // if there are multiple defs in this instruction e.g. in SETX
331 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
332 addInterf4PseudoInstr(MInst);
335 // Also add interference for any implicit definitions in a machine
336 // instr (currently, only calls have this).
338 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
339 if( NumOfImpRefs > 0 ) {
340 for(unsigned z=0; z < NumOfImpRefs; z++)
341 if( MInst->implicitRefIsDefined(z) )
342 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
346 } // for all machine instructions in BB
348 } // for all BBs in method
351 // add interferences for method arguments. Since there are no explict
352 // defs in method for args, we have to add them manually
354 addInterferencesForArgs();
357 cerr << "Interference graphs calculted!\n";
363 //--------------------------------------------------------------------------
364 // Pseudo instructions will be exapnded to multiple instructions by the
365 // assembler. Consequently, all the opernds must get distinct registers.
366 // Therefore, we mark all operands of a pseudo instruction as they interfere
368 //--------------------------------------------------------------------------
369 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
371 bool setInterf = false;
373 // iterate over MI operands to find defs
375 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
377 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
379 if( !LROfOp1 && It1.isDef() )
380 assert( 0 && "No LR for Def in PSEUDO insruction");
382 MachineInstr::val_const_op_iterator It2 = It1;
385 for( ; !It2.done(); ++It2) {
387 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
391 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
392 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
394 if( RCOfOp1 == RCOfOp2 ){
395 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
401 } // for all other defs in machine instr
403 } // for all operands in an instruction
405 if( !setInterf && (MInst->getNumOperands() > 2) ) {
406 cerr << "\nInterf not set for any operand in pseudo instr:\n";
408 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
416 //----------------------------------------------------------------------------
417 // This method will add interferences for incoming arguments to a method.
418 //----------------------------------------------------------------------------
419 void PhyRegAlloc::addInterferencesForArgs() {
420 // get the InSet of root BB
421 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
423 // get the argument list
424 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
426 // get an iterator to arg list
427 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
430 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
431 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
432 // args and LVars at start
434 cerr << " - %% adding interference for argument "
435 << RAV((const Value *)*ArgIt) << "\n";
442 //----------------------------------------------------------------------------
443 // This method is called after register allocation is complete to set the
444 // allocated reisters in the machine code. This code will add register numbers
445 // to MachineOperands that contain a Value. Also it calls target specific
446 // methods to produce caller saving instructions. At the end, it adds all
447 // additional instructions produced by the register allocator to the
448 // instruction stream.
449 //----------------------------------------------------------------------------
450 void PhyRegAlloc::updateMachineCode()
453 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
455 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
457 // get the iterator for machine instructions
459 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
460 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
462 // iterate over all the machine instructions in BB
464 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
466 MachineInstr *MInst = *MInstIterator;
468 unsigned Opcode = MInst->getOpCode();
470 // do not process Phis
471 if (TM.getInstrInfo().isPhi(Opcode))
474 // Now insert speical instructions (if necessary) for call/return
477 if (TM.getInstrInfo().isCall(Opcode) ||
478 TM.getInstrInfo().isReturn(Opcode)) {
480 AddedInstrns *AI = AddedInstrMap[ MInst];
482 AI = new AddedInstrns();
483 AddedInstrMap[ MInst ] = AI;
486 // Tmp stack poistions are needed by some calls that have spilled args
487 // So reset it before we call each such method
489 mcInfo.popAllTempValues(TM);
491 if (TM.getInstrInfo().isCall(Opcode))
492 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
493 else if (TM.getInstrInfo().isReturn(Opcode))
494 MRI.colorRetValue(MInst, LRI, AI);
498 /* -- Using above code instead of this
500 // if this machine instr is call, insert caller saving code
502 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
503 MRI.insertCallerSavingCode(MInst, *BBI, *this );
508 // reset the stack offset for temporary variables since we may
509 // need that to spill
510 // mcInfo.popAllTempValues(TM);
511 // TODO ** : do later
513 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
516 // Now replace set the registers for operands in the machine instruction
518 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
520 MachineOperand& Op = MInst->getOperand(OpNum);
522 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
523 Op.getOperandType() == MachineOperand::MO_CCRegister) {
525 const Value *const Val = Op.getVRegValue();
527 // delete this condition checking later (must assert if Val is null)
530 cerr << "Warning: NULL Value found for operand\n";
533 assert( Val && "Value is NULL");
535 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
539 // nothing to worry if it's a const or a label
542 cerr << "*NO LR for operand : " << Op ;
543 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
544 cerr << " in inst:\t" << *MInst << "\n";
547 // if register is not allocated, mark register as invalid
548 if( Op.getAllocatedRegNum() == -1)
549 Op.setRegForValue( MRI.getInvalidRegNum());
555 unsigned RCID = (LR->getRegClass())->getID();
557 if( LR->hasColor() ) {
558 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
562 // LR did NOT receive a color (register). Now, insert spill code
563 // for spilled opeands in this machine instruction
565 //assert(0 && "LR must be spilled");
566 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
571 } // for each operand
574 // Now add instructions that the register allocator inserts before/after
575 // this machine instructions (done only for calls/rets/incoming args)
576 // We do this here, to ensure that spill for an instruction is inserted
577 // closest as possible to an instruction (see above insertCode4Spill...)
579 // If there are instructions to be added, *before* this machine
580 // instruction, add them now.
582 if( AddedInstrMap[ MInst ] ) {
583 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
585 if( ! IBef.empty() ) {
586 std::deque<MachineInstr *>::iterator AdIt;
588 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
591 cerr << "For inst " << *MInst;
592 cerr << " PREPENDed instr: " << **AdIt << "\n";
595 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
603 // If there are instructions to be added *after* this machine
604 // instruction, add them now
606 if(AddedInstrMap[MInst] &&
607 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
609 // if there are delay slots for this instruction, the instructions
610 // added after it must really go after the delayed instruction(s)
611 // So, we move the InstrAfter of the current instruction to the
612 // corresponding delayed instruction
615 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
616 move2DelayedInstr(MInst, *(MInstIterator+delay) );
618 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
624 // Here we can add the "instructions after" to the current
625 // instruction since there are no delay slots for this instruction
627 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
629 if( ! IAft.empty() ) {
631 std::deque<MachineInstr *>::iterator AdIt;
633 ++MInstIterator; // advance to the next instruction
635 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
638 cerr << "For inst " << *MInst;
639 cerr << " APPENDed instr: " << **AdIt << "\n";
642 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
646 // MInsterator already points to the next instr. Since the
647 // for loop also increments it, decrement it to point to the
648 // instruction added last
657 } // for each machine instruction
663 //----------------------------------------------------------------------------
664 // This method inserts spill code for AN operand whose LR was spilled.
665 // This method may be called several times for a single machine instruction
666 // if it contains many spilled operands. Each time it is called, it finds
667 // a register which is not live at that instruction and also which is not
668 // used by other spilled operands of the same instruction. Then it uses
669 // this register temporarily to accomodate the spilled value.
670 //----------------------------------------------------------------------------
671 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
673 const BasicBlock *BB,
674 const unsigned OpNum) {
676 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
677 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
678 "Arg of a call/ret must be handled elsewhere");
680 MachineOperand& Op = MInst->getOperand(OpNum);
681 bool isDef = MInst->operandIsDefined(OpNum);
682 unsigned RegType = MRI.getRegType( LR );
683 int SpillOff = LR->getSpillOffFromFP();
684 RegClass *RC = LR->getRegClass();
685 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
687 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
689 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
691 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
693 // get the added instructions for this instruciton
694 AddedInstrns *AI = AddedInstrMap[ MInst ];
696 AI = new AddedInstrns();
697 AddedInstrMap[ MInst ] = AI;
703 // for a USE, we have to load the value of LR from stack to a TmpReg
704 // and use the TmpReg as one operand of instruction
706 // actual loading instruction
707 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
710 AI->InstrnsBefore.push_back(MIBef);
712 AI->InstrnsBefore.push_back(AdIMid);
715 AI->InstrnsAfter.push_front(MIAft);
717 } else { // if this is a Def
718 // for a DEF, we have to store the value produced by this instruction
719 // on the stack position allocated for this LR
721 // actual storing instruction
722 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
725 AI->InstrnsBefore.push_back(MIBef);
727 AI->InstrnsAfter.push_front(AdIMid);
730 AI->InstrnsAfter.push_front(MIAft);
734 cerr << "\nFor Inst " << *MInst;
735 cerr << " - SPILLED LR: "; printSet(*LR);
736 cerr << "\n - Added Instructions:";
737 if (MIBef) cerr << *MIBef;
739 if (MIAft) cerr << *MIAft;
741 Op.setRegForValue(TmpRegU); // set the opearnd
746 //----------------------------------------------------------------------------
747 // We can use the following method to get a temporary register to be used
748 // BEFORE any given machine instruction. If there is a register available,
749 // this method will simply return that register and set MIBef = MIAft = NULL.
750 // Otherwise, it will return a register and MIAft and MIBef will contain
751 // two instructions used to free up this returned register.
752 // Returned register number is the UNIFIED register number
753 //----------------------------------------------------------------------------
755 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
757 const MachineInstr *MInst,
758 const ValueSet *LVSetBef,
760 MachineInstr *MIAft) {
762 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
766 // we found an unused register, so we can simply use it
767 MIBef = MIAft = NULL;
770 // we couldn't find an unused register. Generate code to free up a reg by
771 // saving it on stack and restoring after the instruction
773 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
775 RegU = getUniRegNotUsedByThisInst(RC, MInst);
776 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
777 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
783 //----------------------------------------------------------------------------
784 // This method is called to get a new unused register that can be used to
785 // accomodate a spilled value.
786 // This method may be called several times for a single machine instruction
787 // if it contains many spilled operands. Each time it is called, it finds
788 // a register which is not live at that instruction and also which is not
789 // used by other spilled operands of the same instruction.
790 // Return register number is relative to the register class. NOT
792 //----------------------------------------------------------------------------
793 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
794 const MachineInstr *MInst,
795 const ValueSet *LVSetBef) {
797 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
799 bool *IsColorUsedArr = RC->getIsColorUsedArr();
801 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
802 IsColorUsedArr[i] = false;
804 ValueSet::const_iterator LIt = LVSetBef->begin();
806 // for each live var in live variable set after machine inst
807 for( ; LIt != LVSetBef->end(); ++LIt) {
809 // get the live range corresponding to live var
810 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
812 // LR can be null if it is a const since a const
813 // doesn't have a dominating def - see Assumptions above
815 if( LRofLV->hasColor() )
816 IsColorUsedArr[ LRofLV->getColor() ] = true;
819 // It is possible that one operand of this MInst was already spilled
820 // and it received some register temporarily. If that's the case,
821 // it is recorded in machine operand. We must skip such registers.
823 setRelRegsUsedByThisInst(RC, MInst);
825 unsigned c; // find first unused color
826 for( c=0; c < NumAvailRegs; c++)
827 if( ! IsColorUsedArr[ c ] ) break;
830 return MRI.getUnifiedRegNum(RC->getID(), c);
838 //----------------------------------------------------------------------------
839 // Get any other register in a register class, other than what is used
840 // by operands of a machine instruction. Returns the unified reg number.
841 //----------------------------------------------------------------------------
842 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
843 const MachineInstr *MInst) {
845 bool *IsColorUsedArr = RC->getIsColorUsedArr();
846 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
849 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
850 IsColorUsedArr[i] = false;
852 setRelRegsUsedByThisInst(RC, MInst);
854 unsigned c; // find first unused color
855 for( c=0; c < RC->getNumOfAvailRegs(); c++)
856 if( ! IsColorUsedArr[ c ] ) break;
859 return MRI.getUnifiedRegNum(RC->getID(), c);
861 assert( 0 && "FATAL: No free register could be found in reg class!!");
866 //----------------------------------------------------------------------------
867 // This method modifies the IsColorUsedArr of the register class passed to it.
868 // It sets the bits corresponding to the registers used by this machine
869 // instructions. Both explicit and implicit operands are set.
870 //----------------------------------------------------------------------------
871 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
872 const MachineInstr *MInst ) {
874 bool *IsColorUsedArr = RC->getIsColorUsedArr();
876 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
878 const MachineOperand& Op = MInst->getOperand(OpNum);
880 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
881 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
883 const Value *const Val = Op.getVRegValue();
886 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
888 if( (Reg=Op.getAllocatedRegNum()) != -1) {
889 IsColorUsedArr[ Reg ] = true;
892 // it is possilbe that this operand still is not marked with
893 // a register but it has a LR and that received a color
895 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
897 if( LROfVal->hasColor() )
898 IsColorUsedArr[ LROfVal->getColor() ] = true;
901 } // if reg classes are the same
903 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
904 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
908 // If there are implicit references, mark them as well
910 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
912 LiveRange *const LRofImpRef =
913 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
915 if(LRofImpRef && LRofImpRef->hasColor())
916 IsColorUsedArr[LRofImpRef->getColor()] = true;
927 //----------------------------------------------------------------------------
928 // If there are delay slots for an instruction, the instructions
929 // added after it must really go after the delayed instruction(s).
930 // So, we move the InstrAfter of that instruction to the
931 // corresponding delayed instruction using the following method.
933 //----------------------------------------------------------------------------
934 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
935 const MachineInstr *DelayedMI) {
937 // "added after" instructions of the original instr
938 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
940 // "added instructions" of the delayed instr
941 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
943 if(! DelayAdI ) { // create a new "added after" if necessary
944 DelayAdI = new AddedInstrns();
945 AddedInstrMap[DelayedMI] = DelayAdI;
948 // "added after" instructions of the delayed instr
949 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
951 // go thru all the "added after instructions" of the original instruction
952 // and append them to the "addded after instructions" of the delayed
954 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
956 // empty the "added after instructions" of the original instruction
960 //----------------------------------------------------------------------------
961 // This method prints the code with registers after register allocation is
963 //----------------------------------------------------------------------------
964 void PhyRegAlloc::printMachineCode()
967 cerr << "\n;************** Method " << Meth->getName()
968 << " *****************\n";
970 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
972 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
974 cerr << "\n"; printLabel( *BBI); cerr << ": ";
976 // get the iterator for machine instructions
977 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
978 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
980 // iterate over all the machine instructions in BB
981 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
983 MachineInstr *const MInst = *MInstIterator;
987 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
990 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
992 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
994 MachineOperand& Op = MInst->getOperand(OpNum);
996 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
997 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
998 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1000 const Value *const Val = Op.getVRegValue () ;
1001 // ****this code is temporary till NULL Values are fixed
1003 cerr << "\t<*NULL*>";
1007 // if a label or a constant
1008 if(isa<BasicBlock>(Val)) {
1009 cerr << "\t"; printLabel( Op.getVRegValue () );
1011 // else it must be a register value
1012 const int RegNum = Op.getAllocatedRegNum();
1014 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1015 if (Val->hasName() )
1016 cerr << "(" << Val->getName() << ")";
1018 cerr << "(" << Val << ")";
1023 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1025 if( LROfVal->hasSpillOffset() )
1030 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1031 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1035 cerr << "\t" << Op; // use dump field
1040 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1041 if( NumOfImpRefs > 0) {
1042 cerr << "\tImplicit:";
1044 for(unsigned z=0; z < NumOfImpRefs; z++)
1045 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1048 } // for all machine instructions
1060 //----------------------------------------------------------------------------
1062 //----------------------------------------------------------------------------
1064 void PhyRegAlloc::colorCallRetArgs()
1067 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1068 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1070 for( ; It != CallRetInstList.end(); ++It ) {
1072 const MachineInstr *const CRMI = *It;
1073 unsigned OpCode = CRMI->getOpCode();
1075 // get the added instructions for this Call/Ret instruciton
1076 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1078 AI = new AddedInstrns();
1079 AddedInstrMap[ CRMI ] = AI;
1082 // Tmp stack poistions are needed by some calls that have spilled args
1083 // So reset it before we call each such method
1084 //mcInfo.popAllTempValues(TM);
1088 if (TM.getInstrInfo().isCall(OpCode))
1089 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1090 else if (TM.getInstrInfo().isReturn(OpCode))
1091 MRI.colorRetValue( CRMI, LRI, AI );
1093 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1099 //----------------------------------------------------------------------------
1101 //----------------------------------------------------------------------------
1102 void PhyRegAlloc::colorIncomingArgs()
1104 const BasicBlock *const FirstBB = Meth->front();
1105 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1106 assert(FirstMI && "No machine instruction in entry BB");
1108 AddedInstrns *AI = AddedInstrMap[FirstMI];
1110 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1112 MRI.colorMethodArgs(Meth, LRI, AI);
1116 //----------------------------------------------------------------------------
1117 // Used to generate a label for a basic block
1118 //----------------------------------------------------------------------------
1119 void PhyRegAlloc::printLabel(const Value *const Val) {
1121 cerr << Val->getName();
1123 cerr << "Label" << Val;
1127 //----------------------------------------------------------------------------
1128 // This method calls setSugColorUsable method of each live range. This
1129 // will determine whether the suggested color of LR is really usable.
1130 // A suggested color is not usable when the suggested color is volatile
1131 // AND when there are call interferences
1132 //----------------------------------------------------------------------------
1134 void PhyRegAlloc::markUnusableSugColors()
1136 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1138 // hash map iterator
1139 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1140 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1142 for(; HMI != HMIEnd ; ++HMI ) {
1144 LiveRange *L = HMI->second; // get the LiveRange
1146 if(L->hasSuggestedColor()) {
1147 int RCID = L->getRegClass()->getID();
1148 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1149 L->isCallInterference() )
1150 L->setSuggestedColorUsable( false );
1152 L->setSuggestedColorUsable( true );
1154 } // if L->hasSuggestedColor()
1156 } // for all LR's in hash map
1161 //----------------------------------------------------------------------------
1162 // The following method will set the stack offsets of the live ranges that
1163 // are decided to be spillled. This must be called just after coloring the
1164 // LRs using the graph coloring algo. For each live range that is spilled,
1165 // this method allocate a new spill position on the stack.
1166 //----------------------------------------------------------------------------
1168 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1169 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1171 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1172 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1174 for( ; HMI != HMIEnd ; ++HMI) {
1175 if (HMI->first && HMI->second) {
1176 LiveRange *L = HMI->second; // get the LiveRange
1177 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1178 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1180 } // for all LR's in hash map
1185 //----------------------------------------------------------------------------
1186 // The entry pont to Register Allocation
1187 //----------------------------------------------------------------------------
1189 void PhyRegAlloc::allocateRegisters()
1192 // make sure that we put all register classes into the RegClassList
1193 // before we call constructLiveRanges (now done in the constructor of
1194 // PhyRegAlloc class).
1196 LRI.constructLiveRanges(); // create LR info
1199 LRI.printLiveRanges();
1201 createIGNodeListsAndIGs(); // create IGNode list and IGs
1203 buildInterferenceGraphs(); // build IGs in all reg classes
1207 // print all LRs in all reg classes
1208 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1209 RegClassList[ rc ]->printIGNodeList();
1211 // print IGs in all register classes
1212 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1213 RegClassList[ rc ]->printIG();
1217 LRI.coalesceLRs(); // coalesce all live ranges
1221 // print all LRs in all reg classes
1222 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1223 RegClassList[ rc ]->printIGNodeList();
1225 // print IGs in all register classes
1226 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1227 RegClassList[ rc ]->printIG();
1231 // mark un-usable suggested color before graph coloring algorithm.
1232 // When this is done, the graph coloring algo will not reserve
1233 // suggested color unnecessarily - they can be used by another LR
1235 markUnusableSugColors();
1237 // color all register classes using the graph coloring algo
1238 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1239 RegClassList[ rc ]->colorAllRegs();
1241 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1242 // a poistion for such spilled LRs
1244 allocateStackSpace4SpilledLRs();
1246 mcInfo.popAllTempValues(TM); // TODO **Check
1248 // color incoming args - if the correct color was not received
1249 // insert code to copy to the correct register
1251 colorIncomingArgs();
1253 // Now update the machine code with register names and add any
1254 // additional code inserted by the register allocator to the instruction
1257 updateMachineCode();
1260 MachineCodeForMethod::get(Meth).dump();
1261 printMachineCode(); // only for DEBUGGING