2 //***************************************************************************
7 // Register allocation for LLVM.
10 // 9/10/01 - Ruchira Sasanka - created.
11 //**************************************************************************/
13 #include "llvm/CodeGen/PhyRegAlloc.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineFrameInfo.h"
19 // ***TODO: There are several places we add instructions. Validate the order
20 // of adding these instructions.
24 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
25 "enable register allocation debugging information",
26 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
27 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
28 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
31 //----------------------------------------------------------------------------
32 // Constructor: Init local composite objects and create register classes.
33 //----------------------------------------------------------------------------
34 PhyRegAlloc::PhyRegAlloc(Method *M,
35 const TargetMachine& tm,
36 MethodLiveVarInfo *const Lvi)
40 mcInfo(MachineCodeForMethod::get(M)),
41 LVI(Lvi), LRI(M, tm, RegClassList),
42 MRI( tm.getRegInfo() ),
43 NumOfRegClasses(MRI.getNumOfRegClasses()),
47 // **TODO: use an actual reserved color list
48 ReservedColorListType *RCL = new ReservedColorListType();
50 // create each RegisterClass and put in RegClassList
51 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
52 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), RCL) );
55 //----------------------------------------------------------------------------
56 // This method initally creates interference graphs (one in each reg class)
57 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
58 //----------------------------------------------------------------------------
60 void PhyRegAlloc::createIGNodeListsAndIGs()
62 if(DEBUG_RA ) cout << "Creating LR lists ..." << endl;
65 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
68 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
70 for( ; HMI != HMIEnd ; ++HMI ) {
74 LiveRange *L = (*HMI).second; // get the LiveRange
78 cout << "\n*?!?Warning: Null liver range found for: ";
79 printValue( (*HMI).first) ; cout << endl;
83 // if the Value * is not null, and LR
84 // is not yet written to the IGNodeList
85 if( !(L->getUserIGNode()) ) {
87 RegClass *const RC = // RegClass of first value in the LR
88 //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
89 RegClassList[ L->getRegClass()->getID() ];
91 RC-> addLRToIG( L ); // add this LR to an IG
97 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
98 RegClassList[ rc ]->createInterferenceGraph();
101 cout << "LRLists Created!" << endl;
106 //----------------------------------------------------------------------------
107 // This method will add all interferences at for a given instruction.
108 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
109 // class as that of live var. The live var passed to this function is the
110 // LVset AFTER the instruction
111 //----------------------------------------------------------------------------
113 void PhyRegAlloc::addInterference(const Value *const Def,
114 const LiveVarSet *const LVSet,
115 const bool isCallInst) {
117 LiveVarSet::const_iterator LIt = LVSet->begin();
119 // get the live range of instruction
120 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
122 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
123 assert( IGNodeOfDef );
125 RegClass *const RCOfDef = LROfDef->getRegClass();
127 // for each live var in live variable set
128 for( ; LIt != LVSet->end(); ++LIt) {
131 cout << "< Def="; printValue(Def);
132 cout << ", Lvar="; printValue( *LIt); cout << "> ";
135 // get the live range corresponding to live var
136 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
138 // LROfVar can be null if it is a const since a const
139 // doesn't have a dominating def - see Assumptions above
142 if(LROfDef == LROfVar) // do not set interf for same LR
145 // if 2 reg classes are the same set interference
146 if( RCOfDef == LROfVar->getRegClass() ){
147 RCOfDef->setInterference( LROfDef, LROfVar);
151 else if(DEBUG_RA > 1) {
152 // we will not have LRs for values not explicitly allocated in the
153 // instruction stream (e.g., constants)
154 cout << " warning: no live range for " ;
155 printValue( *LIt); cout << endl; }
164 //----------------------------------------------------------------------------
165 // For a call instruction, this method sets the CallInterference flag in
166 // the LR of each variable live int the Live Variable Set live after the
167 // call instruction (except the return value of the call instruction - since
168 // the return value does not interfere with that call itself).
169 //----------------------------------------------------------------------------
171 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
172 const LiveVarSet *const LVSetAft )
174 // Now find the LR of the return value of the call
177 // We do this because, we look at the LV set *after* the instruction
178 // to determine, which LRs must be saved across calls. The return value
179 // of the call is live in this set - but it does not interfere with call
180 // (i.e., we can allocate a volatile register to the return value)
182 LiveRange *RetValLR = NULL;
184 const Value *RetVal = MRI.getCallInstRetVal( MInst );
187 RetValLR = LRI.getLiveRangeForValue( RetVal );
188 assert( RetValLR && "No LR for RetValue of call");
192 cout << "\n For call inst: " << *MInst;
194 LiveVarSet::const_iterator LIt = LVSetAft->begin();
196 // for each live var in live variable set after machine inst
197 for( ; LIt != LVSetAft->end(); ++LIt) {
199 // get the live range corresponding to live var
200 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
202 if( LR && DEBUG_RA) {
203 cout << "\n\tLR Aft Call: ";
208 // LR can be null if it is a const since a const
209 // doesn't have a dominating def - see Assumptions above
210 if( LR && (LR != RetValLR) ) {
211 LR->setCallInterference();
213 cout << "\n ++Added call interf for LR: " ;
223 //----------------------------------------------------------------------------
224 // This method will walk thru code and create interferences in the IG of
226 //----------------------------------------------------------------------------
228 void PhyRegAlloc::buildInterferenceGraphs()
231 if(DEBUG_RA) cout << "Creating interference graphs ..." << endl;
233 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
235 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
237 // get the iterator for machine instructions
238 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
239 MachineCodeForBasicBlock::const_iterator
240 MInstIterator = MIVec.begin();
242 // iterate over all the machine instructions in BB
243 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
245 const MachineInstr * MInst = *MInstIterator;
247 // get the LV set after the instruction
248 const LiveVarSet *const LVSetAI =
249 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
251 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
254 //cout << "\nFor call inst: " << *MInst;
256 // set the isCallInterference flag of each live range wich extends
257 // accross this call instruction. This information is used by graph
258 // coloring algo to avoid allocating volatile colors to live ranges
259 // that span across calls (since they have to be saved/restored)
260 setCallInterferences( MInst, LVSetAI);
264 // iterate over MI operands to find defs
265 for( MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done(); ++OpI) {
268 // create a new LR iff this operand is a def
269 addInterference(*OpI, LVSetAI, isCallInst );
271 } // for all operands
274 // if there are multiple defs in this instruction e.g. in SETX
276 if( (TM.getInstrInfo()).isPseudoInstr( MInst->getOpCode()) )
277 addInterf4PseudoInstr(MInst);
280 // Also add interference for any implicit definitions in a machine
281 // instr (currently, only calls have this).
283 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
284 if( NumOfImpRefs > 0 ) {
285 for(unsigned z=0; z < NumOfImpRefs; z++)
286 if( MInst->implicitRefIsDefined(z) )
287 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
291 // record phi instrns in PhiInstList
292 if( TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()) )
293 PhiInstList.push_back( MInst );
296 } // for all machine instructions in BB
298 } // for all BBs in method
301 // add interferences for method arguments. Since there are no explict
302 // defs in method for args, we have to add them manually
304 addInterferencesForArgs(); // add interference for method args
307 cout << "Interference graphs calculted!" << endl;
311 //--------------------------------------------------------------------------
312 // Pseudo instructions will be exapnded to multiple instructions by the
313 // assembler. Consequently, all the opernds must get distinct registers
314 //--------------------------------------------------------------------------
316 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
318 bool setInterf = false;
320 // iterate over MI operands to find defs
321 for( MachineInstr::val_op_const_iterator It1(MInst);!It1.done(); ++It1) {
323 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
325 if( !LROfOp1 && It1.isDef() )
326 assert( 0 && "No LR for Def in PSEUDO insruction");
328 //if( !LROfOp1 ) continue;
330 MachineInstr::val_op_const_iterator It2 = It1;
333 for( ; !It2.done(); ++It2) {
335 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
339 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
340 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
342 if( RCOfOp1 == RCOfOp2 ){
343 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
344 //cerr << "\nSet interfs for PSEUDO inst: " << *MInst;
351 } // for all other defs in machine instr
353 } // for all operands in an instruction
355 if( !setInterf && (MInst->getNumOperands() > 2) ) {
356 cerr << "\nInterf not set for any operand in pseudo instr:\n";
358 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
368 //----------------------------------------------------------------------------
369 // This method will add interferences for incoming arguments to a method.
370 //----------------------------------------------------------------------------
371 void PhyRegAlloc::addInterferencesForArgs()
373 // get the InSet of root BB
374 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
376 // get the argument list
377 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
379 // get an iterator to arg list
380 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
383 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
384 addInterference( *ArgIt, InSet, false ); // add interferences between
385 // args and LVars at start
387 cout << " - %% adding interference for argument ";
388 printValue( (const Value *) *ArgIt); cout << endl;
394 //----------------------------------------------------------------------------
395 // This method is called after register allocation is complete to set the
396 // allocated reisters in the machine code. This code will add register numbers
397 // to MachineOperands that contain a Value.
398 //----------------------------------------------------------------------------
400 void PhyRegAlloc::updateMachineCode()
403 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
405 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
407 // get the iterator for machine instructions
408 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
409 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
411 // iterate over all the machine instructions in BB
412 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
414 MachineInstr *MInst = *MInstIterator;
416 // do not process Phis
417 if( (TM.getInstrInfo()).isPhi( MInst->getOpCode()) )
421 // if this machine instr is call, insert caller saving code
423 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
424 MRI.insertCallerSavingCode(MInst, *BBI, *this );
427 // reset the stack offset for temporary variables since we may
428 // need that to spill
429 //mcInfo.popAllTempValues(TM);
430 // TODO ** : do later
432 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
435 // Now replace set the registers for operands in the machine instruction
437 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
439 MachineOperand& Op = MInst->getOperand(OpNum);
441 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
442 Op.getOperandType() == MachineOperand::MO_CCRegister) {
444 const Value *const Val = Op.getVRegValue();
446 // delete this condition checking later (must assert if Val is null)
449 cout << "Warning: NULL Value found for operand" << endl;
452 assert( Val && "Value is NULL");
454 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
458 // nothing to worry if it's a const or a label
461 cout << "*NO LR for operand : " << Op ;
462 cout << " [reg:" << Op.getAllocatedRegNum() << "]";
463 cout << " in inst:\t" << *MInst << endl;
466 // if register is not allocated, mark register as invalid
467 if( Op.getAllocatedRegNum() == -1)
468 Op.setRegForValue( MRI.getInvalidRegNum());
474 unsigned RCID = (LR->getRegClass())->getID();
476 if( LR->hasColor() ) {
477 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
481 // LR did NOT receive a color (register). Now, insert spill code
482 // for spilled opeands in this machine instruction
484 //assert(0 && "LR must be spilled");
485 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
490 } // for each operand
493 // If there are instructions to be added, *before* this machine
494 // instruction, add them now.
496 if( AddedInstrMap[ MInst ] ) {
498 deque<MachineInstr *> &IBef = (AddedInstrMap[MInst])->InstrnsBefore;
500 if( ! IBef.empty() ) {
502 deque<MachineInstr *>::iterator AdIt;
504 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
507 cerr << "For inst " << *MInst;
508 cerr << " PREPENDed instr: " << **AdIt << endl;
511 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
519 // If there are instructions to be added *after* this machine
520 // instruction, add them now
522 if( AddedInstrMap[ MInst ] &&
523 ! (AddedInstrMap[ MInst ]->InstrnsAfter).empty() ) {
525 // if there are delay slots for this instruction, the instructions
526 // added after it must really go after the delayed instruction(s)
527 // So, we move the InstrAfter of the current instruction to the
528 // corresponding delayed instruction
531 if((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
532 move2DelayedInstr(MInst, *(MInstIterator+delay) );
534 if(DEBUG_RA) cout<< "\nMoved an added instr after the delay slot";
540 // Here we can add the "instructions after" to the current
541 // instruction since there are no delay slots for this instruction
543 deque<MachineInstr *> &IAft = (AddedInstrMap[MInst])->InstrnsAfter;
545 if( ! IAft.empty() ) {
547 deque<MachineInstr *>::iterator AdIt;
549 ++MInstIterator; // advance to the next instruction
551 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
554 cerr << "For inst " << *MInst;
555 cerr << " APPENDed instr: " << **AdIt << endl;
558 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
562 // MInsterator already points to the next instr. Since the
563 // for loop also increments it, decrement it to point to the
564 // instruction added last
573 } // for each machine instruction
579 //----------------------------------------------------------------------------
580 // This method inserts spill code for AN operand whose LR was spilled.
581 // This method may be called several times for a single machine instruction
582 // if it contains many spilled operands. Each time it is called, it finds
583 // a register which is not live at that instruction and also which is not
584 // used by other spilled operands of the same instruction. Then it uses
585 // this register temporarily to accomodate the spilled value.
586 //----------------------------------------------------------------------------
587 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
589 const BasicBlock *BB,
590 const unsigned OpNum) {
592 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
593 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
594 "Arg of a call/ret must be handled elsewhere");
596 MachineOperand& Op = MInst->getOperand(OpNum);
597 bool isDef = MInst->operandIsDefined(OpNum);
598 unsigned RegType = MRI.getRegType( LR );
599 int SpillOff = LR->getSpillOffFromFP();
600 RegClass *RC = LR->getRegClass();
601 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
603 /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
605 mcInfo.pushTempValue(TM, 8 /* TM.findOptimalStorageSize(LR->getType()) */);
607 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
609 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
611 // get the added instructions for this instruciton
612 AddedInstrns *AI = AddedInstrMap[ MInst ];
614 AI = new AddedInstrns();
615 AddedInstrMap[ MInst ] = AI;
621 // for a USE, we have to load the value of LR from stack to a TmpReg
622 // and use the TmpReg as one operand of instruction
624 // actual loading instruction
625 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
628 (AI->InstrnsBefore).push_back(MIBef);
630 (AI->InstrnsBefore).push_back(AdIMid);
633 (AI->InstrnsAfter).push_front(MIAft);
637 else { // if this is a Def
639 // for a DEF, we have to store the value produced by this instruction
640 // on the stack position allocated for this LR
642 // actual storing instruction
643 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
646 (AI->InstrnsBefore).push_back(MIBef);
648 (AI->InstrnsAfter).push_front(AdIMid);
651 (AI->InstrnsAfter).push_front(MIAft);
655 cerr << "\nFor Inst " << *MInst;
656 cerr << " - SPILLED LR: "; LR->printSet();
657 cerr << "\n - Added Instructions:";
658 if( MIBef ) cerr << *MIBef;
660 if( MIAft ) cerr << *MIAft;
662 Op.setRegForValue( TmpRegU ); // set the opearnd
672 //----------------------------------------------------------------------------
673 // We can use the following method to get a temporary register to be used
674 // BEFORE any given machine instruction. If there is a register available,
675 // this method will simply return that register and set MIBef = MIAft = NULL.
676 // Otherwise, it will return a register and MIAft and MIBef will contain
677 // two instructions used to free up this returned register.
678 // Returned register number is the UNIFIED register number
679 //----------------------------------------------------------------------------
681 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
683 const MachineInstr *MInst,
684 const LiveVarSet *LVSetBef,
686 MachineInstr *MIAft) {
688 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
692 // we found an unused register, so we can simply use it
693 MIBef = MIAft = NULL;
696 // we couldn't find an unused register. Generate code to free up a reg by
697 // saving it on stack and restoring after the instruction
699 /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
700 int TmpOff = mcInfo.pushTempValue(TM, /*size*/ 8);
702 RegU = getUniRegNotUsedByThisInst(RC, MInst);
703 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
704 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
710 //----------------------------------------------------------------------------
711 // This method is called to get a new unused register that can be used to
712 // accomodate a spilled value.
713 // This method may be called several times for a single machine instruction
714 // if it contains many spilled operands. Each time it is called, it finds
715 // a register which is not live at that instruction and also which is not
716 // used by other spilled operands of the same instruction.
717 // Return register number is relative to the register class. NOT
719 //----------------------------------------------------------------------------
720 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
721 const MachineInstr *MInst,
722 const LiveVarSet *LVSetBef) {
724 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
726 bool *IsColorUsedArr = RC->getIsColorUsedArr();
728 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
729 IsColorUsedArr[i] = false;
731 LiveVarSet::const_iterator LIt = LVSetBef->begin();
733 // for each live var in live variable set after machine inst
734 for( ; LIt != LVSetBef->end(); ++LIt) {
736 // get the live range corresponding to live var
737 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
739 // LR can be null if it is a const since a const
740 // doesn't have a dominating def - see Assumptions above
742 if( LRofLV->hasColor() )
743 IsColorUsedArr[ LRofLV->getColor() ] = true;
746 // It is possible that one operand of this MInst was already spilled
747 // and it received some register temporarily. If that's the case,
748 // it is recorded in machine operand. We must skip such registers.
750 setRelRegsUsedByThisInst(RC, MInst);
752 unsigned c; // find first unused color
753 for( c=0; c < NumAvailRegs; c++)
754 if( ! IsColorUsedArr[ c ] ) break;
757 return MRI.getUnifiedRegNum(RC->getID(), c);
765 //----------------------------------------------------------------------------
766 // Get any other register in a register class, other than what is used
767 // by operands of a machine instruction. Returns the unified reg number.
768 //----------------------------------------------------------------------------
769 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
770 const MachineInstr *MInst) {
772 bool *IsColorUsedArr = RC->getIsColorUsedArr();
773 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
776 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
777 IsColorUsedArr[i] = false;
779 setRelRegsUsedByThisInst(RC, MInst);
781 unsigned c; // find first unused color
782 for( c=0; c < RC->getNumOfAvailRegs(); c++)
783 if( ! IsColorUsedArr[ c ] ) break;
786 return MRI.getUnifiedRegNum(RC->getID(), c);
788 assert( 0 && "FATAL: No free register could be found in reg class!!");
796 //----------------------------------------------------------------------------
797 // This method modifies the IsColorUsedArr of the register class passed to it.
798 // It sets the bits corresponding to the registers used by this machine
799 // instructions. Both explicit and implicit operands are set.
800 //----------------------------------------------------------------------------
801 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
802 const MachineInstr *MInst ) {
804 bool *IsColorUsedArr = RC->getIsColorUsedArr();
806 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
808 const MachineOperand& Op = MInst->getOperand(OpNum);
810 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
811 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
813 const Value *const Val = Op.getVRegValue();
816 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
818 if( (Reg=Op.getAllocatedRegNum()) != -1) {
819 IsColorUsedArr[ Reg ] = true;
822 // it is possilbe that this operand still is not marked with
823 // a register but it has a LR and that received a color
825 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
827 if( LROfVal->hasColor() )
828 IsColorUsedArr[ LROfVal->getColor() ] = true;
831 } // if reg classes are the same
833 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
834 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
838 // If there are implicit references, mark them as well
840 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
842 LiveRange *const LRofImpRef =
843 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
846 if( LRofImpRef->hasColor() )
847 IsColorUsedArr[ LRofImpRef->getColor() ] = true;
861 //----------------------------------------------------------------------------
862 // If there are delay slots for an instruction, the instructions
863 // added after it must really go after the delayed instruction(s).
864 // So, we move the InstrAfter of that instruction to the
865 // corresponding delayed instruction using the following method.
867 //----------------------------------------------------------------------------
868 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
869 const MachineInstr *DelayedMI) {
872 // "added after" instructions of the original instr
873 deque<MachineInstr *> &OrigAft = (AddedInstrMap[OrigMI])->InstrnsAfter;
875 // "added instructions" of the delayed instr
876 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
878 if(! DelayAdI ) { // create a new "added after" if necessary
879 DelayAdI = new AddedInstrns();
880 AddedInstrMap[DelayedMI] = DelayAdI;
883 // "added after" instructions of the delayed instr
884 deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
886 // go thru all the "added after instructions" of the original instruction
887 // and append them to the "addded after instructions" of the delayed
890 deque<MachineInstr *>::iterator OrigAdIt;
892 for( OrigAdIt = OrigAft.begin(); OrigAdIt != OrigAft.end() ; ++OrigAdIt ) {
893 DelayedAft.push_back( *OrigAdIt );
896 // empty the "added after instructions" of the original instruction
901 //----------------------------------------------------------------------------
902 // This method prints the code with registers after register allocation is
904 //----------------------------------------------------------------------------
905 void PhyRegAlloc::printMachineCode()
908 cout << endl << ";************** Method ";
909 cout << Meth->getName() << " *****************" << endl;
911 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
913 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
915 cout << endl ; printLabel( *BBI); cout << ": ";
917 // get the iterator for machine instructions
918 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
919 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
921 // iterate over all the machine instructions in BB
922 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
924 MachineInstr *const MInst = *MInstIterator;
927 cout << endl << "\t";
928 cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
931 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
933 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
935 MachineOperand& Op = MInst->getOperand(OpNum);
937 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
938 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
939 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
941 const Value *const Val = Op.getVRegValue () ;
942 // ****this code is temporary till NULL Values are fixed
944 cout << "\t<*NULL*>";
948 // if a label or a constant
949 if( (Val->getValueType() == Value::BasicBlockVal) ) {
951 cout << "\t"; printLabel( Op.getVRegValue () );
954 // else it must be a register value
955 const int RegNum = Op.getAllocatedRegNum();
957 cout << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
959 cout << "(" << Val->getName() << ")";
961 cout << "(" << Val << ")";
966 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
968 if( LROfVal->hasSpillOffset() )
973 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
974 cout << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
978 cout << "\t" << Op; // use dump field
983 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
984 if( NumOfImpRefs > 0 ) {
986 cout << "\tImplicit:";
988 for(unsigned z=0; z < NumOfImpRefs; z++) {
989 printValue( MInst->getImplicitRef(z) );
995 } // for all machine instructions
1006 //----------------------------------------------------------------------------
1008 //----------------------------------------------------------------------------
1010 void PhyRegAlloc::colorCallRetArgs()
1013 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1014 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1016 for( ; It != CallRetInstList.end(); ++It ) {
1018 const MachineInstr *const CRMI = *It;
1019 unsigned OpCode = CRMI->getOpCode();
1021 // get the added instructions for this Call/Ret instruciton
1022 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1024 AI = new AddedInstrns();
1025 AddedInstrMap[ CRMI ] = AI;
1028 // Tmp stack poistions are needed by some calls that have spilled args
1029 // So reset it before we call each such method
1030 //mcInfo.popAllTempValues(TM);
1034 if( (TM.getInstrInfo()).isCall( OpCode ) )
1035 MRI.colorCallArgs( CRMI, LRI, AI, *this );
1037 else if ( (TM.getInstrInfo()).isReturn(OpCode) )
1038 MRI.colorRetValue( CRMI, LRI, AI );
1040 else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
1048 //----------------------------------------------------------------------------
1050 //----------------------------------------------------------------------------
1051 void PhyRegAlloc::colorIncomingArgs()
1053 const BasicBlock *const FirstBB = Meth->front();
1054 const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
1055 assert( FirstMI && "No machine instruction in entry BB");
1057 AddedInstrns *AI = AddedInstrMap[ FirstMI ];
1059 AI = new AddedInstrns();
1060 AddedInstrMap[ FirstMI ] = AI;
1063 MRI.colorMethodArgs(Meth, LRI, AI );
1067 //----------------------------------------------------------------------------
1068 // Used to generate a label for a basic block
1069 //----------------------------------------------------------------------------
1070 void PhyRegAlloc::printLabel(const Value *const Val)
1072 if( Val->hasName() )
1073 cout << Val->getName();
1075 cout << "Label" << Val;
1079 //----------------------------------------------------------------------------
1080 // This method calls setSugColorUsable method of each live range. This
1081 // will determine whether the suggested color of LR is really usable.
1082 // A suggested color is not usable when the suggested color is volatile
1083 // AND when there are call interferences
1084 //----------------------------------------------------------------------------
1086 void PhyRegAlloc::markUnusableSugColors()
1088 if(DEBUG_RA ) cout << "\nmarking unusable suggested colors ..." << endl;
1090 // hash map iterator
1091 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1092 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1094 for( ; HMI != HMIEnd ; ++HMI ) {
1096 if( (*HMI).first ) {
1098 LiveRange *L = (*HMI).second; // get the LiveRange
1101 if( L->hasSuggestedColor() ) {
1103 int RCID = (L->getRegClass())->getID();
1104 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1105 L->isCallInterference() )
1106 L->setSuggestedColorUsable( false );
1108 L->setSuggestedColorUsable( true );
1110 } // if L->hasSuggestedColor()
1112 } // for all LR's in hash map
1117 //----------------------------------------------------------------------------
1118 // The following method will set the stack offsets of the live ranges that
1119 // are decided to be spillled. This must be called just after coloring the
1120 // LRs using the graph coloring algo. For each live range that is spilled,
1121 // this method allocate a new spill position on the stack.
1122 //----------------------------------------------------------------------------
1124 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1126 if(DEBUG_RA ) cout << "\nsetting LR stack offsets ..." << endl;
1128 // hash map iterator
1129 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1130 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1132 for( ; HMI != HMIEnd ; ++HMI ) {
1133 if( (*HMI).first ) {
1134 LiveRange *L = (*HMI).second; // get the LiveRange
1136 if( ! L->hasColor() )
1137 /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
1138 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy /*L->getType()*/ ));
1140 } // for all LR's in hash map
1145 //----------------------------------------------------------------------------
1146 // The entry pont to Register Allocation
1147 //----------------------------------------------------------------------------
1149 void PhyRegAlloc::allocateRegisters()
1152 // make sure that we put all register classes into the RegClassList
1153 // before we call constructLiveRanges (now done in the constructor of
1154 // PhyRegAlloc class).
1156 constructLiveRanges(); // create LR info
1159 LRI.printLiveRanges();
1161 createIGNodeListsAndIGs(); // create IGNode list and IGs
1163 buildInterferenceGraphs(); // build IGs in all reg classes
1167 // print all LRs in all reg classes
1168 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1169 RegClassList[ rc ]->printIGNodeList();
1171 // print IGs in all register classes
1172 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1173 RegClassList[ rc ]->printIG();
1176 LRI.coalesceLRs(); // coalesce all live ranges
1178 // coalscing could not get rid of all phi's, add phi elimination
1180 // insertPhiEleminateInstrns();
1183 // print all LRs in all reg classes
1184 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1185 RegClassList[ rc ]->printIGNodeList();
1187 // print IGs in all register classes
1188 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1189 RegClassList[ rc ]->printIG();
1193 // mark un-usable suggested color before graph coloring algorithm.
1194 // When this is done, the graph coloring algo will not reserve
1195 // suggested color unnecessarily - they can be used by another LR
1196 markUnusableSugColors();
1198 // color all register classes using the graph coloring algo
1199 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1200 RegClassList[ rc ]->colorAllRegs();
1202 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1203 // a poistion for such spilled LRs
1204 allocateStackSpace4SpilledLRs();
1206 mcInfo.popAllTempValues(TM); // TODO **Check
1208 // color incoming args and call args
1209 colorIncomingArgs();
1213 updateMachineCode();
1215 MachineCodeForMethod::get(Meth).dump();
1216 printMachineCode(); // only for DEBUGGING
1222 printMachineCode(); // only for DEBUGGING
1224 cout << "\nAllocted for method " << Meth->getName();