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"
28 // ***TODO: There are several places we add instructions. Validate the order
29 // of adding these instructions.
31 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
32 "enable register allocation debugging information",
33 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
34 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
35 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
38 //----------------------------------------------------------------------------
39 // RegisterAllocation pass front end...
40 //----------------------------------------------------------------------------
42 class RegisterAllocator : public MethodPass {
43 TargetMachine &Target;
45 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
47 bool runOnMethod(Method *M) {
49 cerr << "\n******************** Method "<< M->getName()
50 << " ********************\n";
52 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
53 &getAnalysis<cfg::LoopInfo>());
54 PRA.allocateRegisters();
56 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
60 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
61 Pass::AnalysisSet &Destroyed,
62 Pass::AnalysisSet &Provided) {
63 Requires.push_back(cfg::LoopInfo::ID);
64 Requires.push_back(MethodLiveVarInfo::ID);
69 MethodPass *getRegisterAllocator(TargetMachine &T) {
70 return new RegisterAllocator(T);
73 //----------------------------------------------------------------------------
74 // Constructor: Init local composite objects and create register classes.
75 //----------------------------------------------------------------------------
76 PhyRegAlloc::PhyRegAlloc(Method *M,
77 const TargetMachine& tm,
78 MethodLiveVarInfo *Lvi,
81 mcInfo(MachineCodeForMethod::get(M)),
82 LVI(Lvi), LRI(M, tm, RegClassList),
83 MRI( tm.getRegInfo() ),
84 NumOfRegClasses(MRI.getNumOfRegClasses()),
87 // create each RegisterClass and put in RegClassList
89 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
90 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
95 //----------------------------------------------------------------------------
96 // Destructor: Deletes register classes
97 //----------------------------------------------------------------------------
98 PhyRegAlloc::~PhyRegAlloc() {
99 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
100 delete RegClassList[rc];
103 //----------------------------------------------------------------------------
104 // This method initally creates interference graphs (one in each reg class)
105 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
106 //----------------------------------------------------------------------------
107 void PhyRegAlloc::createIGNodeListsAndIGs() {
108 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
111 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
114 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
116 for (; HMI != HMIEnd ; ++HMI ) {
118 LiveRange *L = HMI->second; // get the LiveRange
121 cerr << "\n*?!?Warning: Null liver range found for: "
122 << RAV(HMI->first) << "\n";
126 // if the Value * is not null, and LR
127 // is not yet written to the IGNodeList
128 if( !(L->getUserIGNode()) ) {
129 RegClass *const RC = // RegClass of first value in the LR
130 RegClassList[ L->getRegClass()->getID() ];
132 RC->addLRToIG(L); // add this LR to an IG
138 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
139 RegClassList[rc]->createInterferenceGraph();
142 cerr << "LRLists Created!\n";
148 //----------------------------------------------------------------------------
149 // This method will add all interferences at for a given instruction.
150 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
151 // class as that of live var. The live var passed to this function is the
152 // LVset AFTER the instruction
153 //----------------------------------------------------------------------------
154 void PhyRegAlloc::addInterference(const Value *Def,
155 const ValueSet *LVSet,
158 ValueSet::const_iterator LIt = LVSet->begin();
160 // get the live range of instruction
162 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
164 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
165 assert( IGNodeOfDef );
167 RegClass *const RCOfDef = LROfDef->getRegClass();
169 // for each live var in live variable set
171 for( ; LIt != LVSet->end(); ++LIt) {
174 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
176 // get the live range corresponding to live var
178 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
180 // LROfVar can be null if it is a const since a const
181 // doesn't have a dominating def - see Assumptions above
184 if(LROfDef == LROfVar) // do not set interf for same LR
187 // if 2 reg classes are the same set interference
189 if (RCOfDef == LROfVar->getRegClass()) {
190 RCOfDef->setInterference( LROfDef, LROfVar);
191 } else if (DEBUG_RA > 1) {
192 // we will not have LRs for values not explicitly allocated in the
193 // instruction stream (e.g., constants)
194 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
202 //----------------------------------------------------------------------------
203 // For a call instruction, this method sets the CallInterference flag in
204 // the LR of each variable live int the Live Variable Set live after the
205 // call instruction (except the return value of the call instruction - since
206 // the return value does not interfere with that call itself).
207 //----------------------------------------------------------------------------
209 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
210 const ValueSet *LVSetAft) {
212 // Now find the LR of the return value of the call
213 // We do this because, we look at the LV set *after* the instruction
214 // to determine, which LRs must be saved across calls. The return value
215 // of the call is live in this set - but it does not interfere with call
216 // (i.e., we can allocate a volatile register to the return value)
218 LiveRange *RetValLR = NULL;
219 const Value *RetVal = MRI.getCallInstRetVal( MInst );
222 RetValLR = LRI.getLiveRangeForValue( RetVal );
223 assert( RetValLR && "No LR for RetValue of call");
227 cerr << "\n For call inst: " << *MInst;
229 ValueSet::const_iterator LIt = LVSetAft->begin();
231 // for each live var in live variable set after machine inst
233 for( ; LIt != LVSetAft->end(); ++LIt) {
235 // get the live range corresponding to live var
237 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
239 if( LR && DEBUG_RA) {
240 cerr << "\n\tLR Aft Call: ";
245 // LR can be null if it is a const since a const
246 // doesn't have a dominating def - see Assumptions above
248 if( LR && (LR != RetValLR) ) {
249 LR->setCallInterference();
251 cerr << "\n ++Added call interf for LR: " ;
263 //----------------------------------------------------------------------------
264 // This method will walk thru code and create interferences in the IG of
265 // each RegClass. Also, this method calculates the spill cost of each
266 // Live Range (it is done in this method to save another pass over the code).
267 //----------------------------------------------------------------------------
268 void PhyRegAlloc::buildInterferenceGraphs()
271 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
273 unsigned BBLoopDepthCost;
274 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
276 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
278 // find the 10^(loop_depth) of this BB
280 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
282 // get the iterator for machine instructions
284 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
285 MachineCodeForBasicBlock::const_iterator
286 MInstIterator = MIVec.begin();
288 // iterate over all the machine instructions in BB
290 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
292 const MachineInstr * MInst = *MInstIterator;
294 // get the LV set after the instruction
296 const ValueSet *LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
298 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
301 // set the isCallInterference flag of each live range wich extends
302 // accross this call instruction. This information is used by graph
303 // coloring algo to avoid allocating volatile colors to live ranges
304 // that span across calls (since they have to be saved/restored)
306 setCallInterferences( MInst, LVSetAI);
310 // iterate over all MI operands to find defs
312 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
315 // create a new LR iff this operand is a def
317 addInterference(*OpI, LVSetAI, isCallInst );
320 // Calculate the spill cost of each live range
322 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
324 LR->addSpillCost(BBLoopDepthCost);
328 // if there are multiple defs in this instruction e.g. in SETX
330 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
331 addInterf4PseudoInstr(MInst);
334 // Also add interference for any implicit definitions in a machine
335 // instr (currently, only calls have this).
337 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
338 if( NumOfImpRefs > 0 ) {
339 for(unsigned z=0; z < NumOfImpRefs; z++)
340 if( MInst->implicitRefIsDefined(z) )
341 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
345 } // for all machine instructions in BB
347 } // for all BBs in method
350 // add interferences for method arguments. Since there are no explict
351 // defs in method for args, we have to add them manually
353 addInterferencesForArgs();
356 cerr << "Interference graphs calculted!\n";
362 //--------------------------------------------------------------------------
363 // Pseudo instructions will be exapnded to multiple instructions by the
364 // assembler. Consequently, all the opernds must get distinct registers.
365 // Therefore, we mark all operands of a pseudo instruction as they interfere
367 //--------------------------------------------------------------------------
368 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
370 bool setInterf = false;
372 // iterate over MI operands to find defs
374 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
376 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
378 if( !LROfOp1 && It1.isDef() )
379 assert( 0 && "No LR for Def in PSEUDO insruction");
381 MachineInstr::val_const_op_iterator It2 = It1;
384 for( ; !It2.done(); ++It2) {
386 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
390 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
391 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
393 if( RCOfOp1 == RCOfOp2 ){
394 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
400 } // for all other defs in machine instr
402 } // for all operands in an instruction
404 if( !setInterf && (MInst->getNumOperands() > 2) ) {
405 cerr << "\nInterf not set for any operand in pseudo instr:\n";
407 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
415 //----------------------------------------------------------------------------
416 // This method will add interferences for incoming arguments to a method.
417 //----------------------------------------------------------------------------
418 void PhyRegAlloc::addInterferencesForArgs() {
419 // get the InSet of root BB
420 const ValueSet *InSet = LVI->getInSetOfBB(Meth->front());
422 // get the argument list
423 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
425 // get an iterator to arg list
426 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
429 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
430 addInterference((Value*)*ArgIt, InSet, false); // add interferences between
431 // args and LVars at start
433 cerr << " - %% adding interference for argument "
434 << RAV((const Value *)*ArgIt) << "\n";
441 //----------------------------------------------------------------------------
442 // This method is called after register allocation is complete to set the
443 // allocated reisters in the machine code. This code will add register numbers
444 // to MachineOperands that contain a Value. Also it calls target specific
445 // methods to produce caller saving instructions. At the end, it adds all
446 // additional instructions produced by the register allocator to the
447 // instruction stream.
448 //----------------------------------------------------------------------------
449 void PhyRegAlloc::updateMachineCode()
452 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
454 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
456 // get the iterator for machine instructions
458 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
459 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
461 // iterate over all the machine instructions in BB
463 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
465 MachineInstr *MInst = *MInstIterator;
467 unsigned Opcode = MInst->getOpCode();
469 // do not process Phis
470 if (TM.getInstrInfo().isPhi(Opcode))
473 // Now insert speical instructions (if necessary) for call/return
476 if (TM.getInstrInfo().isCall(Opcode) ||
477 TM.getInstrInfo().isReturn(Opcode)) {
479 AddedInstrns *AI = AddedInstrMap[ MInst];
481 AI = new AddedInstrns();
482 AddedInstrMap[ MInst ] = AI;
485 // Tmp stack poistions are needed by some calls that have spilled args
486 // So reset it before we call each such method
488 mcInfo.popAllTempValues(TM);
490 if (TM.getInstrInfo().isCall(Opcode))
491 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
492 else if (TM.getInstrInfo().isReturn(Opcode))
493 MRI.colorRetValue(MInst, LRI, AI);
497 /* -- Using above code instead of this
499 // if this machine instr is call, insert caller saving code
501 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
502 MRI.insertCallerSavingCode(MInst, *BBI, *this );
507 // reset the stack offset for temporary variables since we may
508 // need that to spill
509 // mcInfo.popAllTempValues(TM);
510 // TODO ** : do later
512 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
515 // Now replace set the registers for operands in the machine instruction
517 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
519 MachineOperand& Op = MInst->getOperand(OpNum);
521 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
522 Op.getOperandType() == MachineOperand::MO_CCRegister) {
524 const Value *const Val = Op.getVRegValue();
526 // delete this condition checking later (must assert if Val is null)
529 cerr << "Warning: NULL Value found for operand\n";
532 assert( Val && "Value is NULL");
534 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
538 // nothing to worry if it's a const or a label
541 cerr << "*NO LR for operand : " << Op ;
542 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
543 cerr << " in inst:\t" << *MInst << "\n";
546 // if register is not allocated, mark register as invalid
547 if( Op.getAllocatedRegNum() == -1)
548 Op.setRegForValue( MRI.getInvalidRegNum());
554 unsigned RCID = (LR->getRegClass())->getID();
556 if( LR->hasColor() ) {
557 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
561 // LR did NOT receive a color (register). Now, insert spill code
562 // for spilled opeands in this machine instruction
564 //assert(0 && "LR must be spilled");
565 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
570 } // for each operand
573 // Now add instructions that the register allocator inserts before/after
574 // this machine instructions (done only for calls/rets/incoming args)
575 // We do this here, to ensure that spill for an instruction is inserted
576 // closest as possible to an instruction (see above insertCode4Spill...)
578 // If there are instructions to be added, *before* this machine
579 // instruction, add them now.
581 if( AddedInstrMap[ MInst ] ) {
582 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
584 if( ! IBef.empty() ) {
585 std::deque<MachineInstr *>::iterator AdIt;
587 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
590 cerr << "For inst " << *MInst;
591 cerr << " PREPENDed instr: " << **AdIt << "\n";
594 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
602 // If there are instructions to be added *after* this machine
603 // instruction, add them now
605 if(AddedInstrMap[MInst] &&
606 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
608 // if there are delay slots for this instruction, the instructions
609 // added after it must really go after the delayed instruction(s)
610 // So, we move the InstrAfter of the current instruction to the
611 // corresponding delayed instruction
614 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
615 move2DelayedInstr(MInst, *(MInstIterator+delay) );
617 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
623 // Here we can add the "instructions after" to the current
624 // instruction since there are no delay slots for this instruction
626 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
628 if( ! IAft.empty() ) {
630 std::deque<MachineInstr *>::iterator AdIt;
632 ++MInstIterator; // advance to the next instruction
634 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
637 cerr << "For inst " << *MInst;
638 cerr << " APPENDed instr: " << **AdIt << "\n";
641 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
645 // MInsterator already points to the next instr. Since the
646 // for loop also increments it, decrement it to point to the
647 // instruction added last
656 } // for each machine instruction
662 //----------------------------------------------------------------------------
663 // This method inserts spill code for AN operand whose LR was spilled.
664 // This method may be called several times for a single machine instruction
665 // if it contains many spilled operands. Each time it is called, it finds
666 // a register which is not live at that instruction and also which is not
667 // used by other spilled operands of the same instruction. Then it uses
668 // this register temporarily to accomodate the spilled value.
669 //----------------------------------------------------------------------------
670 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
672 const BasicBlock *BB,
673 const unsigned OpNum) {
675 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
676 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
677 "Arg of a call/ret must be handled elsewhere");
679 MachineOperand& Op = MInst->getOperand(OpNum);
680 bool isDef = MInst->operandIsDefined(OpNum);
681 unsigned RegType = MRI.getRegType( LR );
682 int SpillOff = LR->getSpillOffFromFP();
683 RegClass *RC = LR->getRegClass();
684 const ValueSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
686 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
688 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
690 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
692 // get the added instructions for this instruciton
693 AddedInstrns *AI = AddedInstrMap[ MInst ];
695 AI = new AddedInstrns();
696 AddedInstrMap[ MInst ] = AI;
702 // for a USE, we have to load the value of LR from stack to a TmpReg
703 // and use the TmpReg as one operand of instruction
705 // actual loading instruction
706 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
709 AI->InstrnsBefore.push_back(MIBef);
711 AI->InstrnsBefore.push_back(AdIMid);
714 AI->InstrnsAfter.push_front(MIAft);
716 } else { // if this is a Def
717 // for a DEF, we have to store the value produced by this instruction
718 // on the stack position allocated for this LR
720 // actual storing instruction
721 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
724 AI->InstrnsBefore.push_back(MIBef);
726 AI->InstrnsAfter.push_front(AdIMid);
729 AI->InstrnsAfter.push_front(MIAft);
733 cerr << "\nFor Inst " << *MInst;
734 cerr << " - SPILLED LR: "; printSet(*LR);
735 cerr << "\n - Added Instructions:";
736 if (MIBef) cerr << *MIBef;
738 if (MIAft) cerr << *MIAft;
740 Op.setRegForValue(TmpRegU); // set the opearnd
745 //----------------------------------------------------------------------------
746 // We can use the following method to get a temporary register to be used
747 // BEFORE any given machine instruction. If there is a register available,
748 // this method will simply return that register and set MIBef = MIAft = NULL.
749 // Otherwise, it will return a register and MIAft and MIBef will contain
750 // two instructions used to free up this returned register.
751 // Returned register number is the UNIFIED register number
752 //----------------------------------------------------------------------------
754 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
756 const MachineInstr *MInst,
757 const ValueSet *LVSetBef,
759 MachineInstr *MIAft) {
761 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
765 // we found an unused register, so we can simply use it
766 MIBef = MIAft = NULL;
769 // we couldn't find an unused register. Generate code to free up a reg by
770 // saving it on stack and restoring after the instruction
772 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
774 RegU = getUniRegNotUsedByThisInst(RC, MInst);
775 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
776 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
782 //----------------------------------------------------------------------------
783 // This method is called to get a new unused register that can be used to
784 // accomodate a spilled value.
785 // This method may be called several times for a single machine instruction
786 // if it contains many spilled operands. Each time it is called, it finds
787 // a register which is not live at that instruction and also which is not
788 // used by other spilled operands of the same instruction.
789 // Return register number is relative to the register class. NOT
791 //----------------------------------------------------------------------------
792 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
793 const MachineInstr *MInst,
794 const ValueSet *LVSetBef) {
796 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
798 bool *IsColorUsedArr = RC->getIsColorUsedArr();
800 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
801 IsColorUsedArr[i] = false;
803 ValueSet::const_iterator LIt = LVSetBef->begin();
805 // for each live var in live variable set after machine inst
806 for( ; LIt != LVSetBef->end(); ++LIt) {
808 // get the live range corresponding to live var
809 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
811 // LR can be null if it is a const since a const
812 // doesn't have a dominating def - see Assumptions above
814 if( LRofLV->hasColor() )
815 IsColorUsedArr[ LRofLV->getColor() ] = true;
818 // It is possible that one operand of this MInst was already spilled
819 // and it received some register temporarily. If that's the case,
820 // it is recorded in machine operand. We must skip such registers.
822 setRelRegsUsedByThisInst(RC, MInst);
824 unsigned c; // find first unused color
825 for( c=0; c < NumAvailRegs; c++)
826 if( ! IsColorUsedArr[ c ] ) break;
829 return MRI.getUnifiedRegNum(RC->getID(), c);
837 //----------------------------------------------------------------------------
838 // Get any other register in a register class, other than what is used
839 // by operands of a machine instruction. Returns the unified reg number.
840 //----------------------------------------------------------------------------
841 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
842 const MachineInstr *MInst) {
844 bool *IsColorUsedArr = RC->getIsColorUsedArr();
845 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
848 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
849 IsColorUsedArr[i] = false;
851 setRelRegsUsedByThisInst(RC, MInst);
853 unsigned c; // find first unused color
854 for( c=0; c < RC->getNumOfAvailRegs(); c++)
855 if( ! IsColorUsedArr[ c ] ) break;
858 return MRI.getUnifiedRegNum(RC->getID(), c);
860 assert( 0 && "FATAL: No free register could be found in reg class!!");
865 //----------------------------------------------------------------------------
866 // This method modifies the IsColorUsedArr of the register class passed to it.
867 // It sets the bits corresponding to the registers used by this machine
868 // instructions. Both explicit and implicit operands are set.
869 //----------------------------------------------------------------------------
870 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
871 const MachineInstr *MInst ) {
873 bool *IsColorUsedArr = RC->getIsColorUsedArr();
875 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
877 const MachineOperand& Op = MInst->getOperand(OpNum);
879 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
880 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
882 const Value *const Val = Op.getVRegValue();
885 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
887 if( (Reg=Op.getAllocatedRegNum()) != -1) {
888 IsColorUsedArr[ Reg ] = true;
891 // it is possilbe that this operand still is not marked with
892 // a register but it has a LR and that received a color
894 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
896 if( LROfVal->hasColor() )
897 IsColorUsedArr[ LROfVal->getColor() ] = true;
900 } // if reg classes are the same
902 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
903 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
907 // If there are implicit references, mark them as well
909 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
911 LiveRange *const LRofImpRef =
912 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
914 if(LRofImpRef && LRofImpRef->hasColor())
915 IsColorUsedArr[LRofImpRef->getColor()] = true;
926 //----------------------------------------------------------------------------
927 // If there are delay slots for an instruction, the instructions
928 // added after it must really go after the delayed instruction(s).
929 // So, we move the InstrAfter of that instruction to the
930 // corresponding delayed instruction using the following method.
932 //----------------------------------------------------------------------------
933 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
934 const MachineInstr *DelayedMI) {
936 // "added after" instructions of the original instr
937 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
939 // "added instructions" of the delayed instr
940 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
942 if(! DelayAdI ) { // create a new "added after" if necessary
943 DelayAdI = new AddedInstrns();
944 AddedInstrMap[DelayedMI] = DelayAdI;
947 // "added after" instructions of the delayed instr
948 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
950 // go thru all the "added after instructions" of the original instruction
951 // and append them to the "addded after instructions" of the delayed
953 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
955 // empty the "added after instructions" of the original instruction
959 //----------------------------------------------------------------------------
960 // This method prints the code with registers after register allocation is
962 //----------------------------------------------------------------------------
963 void PhyRegAlloc::printMachineCode()
966 cerr << "\n;************** Method " << Meth->getName()
967 << " *****************\n";
969 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
971 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
973 cerr << "\n"; printLabel( *BBI); cerr << ": ";
975 // get the iterator for machine instructions
976 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
977 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
979 // iterate over all the machine instructions in BB
980 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
982 MachineInstr *const MInst = *MInstIterator;
986 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
989 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
991 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
993 MachineOperand& Op = MInst->getOperand(OpNum);
995 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
996 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
997 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
999 const Value *const Val = Op.getVRegValue () ;
1000 // ****this code is temporary till NULL Values are fixed
1002 cerr << "\t<*NULL*>";
1006 // if a label or a constant
1007 if(isa<BasicBlock>(Val)) {
1008 cerr << "\t"; printLabel( Op.getVRegValue () );
1010 // else it must be a register value
1011 const int RegNum = Op.getAllocatedRegNum();
1013 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1014 if (Val->hasName() )
1015 cerr << "(" << Val->getName() << ")";
1017 cerr << "(" << Val << ")";
1022 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1024 if( LROfVal->hasSpillOffset() )
1029 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1030 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1034 cerr << "\t" << Op; // use dump field
1039 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1040 if( NumOfImpRefs > 0) {
1041 cerr << "\tImplicit:";
1043 for(unsigned z=0; z < NumOfImpRefs; z++)
1044 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1047 } // for all machine instructions
1059 //----------------------------------------------------------------------------
1061 //----------------------------------------------------------------------------
1063 void PhyRegAlloc::colorCallRetArgs()
1066 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1067 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1069 for( ; It != CallRetInstList.end(); ++It ) {
1071 const MachineInstr *const CRMI = *It;
1072 unsigned OpCode = CRMI->getOpCode();
1074 // get the added instructions for this Call/Ret instruciton
1075 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1077 AI = new AddedInstrns();
1078 AddedInstrMap[ CRMI ] = AI;
1081 // Tmp stack poistions are needed by some calls that have spilled args
1082 // So reset it before we call each such method
1083 //mcInfo.popAllTempValues(TM);
1087 if (TM.getInstrInfo().isCall(OpCode))
1088 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1089 else if (TM.getInstrInfo().isReturn(OpCode))
1090 MRI.colorRetValue( CRMI, LRI, AI );
1092 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1098 //----------------------------------------------------------------------------
1100 //----------------------------------------------------------------------------
1101 void PhyRegAlloc::colorIncomingArgs()
1103 const BasicBlock *const FirstBB = Meth->front();
1104 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1105 assert(FirstMI && "No machine instruction in entry BB");
1107 AddedInstrns *AI = AddedInstrMap[FirstMI];
1109 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1111 MRI.colorMethodArgs(Meth, LRI, AI);
1115 //----------------------------------------------------------------------------
1116 // Used to generate a label for a basic block
1117 //----------------------------------------------------------------------------
1118 void PhyRegAlloc::printLabel(const Value *const Val) {
1120 cerr << Val->getName();
1122 cerr << "Label" << Val;
1126 //----------------------------------------------------------------------------
1127 // This method calls setSugColorUsable method of each live range. This
1128 // will determine whether the suggested color of LR is really usable.
1129 // A suggested color is not usable when the suggested color is volatile
1130 // AND when there are call interferences
1131 //----------------------------------------------------------------------------
1133 void PhyRegAlloc::markUnusableSugColors()
1135 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1137 // hash map iterator
1138 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1139 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1141 for(; HMI != HMIEnd ; ++HMI ) {
1143 LiveRange *L = HMI->second; // get the LiveRange
1145 if(L->hasSuggestedColor()) {
1146 int RCID = L->getRegClass()->getID();
1147 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1148 L->isCallInterference() )
1149 L->setSuggestedColorUsable( false );
1151 L->setSuggestedColorUsable( true );
1153 } // if L->hasSuggestedColor()
1155 } // for all LR's in hash map
1160 //----------------------------------------------------------------------------
1161 // The following method will set the stack offsets of the live ranges that
1162 // are decided to be spillled. This must be called just after coloring the
1163 // LRs using the graph coloring algo. For each live range that is spilled,
1164 // this method allocate a new spill position on the stack.
1165 //----------------------------------------------------------------------------
1167 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1169 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1171 // hash map iterator
1172 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1173 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1175 for( ; HMI != HMIEnd ; ++HMI ) {
1176 if(HMI->first && HMI->second) {
1177 LiveRange *L = HMI->second; // get the LiveRange
1178 if( ! L->hasColor() )
1179 // NOTE: ** allocating the size of long Type **
1180 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1182 } // for all LR's in hash map
1187 //----------------------------------------------------------------------------
1188 // The entry pont to Register Allocation
1189 //----------------------------------------------------------------------------
1191 void PhyRegAlloc::allocateRegisters()
1194 // make sure that we put all register classes into the RegClassList
1195 // before we call constructLiveRanges (now done in the constructor of
1196 // PhyRegAlloc class).
1198 LRI.constructLiveRanges(); // create LR info
1201 LRI.printLiveRanges();
1203 createIGNodeListsAndIGs(); // create IGNode list and IGs
1205 buildInterferenceGraphs(); // build IGs in all reg classes
1209 // print all LRs in all reg classes
1210 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1211 RegClassList[ rc ]->printIGNodeList();
1213 // print IGs in all register classes
1214 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1215 RegClassList[ rc ]->printIG();
1219 LRI.coalesceLRs(); // coalesce all live ranges
1223 // print all LRs in all reg classes
1224 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1225 RegClassList[ rc ]->printIGNodeList();
1227 // print IGs in all register classes
1228 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1229 RegClassList[ rc ]->printIG();
1233 // mark un-usable suggested color before graph coloring algorithm.
1234 // When this is done, the graph coloring algo will not reserve
1235 // suggested color unnecessarily - they can be used by another LR
1237 markUnusableSugColors();
1239 // color all register classes using the graph coloring algo
1240 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1241 RegClassList[ rc ]->colorAllRegs();
1243 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1244 // a poistion for such spilled LRs
1246 allocateStackSpace4SpilledLRs();
1248 mcInfo.popAllTempValues(TM); // TODO **Check
1250 // color incoming args - if the correct color was not received
1251 // insert code to copy to the correct register
1253 colorIncomingArgs();
1255 // Now update the machine code with register names and add any
1256 // additional code inserted by the register allocator to the instruction
1259 updateMachineCode();
1262 MachineCodeForMethod::get(Meth).dump();
1263 printMachineCode(); // only for DEBUGGING