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/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/MachineFrameInfo.h"
21 #include "llvm/Method.h"
27 // ***TODO: There are several places we add instructions. Validate the order
28 // of adding these instructions.
30 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
31 "enable register allocation debugging information",
32 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
33 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
34 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
37 //----------------------------------------------------------------------------
38 // RegisterAllocation pass front end...
39 //----------------------------------------------------------------------------
41 class RegisterAllocator : public MethodPass {
42 TargetMachine &Target;
44 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
46 bool runOnMethod(Method *M) {
48 cerr << "\n******************** Method "<< M->getName()
49 << " ********************\n";
51 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
52 &getAnalysis<cfg::LoopInfo>());
53 PRA.allocateRegisters();
55 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
59 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
60 Pass::AnalysisSet &Destroyed,
61 Pass::AnalysisSet &Provided) {
62 Requires.push_back(cfg::LoopInfo::ID);
63 Requires.push_back(MethodLiveVarInfo::ID);
68 MethodPass *getRegisterAllocator(TargetMachine &T) {
69 return new RegisterAllocator(T);
72 //----------------------------------------------------------------------------
73 // Constructor: Init local composite objects and create register classes.
74 //----------------------------------------------------------------------------
75 PhyRegAlloc::PhyRegAlloc(Method *M,
76 const TargetMachine& tm,
77 MethodLiveVarInfo *Lvi,
80 mcInfo(MachineCodeForMethod::get(M)),
81 LVI(Lvi), LRI(M, tm, RegClassList),
82 MRI( tm.getRegInfo() ),
83 NumOfRegClasses(MRI.getNumOfRegClasses()),
86 // create each RegisterClass and put in RegClassList
88 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
89 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
94 //----------------------------------------------------------------------------
95 // Destructor: Deletes register classes
96 //----------------------------------------------------------------------------
97 PhyRegAlloc::~PhyRegAlloc() {
98 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
99 delete RegClassList[rc];
102 //----------------------------------------------------------------------------
103 // This method initally creates interference graphs (one in each reg class)
104 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
105 //----------------------------------------------------------------------------
106 void PhyRegAlloc::createIGNodeListsAndIGs() {
107 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
110 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
113 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
115 for (; HMI != HMIEnd ; ++HMI ) {
117 LiveRange *L = HMI->second; // get the LiveRange
120 cerr << "\n*?!?Warning: Null liver range found for: ";
121 printValue(HMI->first); cerr << "\n";
125 // if the Value * is not null, and LR
126 // is not yet written to the IGNodeList
127 if( !(L->getUserIGNode()) ) {
128 RegClass *const RC = // RegClass of first value in the LR
129 RegClassList[ L->getRegClass()->getID() ];
131 RC->addLRToIG(L); // add this LR to an IG
137 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
138 RegClassList[rc]->createInterferenceGraph();
141 cerr << "LRLists Created!\n";
147 //----------------------------------------------------------------------------
148 // This method will add all interferences at for a given instruction.
149 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
150 // class as that of live var. The live var passed to this function is the
151 // LVset AFTER the instruction
152 //----------------------------------------------------------------------------
153 void PhyRegAlloc::addInterference(const Value *const Def,
154 const LiveVarSet *const LVSet,
155 const bool isCallInst) {
157 LiveVarSet::const_iterator LIt = LVSet->begin();
159 // get the live range of instruction
161 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
163 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
164 assert( IGNodeOfDef );
166 RegClass *const RCOfDef = LROfDef->getRegClass();
168 // for each live var in live variable set
170 for( ; LIt != LVSet->end(); ++LIt) {
173 cerr << "< Def="; printValue(Def);
174 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
177 // get the live range corresponding to live var
179 LiveRange *const 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 " ;
196 printValue(*LIt); cerr << "\n";
204 //----------------------------------------------------------------------------
205 // For a call instruction, this method sets the CallInterference flag in
206 // the LR of each variable live int the Live Variable Set live after the
207 // call instruction (except the return value of the call instruction - since
208 // the return value does not interfere with that call itself).
209 //----------------------------------------------------------------------------
211 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
212 const LiveVarSet *const LVSetAft ) {
214 // Now find the LR of the return value of the call
215 // We do this because, we look at the LV set *after* the instruction
216 // to determine, which LRs must be saved across calls. The return value
217 // of the call is live in this set - but it does not interfere with call
218 // (i.e., we can allocate a volatile register to the return value)
220 LiveRange *RetValLR = NULL;
221 const Value *RetVal = MRI.getCallInstRetVal( MInst );
224 RetValLR = LRI.getLiveRangeForValue( RetVal );
225 assert( RetValLR && "No LR for RetValue of call");
229 cerr << "\n For call inst: " << *MInst;
231 LiveVarSet::const_iterator LIt = LVSetAft->begin();
233 // for each live var in live variable set after machine inst
235 for( ; LIt != LVSetAft->end(); ++LIt) {
237 // get the live range corresponding to live var
239 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
241 if( LR && DEBUG_RA) {
242 cerr << "\n\tLR Aft Call: ";
247 // LR can be null if it is a const since a const
248 // doesn't have a dominating def - see Assumptions above
250 if( LR && (LR != RetValLR) ) {
251 LR->setCallInterference();
253 cerr << "\n ++Added call interf for LR: " ;
265 //----------------------------------------------------------------------------
266 // This method will walk thru code and create interferences in the IG of
267 // each RegClass. Also, this method calculates the spill cost of each
268 // Live Range (it is done in this method to save another pass over the code).
269 //----------------------------------------------------------------------------
270 void PhyRegAlloc::buildInterferenceGraphs()
273 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
275 unsigned BBLoopDepthCost;
276 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
278 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
280 // find the 10^(loop_depth) of this BB
282 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
284 // get the iterator for machine instructions
286 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
287 MachineCodeForBasicBlock::const_iterator
288 MInstIterator = MIVec.begin();
290 // iterate over all the machine instructions in BB
292 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
294 const MachineInstr * MInst = *MInstIterator;
296 // get the LV set after the instruction
298 const LiveVarSet *const LVSetAI =
299 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
301 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
304 // set the isCallInterference flag of each live range wich extends
305 // accross this call instruction. This information is used by graph
306 // coloring algo to avoid allocating volatile colors to live ranges
307 // that span across calls (since they have to be saved/restored)
309 setCallInterferences( MInst, LVSetAI);
313 // iterate over all MI operands to find defs
315 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
318 // create a new LR iff this operand is a def
320 addInterference(*OpI, LVSetAI, isCallInst );
323 // Calculate the spill cost of each live range
325 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
327 LR->addSpillCost(BBLoopDepthCost);
331 // if there are multiple defs in this instruction e.g. in SETX
333 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
334 addInterf4PseudoInstr(MInst);
337 // Also add interference for any implicit definitions in a machine
338 // instr (currently, only calls have this).
340 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
341 if( NumOfImpRefs > 0 ) {
342 for(unsigned z=0; z < NumOfImpRefs; z++)
343 if( MInst->implicitRefIsDefined(z) )
344 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
348 } // for all machine instructions in BB
350 } // for all BBs in method
353 // add interferences for method arguments. Since there are no explict
354 // defs in method for args, we have to add them manually
356 addInterferencesForArgs();
359 cerr << "Interference graphs calculted!\n";
365 //--------------------------------------------------------------------------
366 // Pseudo instructions will be exapnded to multiple instructions by the
367 // assembler. Consequently, all the opernds must get distinct registers.
368 // Therefore, we mark all operands of a pseudo instruction as they interfere
370 //--------------------------------------------------------------------------
371 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
373 bool setInterf = false;
375 // iterate over MI operands to find defs
377 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
379 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
381 if( !LROfOp1 && It1.isDef() )
382 assert( 0 && "No LR for Def in PSEUDO insruction");
384 MachineInstr::val_const_op_iterator It2 = It1;
387 for( ; !It2.done(); ++It2) {
389 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
393 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
394 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
396 if( RCOfOp1 == RCOfOp2 ){
397 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
403 } // for all other defs in machine instr
405 } // for all operands in an instruction
407 if( !setInterf && (MInst->getNumOperands() > 2) ) {
408 cerr << "\nInterf not set for any operand in pseudo instr:\n";
410 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
418 //----------------------------------------------------------------------------
419 // This method will add interferences for incoming arguments to a method.
420 //----------------------------------------------------------------------------
421 void PhyRegAlloc::addInterferencesForArgs()
423 // get the InSet of root BB
424 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
426 // get the argument list
427 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
429 // get an iterator to arg list
430 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
433 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
434 addInterference((Value*)*ArgIt, InSet, false); // add interferences between
435 // args and LVars at start
437 cerr << " - %% adding interference for argument ";
438 printValue((const Value *)*ArgIt); cerr << "\n";
446 //----------------------------------------------------------------------------
447 // This method is called after register allocation is complete to set the
448 // allocated reisters in the machine code. This code will add register numbers
449 // to MachineOperands that contain a Value. Also it calls target specific
450 // methods to produce caller saving instructions. At the end, it adds all
451 // additional instructions produced by the register allocator to the
452 // instruction stream.
453 //----------------------------------------------------------------------------
454 void PhyRegAlloc::updateMachineCode()
457 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
459 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
461 // get the iterator for machine instructions
463 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
464 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
466 // iterate over all the machine instructions in BB
468 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
470 MachineInstr *MInst = *MInstIterator;
472 unsigned Opcode = MInst->getOpCode();
474 // do not process Phis
475 if (TM.getInstrInfo().isPhi(Opcode))
478 // Now insert speical instructions (if necessary) for call/return
481 if (TM.getInstrInfo().isCall(Opcode) ||
482 TM.getInstrInfo().isReturn(Opcode)) {
484 AddedInstrns *AI = AddedInstrMap[ MInst];
486 AI = new AddedInstrns();
487 AddedInstrMap[ MInst ] = AI;
490 // Tmp stack poistions are needed by some calls that have spilled args
491 // So reset it before we call each such method
493 mcInfo.popAllTempValues(TM);
495 if (TM.getInstrInfo().isCall(Opcode))
496 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
497 else if (TM.getInstrInfo().isReturn(Opcode))
498 MRI.colorRetValue(MInst, LRI, AI);
502 /* -- Using above code instead of this
504 // if this machine instr is call, insert caller saving code
506 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
507 MRI.insertCallerSavingCode(MInst, *BBI, *this );
512 // reset the stack offset for temporary variables since we may
513 // need that to spill
514 // mcInfo.popAllTempValues(TM);
515 // TODO ** : do later
517 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
520 // Now replace set the registers for operands in the machine instruction
522 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
524 MachineOperand& Op = MInst->getOperand(OpNum);
526 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
527 Op.getOperandType() == MachineOperand::MO_CCRegister) {
529 const Value *const Val = Op.getVRegValue();
531 // delete this condition checking later (must assert if Val is null)
534 cerr << "Warning: NULL Value found for operand\n";
537 assert( Val && "Value is NULL");
539 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
543 // nothing to worry if it's a const or a label
546 cerr << "*NO LR for operand : " << Op ;
547 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
548 cerr << " in inst:\t" << *MInst << "\n";
551 // if register is not allocated, mark register as invalid
552 if( Op.getAllocatedRegNum() == -1)
553 Op.setRegForValue( MRI.getInvalidRegNum());
559 unsigned RCID = (LR->getRegClass())->getID();
561 if( LR->hasColor() ) {
562 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
566 // LR did NOT receive a color (register). Now, insert spill code
567 // for spilled opeands in this machine instruction
569 //assert(0 && "LR must be spilled");
570 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
575 } // for each operand
578 // Now add instructions that the register allocator inserts before/after
579 // this machine instructions (done only for calls/rets/incoming args)
580 // We do this here, to ensure that spill for an instruction is inserted
581 // closest as possible to an instruction (see above insertCode4Spill...)
583 // If there are instructions to be added, *before* this machine
584 // instruction, add them now.
586 if( AddedInstrMap[ MInst ] ) {
587 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
589 if( ! IBef.empty() ) {
590 std::deque<MachineInstr *>::iterator AdIt;
592 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
595 cerr << "For inst " << *MInst;
596 cerr << " PREPENDed instr: " << **AdIt << "\n";
599 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
607 // If there are instructions to be added *after* this machine
608 // instruction, add them now
610 if(AddedInstrMap[MInst] &&
611 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
613 // if there are delay slots for this instruction, the instructions
614 // added after it must really go after the delayed instruction(s)
615 // So, we move the InstrAfter of the current instruction to the
616 // corresponding delayed instruction
619 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
620 move2DelayedInstr(MInst, *(MInstIterator+delay) );
622 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
628 // Here we can add the "instructions after" to the current
629 // instruction since there are no delay slots for this instruction
631 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
633 if( ! IAft.empty() ) {
635 std::deque<MachineInstr *>::iterator AdIt;
637 ++MInstIterator; // advance to the next instruction
639 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
642 cerr << "For inst " << *MInst;
643 cerr << " APPENDed instr: " << **AdIt << "\n";
646 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
650 // MInsterator already points to the next instr. Since the
651 // for loop also increments it, decrement it to point to the
652 // instruction added last
661 } // for each machine instruction
667 //----------------------------------------------------------------------------
668 // This method inserts spill code for AN operand whose LR was spilled.
669 // This method may be called several times for a single machine instruction
670 // if it contains many spilled operands. Each time it is called, it finds
671 // a register which is not live at that instruction and also which is not
672 // used by other spilled operands of the same instruction. Then it uses
673 // this register temporarily to accomodate the spilled value.
674 //----------------------------------------------------------------------------
675 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
677 const BasicBlock *BB,
678 const unsigned OpNum) {
680 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
681 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
682 "Arg of a call/ret must be handled elsewhere");
684 MachineOperand& Op = MInst->getOperand(OpNum);
685 bool isDef = MInst->operandIsDefined(OpNum);
686 unsigned RegType = MRI.getRegType( LR );
687 int SpillOff = LR->getSpillOffFromFP();
688 RegClass *RC = LR->getRegClass();
689 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
691 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
693 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
695 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
697 // get the added instructions for this instruciton
698 AddedInstrns *AI = AddedInstrMap[ MInst ];
700 AI = new AddedInstrns();
701 AddedInstrMap[ MInst ] = AI;
707 // for a USE, we have to load the value of LR from stack to a TmpReg
708 // and use the TmpReg as one operand of instruction
710 // actual loading instruction
711 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
714 AI->InstrnsBefore.push_back(MIBef);
716 AI->InstrnsBefore.push_back(AdIMid);
719 AI->InstrnsAfter.push_front(MIAft);
723 else { // if this is a Def
725 // for a DEF, we have to store the value produced by this instruction
726 // on the stack position allocated for this LR
728 // actual storing instruction
729 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
732 AI->InstrnsBefore.push_back(MIBef);
734 AI->InstrnsAfter.push_front(AdIMid);
737 AI->InstrnsAfter.push_front(MIAft);
741 cerr << "\nFor Inst " << *MInst;
742 cerr << " - SPILLED LR: "; LR->printSet();
743 cerr << "\n - Added Instructions:";
744 if( MIBef ) cerr << *MIBef;
746 if( MIAft ) cerr << *MIAft;
748 Op.setRegForValue( TmpRegU ); // set the opearnd
758 //----------------------------------------------------------------------------
759 // We can use the following method to get a temporary register to be used
760 // BEFORE any given machine instruction. If there is a register available,
761 // this method will simply return that register and set MIBef = MIAft = NULL.
762 // Otherwise, it will return a register and MIAft and MIBef will contain
763 // two instructions used to free up this returned register.
764 // Returned register number is the UNIFIED register number
765 //----------------------------------------------------------------------------
767 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
769 const MachineInstr *MInst,
770 const LiveVarSet *LVSetBef,
772 MachineInstr *MIAft) {
774 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
778 // we found an unused register, so we can simply use it
779 MIBef = MIAft = NULL;
782 // we couldn't find an unused register. Generate code to free up a reg by
783 // saving it on stack and restoring after the instruction
785 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
787 RegU = getUniRegNotUsedByThisInst(RC, MInst);
788 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
789 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
795 //----------------------------------------------------------------------------
796 // This method is called to get a new unused register that can be used to
797 // accomodate a spilled value.
798 // This method may be called several times for a single machine instruction
799 // if it contains many spilled operands. Each time it is called, it finds
800 // a register which is not live at that instruction and also which is not
801 // used by other spilled operands of the same instruction.
802 // Return register number is relative to the register class. NOT
804 //----------------------------------------------------------------------------
805 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
806 const MachineInstr *MInst,
807 const LiveVarSet *LVSetBef) {
809 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
811 bool *IsColorUsedArr = RC->getIsColorUsedArr();
813 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
814 IsColorUsedArr[i] = false;
816 LiveVarSet::const_iterator LIt = LVSetBef->begin();
818 // for each live var in live variable set after machine inst
819 for( ; LIt != LVSetBef->end(); ++LIt) {
821 // get the live range corresponding to live var
822 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
824 // LR can be null if it is a const since a const
825 // doesn't have a dominating def - see Assumptions above
827 if( LRofLV->hasColor() )
828 IsColorUsedArr[ LRofLV->getColor() ] = true;
831 // It is possible that one operand of this MInst was already spilled
832 // and it received some register temporarily. If that's the case,
833 // it is recorded in machine operand. We must skip such registers.
835 setRelRegsUsedByThisInst(RC, MInst);
837 unsigned c; // find first unused color
838 for( c=0; c < NumAvailRegs; c++)
839 if( ! IsColorUsedArr[ c ] ) break;
842 return MRI.getUnifiedRegNum(RC->getID(), c);
850 //----------------------------------------------------------------------------
851 // Get any other register in a register class, other than what is used
852 // by operands of a machine instruction. Returns the unified reg number.
853 //----------------------------------------------------------------------------
854 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
855 const MachineInstr *MInst) {
857 bool *IsColorUsedArr = RC->getIsColorUsedArr();
858 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
861 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
862 IsColorUsedArr[i] = false;
864 setRelRegsUsedByThisInst(RC, MInst);
866 unsigned c; // find first unused color
867 for( c=0; c < RC->getNumOfAvailRegs(); c++)
868 if( ! IsColorUsedArr[ c ] ) break;
871 return MRI.getUnifiedRegNum(RC->getID(), c);
873 assert( 0 && "FATAL: No free register could be found in reg class!!");
878 //----------------------------------------------------------------------------
879 // This method modifies the IsColorUsedArr of the register class passed to it.
880 // It sets the bits corresponding to the registers used by this machine
881 // instructions. Both explicit and implicit operands are set.
882 //----------------------------------------------------------------------------
883 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
884 const MachineInstr *MInst ) {
886 bool *IsColorUsedArr = RC->getIsColorUsedArr();
888 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
890 const MachineOperand& Op = MInst->getOperand(OpNum);
892 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
893 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
895 const Value *const Val = Op.getVRegValue();
898 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
900 if( (Reg=Op.getAllocatedRegNum()) != -1) {
901 IsColorUsedArr[ Reg ] = true;
904 // it is possilbe that this operand still is not marked with
905 // a register but it has a LR and that received a color
907 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
909 if( LROfVal->hasColor() )
910 IsColorUsedArr[ LROfVal->getColor() ] = true;
913 } // if reg classes are the same
915 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
916 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
920 // If there are implicit references, mark them as well
922 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
924 LiveRange *const LRofImpRef =
925 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
927 if(LRofImpRef && LRofImpRef->hasColor())
928 IsColorUsedArr[LRofImpRef->getColor()] = true;
939 //----------------------------------------------------------------------------
940 // If there are delay slots for an instruction, the instructions
941 // added after it must really go after the delayed instruction(s).
942 // So, we move the InstrAfter of that instruction to the
943 // corresponding delayed instruction using the following method.
945 //----------------------------------------------------------------------------
946 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
947 const MachineInstr *DelayedMI) {
949 // "added after" instructions of the original instr
950 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
952 // "added instructions" of the delayed instr
953 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
955 if(! DelayAdI ) { // create a new "added after" if necessary
956 DelayAdI = new AddedInstrns();
957 AddedInstrMap[DelayedMI] = DelayAdI;
960 // "added after" instructions of the delayed instr
961 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
963 // go thru all the "added after instructions" of the original instruction
964 // and append them to the "addded after instructions" of the delayed
966 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
968 // empty the "added after instructions" of the original instruction
972 //----------------------------------------------------------------------------
973 // This method prints the code with registers after register allocation is
975 //----------------------------------------------------------------------------
976 void PhyRegAlloc::printMachineCode()
979 cerr << "\n;************** Method " << Meth->getName()
980 << " *****************\n";
982 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
984 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
986 cerr << "\n"; printLabel( *BBI); cerr << ": ";
988 // get the iterator for machine instructions
989 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
990 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
992 // iterate over all the machine instructions in BB
993 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
995 MachineInstr *const MInst = *MInstIterator;
999 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
1002 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
1004 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1006 MachineOperand& Op = MInst->getOperand(OpNum);
1008 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
1009 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
1010 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1012 const Value *const Val = Op.getVRegValue () ;
1013 // ****this code is temporary till NULL Values are fixed
1015 cerr << "\t<*NULL*>";
1019 // if a label or a constant
1020 if(isa<BasicBlock>(Val)) {
1021 cerr << "\t"; printLabel( Op.getVRegValue () );
1023 // else it must be a register value
1024 const int RegNum = Op.getAllocatedRegNum();
1026 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1027 if (Val->hasName() )
1028 cerr << "(" << Val->getName() << ")";
1030 cerr << "(" << Val << ")";
1035 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1037 if( LROfVal->hasSpillOffset() )
1042 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1043 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1047 cerr << "\t" << Op; // use dump field
1052 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1053 if( NumOfImpRefs > 0 ) {
1055 cerr << "\tImplicit:";
1057 for(unsigned z=0; z < NumOfImpRefs; z++) {
1058 printValue( MInst->getImplicitRef(z) );
1064 } // for all machine instructions
1076 //----------------------------------------------------------------------------
1078 //----------------------------------------------------------------------------
1080 void PhyRegAlloc::colorCallRetArgs()
1083 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1084 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1086 for( ; It != CallRetInstList.end(); ++It ) {
1088 const MachineInstr *const CRMI = *It;
1089 unsigned OpCode = CRMI->getOpCode();
1091 // get the added instructions for this Call/Ret instruciton
1092 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1094 AI = new AddedInstrns();
1095 AddedInstrMap[ CRMI ] = AI;
1098 // Tmp stack poistions are needed by some calls that have spilled args
1099 // So reset it before we call each such method
1100 //mcInfo.popAllTempValues(TM);
1104 if (TM.getInstrInfo().isCall(OpCode))
1105 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1106 else if (TM.getInstrInfo().isReturn(OpCode))
1107 MRI.colorRetValue( CRMI, LRI, AI );
1109 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1115 //----------------------------------------------------------------------------
1117 //----------------------------------------------------------------------------
1118 void PhyRegAlloc::colorIncomingArgs()
1120 const BasicBlock *const FirstBB = Meth->front();
1121 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1122 assert(FirstMI && "No machine instruction in entry BB");
1124 AddedInstrns *AI = AddedInstrMap[FirstMI];
1126 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1128 MRI.colorMethodArgs(Meth, LRI, AI);
1132 //----------------------------------------------------------------------------
1133 // Used to generate a label for a basic block
1134 //----------------------------------------------------------------------------
1135 void PhyRegAlloc::printLabel(const Value *const Val) {
1137 cerr << Val->getName();
1139 cerr << "Label" << Val;
1143 //----------------------------------------------------------------------------
1144 // This method calls setSugColorUsable method of each live range. This
1145 // will determine whether the suggested color of LR is really usable.
1146 // A suggested color is not usable when the suggested color is volatile
1147 // AND when there are call interferences
1148 //----------------------------------------------------------------------------
1150 void PhyRegAlloc::markUnusableSugColors()
1152 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1154 // hash map iterator
1155 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1156 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1158 for(; HMI != HMIEnd ; ++HMI ) {
1160 LiveRange *L = HMI->second; // get the LiveRange
1162 if(L->hasSuggestedColor()) {
1163 int RCID = L->getRegClass()->getID();
1164 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1165 L->isCallInterference() )
1166 L->setSuggestedColorUsable( false );
1168 L->setSuggestedColorUsable( true );
1170 } // if L->hasSuggestedColor()
1172 } // for all LR's in hash map
1177 //----------------------------------------------------------------------------
1178 // The following method will set the stack offsets of the live ranges that
1179 // are decided to be spillled. This must be called just after coloring the
1180 // LRs using the graph coloring algo. For each live range that is spilled,
1181 // this method allocate a new spill position on the stack.
1182 //----------------------------------------------------------------------------
1184 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1186 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1188 // hash map iterator
1189 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1190 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1192 for( ; HMI != HMIEnd ; ++HMI ) {
1193 if(HMI->first && HMI->second) {
1194 LiveRange *L = HMI->second; // get the LiveRange
1195 if( ! L->hasColor() )
1196 // NOTE: ** allocating the size of long Type **
1197 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1199 } // for all LR's in hash map
1204 //----------------------------------------------------------------------------
1205 // The entry pont to Register Allocation
1206 //----------------------------------------------------------------------------
1208 void PhyRegAlloc::allocateRegisters()
1211 // make sure that we put all register classes into the RegClassList
1212 // before we call constructLiveRanges (now done in the constructor of
1213 // PhyRegAlloc class).
1215 LRI.constructLiveRanges(); // create LR info
1218 LRI.printLiveRanges();
1220 createIGNodeListsAndIGs(); // create IGNode list and IGs
1222 buildInterferenceGraphs(); // build IGs in all reg classes
1226 // print all LRs in all reg classes
1227 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1228 RegClassList[ rc ]->printIGNodeList();
1230 // print IGs in all register classes
1231 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1232 RegClassList[ rc ]->printIG();
1236 LRI.coalesceLRs(); // coalesce all live ranges
1240 // print all LRs in all reg classes
1241 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1242 RegClassList[ rc ]->printIGNodeList();
1244 // print IGs in all register classes
1245 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1246 RegClassList[ rc ]->printIG();
1250 // mark un-usable suggested color before graph coloring algorithm.
1251 // When this is done, the graph coloring algo will not reserve
1252 // suggested color unnecessarily - they can be used by another LR
1254 markUnusableSugColors();
1256 // color all register classes using the graph coloring algo
1257 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1258 RegClassList[ rc ]->colorAllRegs();
1260 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1261 // a poistion for such spilled LRs
1263 allocateStackSpace4SpilledLRs();
1265 mcInfo.popAllTempValues(TM); // TODO **Check
1267 // color incoming args - if the correct color was not received
1268 // insert code to copy to the correct register
1270 colorIncomingArgs();
1272 // Now update the machine code with register names and add any
1273 // additional code inserted by the register allocator to the instruction
1276 updateMachineCode();
1279 MachineCodeForMethod::get(Meth).dump();
1280 printMachineCode(); // only for DEBUGGING