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/BasicBlock.h"
22 #include "llvm/Method.h"
23 #include "llvm/Type.h"
29 // ***TODO: There are several places we add instructions. Validate the order
30 // of adding these instructions.
32 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
33 "enable register allocation debugging information",
34 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
35 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
36 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
39 //----------------------------------------------------------------------------
40 // RegisterAllocation pass front end...
41 //----------------------------------------------------------------------------
43 class RegisterAllocator : public MethodPass {
44 TargetMachine &Target;
46 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
48 bool runOnMethod(Method *M) {
50 cerr << "\n******************** Method "<< M->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
54 &getAnalysis<cfg::LoopInfo>());
55 PRA.allocateRegisters();
57 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
62 Pass::AnalysisSet &Destroyed,
63 Pass::AnalysisSet &Provided) {
64 Requires.push_back(cfg::LoopInfo::ID);
65 Requires.push_back(MethodLiveVarInfo::ID);
70 MethodPass *getRegisterAllocator(TargetMachine &T) {
71 return new RegisterAllocator(T);
74 //----------------------------------------------------------------------------
75 // Constructor: Init local composite objects and create register classes.
76 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Method *M,
78 const TargetMachine& tm,
79 MethodLiveVarInfo *Lvi,
82 mcInfo(MachineCodeForMethod::get(M)),
83 LVI(Lvi), LRI(M, tm, RegClassList),
84 MRI( tm.getRegInfo() ),
85 NumOfRegClasses(MRI.getNumOfRegClasses()),
88 // create each RegisterClass and put in RegClassList
90 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
91 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
96 //----------------------------------------------------------------------------
97 // Destructor: Deletes register classes
98 //----------------------------------------------------------------------------
99 PhyRegAlloc::~PhyRegAlloc() {
100 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
101 delete RegClassList[rc];
104 //----------------------------------------------------------------------------
105 // This method initally creates interference graphs (one in each reg class)
106 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
107 //----------------------------------------------------------------------------
108 void PhyRegAlloc::createIGNodeListsAndIGs() {
109 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
112 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
115 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
117 for (; HMI != HMIEnd ; ++HMI ) {
119 LiveRange *L = HMI->second; // get the LiveRange
122 cerr << "\n*?!?Warning: Null liver range found for: "
123 << RAV(HMI->first) << "\n";
127 // if the Value * is not null, and LR
128 // is not yet written to the IGNodeList
129 if( !(L->getUserIGNode()) ) {
130 RegClass *const RC = // RegClass of first value in the LR
131 RegClassList[ L->getRegClass()->getID() ];
133 RC->addLRToIG(L); // add this LR to an IG
139 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
140 RegClassList[rc]->createInterferenceGraph();
143 cerr << "LRLists Created!\n";
149 //----------------------------------------------------------------------------
150 // This method will add all interferences at for a given instruction.
151 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
152 // class as that of live var. The live var passed to this function is the
153 // LVset AFTER the instruction
154 //----------------------------------------------------------------------------
155 void PhyRegAlloc::addInterference(const Value *Def,
156 const ValueSet *LVSet,
159 ValueSet::const_iterator LIt = LVSet->begin();
161 // get the live range of instruction
163 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
165 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
166 assert( IGNodeOfDef );
168 RegClass *const RCOfDef = LROfDef->getRegClass();
170 // for each live var in live variable set
172 for( ; LIt != LVSet->end(); ++LIt) {
175 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
177 // get the live range corresponding to live var
179 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
181 // LROfVar can be null if it is a const since a const
182 // doesn't have a dominating def - see Assumptions above
185 if(LROfDef == LROfVar) // do not set interf for same LR
188 // if 2 reg classes are the same set interference
190 if (RCOfDef == LROfVar->getRegClass()) {
191 RCOfDef->setInterference( LROfDef, LROfVar);
192 } else if (DEBUG_RA > 1) {
193 // we will not have LRs for values not explicitly allocated in the
194 // instruction stream (e.g., constants)
195 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
203 //----------------------------------------------------------------------------
204 // For a call instruction, this method sets the CallInterference flag in
205 // the LR of each variable live int the Live Variable Set live after the
206 // call instruction (except the return value of the call instruction - since
207 // the return value does not interfere with that call itself).
208 //----------------------------------------------------------------------------
210 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
211 const ValueSet *LVSetAft) {
213 // Now find the LR of the return value of the call
214 // We do this because, we look at the LV set *after* the instruction
215 // to determine, which LRs must be saved across calls. The return value
216 // of the call is live in this set - but it does not interfere with call
217 // (i.e., we can allocate a volatile register to the return value)
219 LiveRange *RetValLR = NULL;
220 const Value *RetVal = MRI.getCallInstRetVal( MInst );
223 RetValLR = LRI.getLiveRangeForValue( RetVal );
224 assert( RetValLR && "No LR for RetValue of call");
228 cerr << "\n For call inst: " << *MInst;
230 ValueSet::const_iterator LIt = LVSetAft->begin();
232 // for each live var in live variable set after machine inst
234 for( ; LIt != LVSetAft->end(); ++LIt) {
236 // get the live range corresponding to live var
238 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
240 if( LR && DEBUG_RA) {
241 cerr << "\n\tLR Aft Call: ";
246 // LR can be null if it is a const since a const
247 // doesn't have a dominating def - see Assumptions above
249 if( LR && (LR != RetValLR) ) {
250 LR->setCallInterference();
252 cerr << "\n ++Added call interf for LR: " ;
264 //----------------------------------------------------------------------------
265 // This method will walk thru code and create interferences in the IG of
266 // each RegClass. Also, this method calculates the spill cost of each
267 // Live Range (it is done in this method to save another pass over the code).
268 //----------------------------------------------------------------------------
269 void PhyRegAlloc::buildInterferenceGraphs()
272 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
274 unsigned BBLoopDepthCost;
275 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
277 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
279 // find the 10^(loop_depth) of this BB
281 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
283 // get the iterator for machine instructions
285 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
286 MachineCodeForBasicBlock::const_iterator
287 MInstIterator = MIVec.begin();
289 // iterate over all the machine instructions in BB
291 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
293 const MachineInstr *MInst = *MInstIterator;
295 // get the LV set after the instruction
297 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
299 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
302 // set the isCallInterference flag of each live range wich extends
303 // accross this call instruction. This information is used by graph
304 // coloring algo to avoid allocating volatile colors to live ranges
305 // that span across calls (since they have to be saved/restored)
307 setCallInterferences(MInst, &LVSetAI);
311 // iterate over all MI operands to find defs
313 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
314 OpE = MInst->end(); OpI != OpE; ++OpI) {
315 if (OpI.isDef()) // create a new LR iff this operand is a def
316 addInterference(*OpI, &LVSetAI, isCallInst);
318 // Calculate the spill cost of each live range
320 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
321 if (LR) LR->addSpillCost(BBLoopDepthCost);
325 // if there are multiple defs in this instruction e.g. in SETX
327 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
328 addInterf4PseudoInstr(MInst);
331 // Also add interference for any implicit definitions in a machine
332 // instr (currently, only calls have this).
334 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
335 if( NumOfImpRefs > 0 ) {
336 for(unsigned z=0; z < NumOfImpRefs; z++)
337 if( MInst->implicitRefIsDefined(z) )
338 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
342 } // for all machine instructions in BB
344 } // for all BBs in method
347 // add interferences for method arguments. Since there are no explict
348 // defs in method for args, we have to add them manually
350 addInterferencesForArgs();
353 cerr << "Interference graphs calculted!\n";
359 //--------------------------------------------------------------------------
360 // Pseudo instructions will be exapnded to multiple instructions by the
361 // assembler. Consequently, all the opernds must get distinct registers.
362 // Therefore, we mark all operands of a pseudo instruction as they interfere
364 //--------------------------------------------------------------------------
365 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
367 bool setInterf = false;
369 // iterate over MI operands to find defs
371 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
372 ItE = MInst->end(); It1 != ItE; ++It1) {
373 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
374 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
376 MachineInstr::const_val_op_iterator It2 = It1;
377 for(++It2; It2 != ItE; ++It2) {
378 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
381 RegClass *RCOfOp1 = LROfOp1->getRegClass();
382 RegClass *RCOfOp2 = LROfOp2->getRegClass();
384 if( RCOfOp1 == RCOfOp2 ){
385 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
389 } // for all other defs in machine instr
390 } // for all operands in an instruction
392 if (!setInterf && MInst->getNumOperands() > 2) {
393 cerr << "\nInterf not set for any operand in pseudo instr:\n";
395 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
401 //----------------------------------------------------------------------------
402 // This method will add interferences for incoming arguments to a method.
403 //----------------------------------------------------------------------------
404 void PhyRegAlloc::addInterferencesForArgs() {
405 // get the InSet of root BB
406 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
408 // get the argument list
409 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
411 // get an iterator to arg list
412 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
415 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
416 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
417 // args and LVars at start
419 cerr << " - %% adding interference for argument "
420 << RAV((const Value *)*ArgIt) << "\n";
427 //----------------------------------------------------------------------------
428 // This method is called after register allocation is complete to set the
429 // allocated reisters in the machine code. This code will add register numbers
430 // to MachineOperands that contain a Value. Also it calls target specific
431 // methods to produce caller saving instructions. At the end, it adds all
432 // additional instructions produced by the register allocator to the
433 // instruction stream.
434 //----------------------------------------------------------------------------
435 void PhyRegAlloc::updateMachineCode()
438 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
440 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
442 // get the iterator for machine instructions
444 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
445 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
447 // iterate over all the machine instructions in BB
449 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
451 MachineInstr *MInst = *MInstIterator;
453 unsigned Opcode = MInst->getOpCode();
455 // do not process Phis
456 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
459 // Now insert speical instructions (if necessary) for call/return
462 if (TM.getInstrInfo().isCall(Opcode) ||
463 TM.getInstrInfo().isReturn(Opcode)) {
465 AddedInstrns *AI = AddedInstrMap[ MInst];
467 AI = new AddedInstrns();
468 AddedInstrMap[ MInst ] = AI;
471 // Tmp stack poistions are needed by some calls that have spilled args
472 // So reset it before we call each such method
474 mcInfo.popAllTempValues(TM);
476 if (TM.getInstrInfo().isCall(Opcode))
477 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
478 else if (TM.getInstrInfo().isReturn(Opcode))
479 MRI.colorRetValue(MInst, LRI, AI);
483 /* -- Using above code instead of this
485 // if this machine instr is call, insert caller saving code
487 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
488 MRI.insertCallerSavingCode(MInst, *BBI, *this );
493 // reset the stack offset for temporary variables since we may
494 // need that to spill
495 // mcInfo.popAllTempValues(TM);
496 // TODO ** : do later
498 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
501 // Now replace set the registers for operands in the machine instruction
503 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
505 MachineOperand& Op = MInst->getOperand(OpNum);
507 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
508 Op.getOperandType() == MachineOperand::MO_CCRegister) {
510 const Value *const Val = Op.getVRegValue();
512 // delete this condition checking later (must assert if Val is null)
515 cerr << "Warning: NULL Value found for operand\n";
518 assert( Val && "Value is NULL");
520 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
524 // nothing to worry if it's a const or a label
527 cerr << "*NO LR for operand : " << Op ;
528 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
529 cerr << " in inst:\t" << *MInst << "\n";
532 // if register is not allocated, mark register as invalid
533 if( Op.getAllocatedRegNum() == -1)
534 Op.setRegForValue( MRI.getInvalidRegNum());
540 unsigned RCID = (LR->getRegClass())->getID();
542 if( LR->hasColor() ) {
543 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
547 // LR did NOT receive a color (register). Now, insert spill code
548 // for spilled opeands in this machine instruction
550 //assert(0 && "LR must be spilled");
551 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
556 } // for each operand
559 // Now add instructions that the register allocator inserts before/after
560 // this machine instructions (done only for calls/rets/incoming args)
561 // We do this here, to ensure that spill for an instruction is inserted
562 // closest as possible to an instruction (see above insertCode4Spill...)
564 // If there are instructions to be added, *before* this machine
565 // instruction, add them now.
567 if( AddedInstrMap[ MInst ] ) {
568 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
570 if( ! IBef.empty() ) {
571 std::deque<MachineInstr *>::iterator AdIt;
573 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
576 cerr << "For inst " << *MInst;
577 cerr << " PREPENDed instr: " << **AdIt << "\n";
580 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
588 // If there are instructions to be added *after* this machine
589 // instruction, add them now
591 if(AddedInstrMap[MInst] &&
592 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
594 // if there are delay slots for this instruction, the instructions
595 // added after it must really go after the delayed instruction(s)
596 // So, we move the InstrAfter of the current instruction to the
597 // corresponding delayed instruction
600 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
601 move2DelayedInstr(MInst, *(MInstIterator+delay) );
603 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
609 // Here we can add the "instructions after" to the current
610 // instruction since there are no delay slots for this instruction
612 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
614 if( ! IAft.empty() ) {
616 std::deque<MachineInstr *>::iterator AdIt;
618 ++MInstIterator; // advance to the next instruction
620 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
623 cerr << "For inst " << *MInst;
624 cerr << " APPENDed instr: " << **AdIt << "\n";
627 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
631 // MInsterator already points to the next instr. Since the
632 // for loop also increments it, decrement it to point to the
633 // instruction added last
642 } // for each machine instruction
648 //----------------------------------------------------------------------------
649 // This method inserts spill code for AN operand whose LR was spilled.
650 // This method may be called several times for a single machine instruction
651 // if it contains many spilled operands. Each time it is called, it finds
652 // a register which is not live at that instruction and also which is not
653 // used by other spilled operands of the same instruction. Then it uses
654 // this register temporarily to accomodate the spilled value.
655 //----------------------------------------------------------------------------
656 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
658 const BasicBlock *BB,
659 const unsigned OpNum) {
661 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
662 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
663 "Arg of a call/ret must be handled elsewhere");
665 MachineOperand& Op = MInst->getOperand(OpNum);
666 bool isDef = MInst->operandIsDefined(OpNum);
667 unsigned RegType = MRI.getRegType( LR );
668 int SpillOff = LR->getSpillOffFromFP();
669 RegClass *RC = LR->getRegClass();
670 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
672 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
674 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
676 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
678 // get the added instructions for this instruciton
679 AddedInstrns *AI = AddedInstrMap[ MInst ];
681 AI = new AddedInstrns();
682 AddedInstrMap[ MInst ] = AI;
688 // for a USE, we have to load the value of LR from stack to a TmpReg
689 // and use the TmpReg as one operand of instruction
691 // actual loading instruction
692 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
695 AI->InstrnsBefore.push_back(MIBef);
697 AI->InstrnsBefore.push_back(AdIMid);
700 AI->InstrnsAfter.push_front(MIAft);
702 } else { // if this is a Def
703 // for a DEF, we have to store the value produced by this instruction
704 // on the stack position allocated for this LR
706 // actual storing instruction
707 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
710 AI->InstrnsBefore.push_back(MIBef);
712 AI->InstrnsAfter.push_front(AdIMid);
715 AI->InstrnsAfter.push_front(MIAft);
719 cerr << "\nFor Inst " << *MInst;
720 cerr << " - SPILLED LR: "; printSet(*LR);
721 cerr << "\n - Added Instructions:";
722 if (MIBef) cerr << *MIBef;
724 if (MIAft) cerr << *MIAft;
726 Op.setRegForValue(TmpRegU); // set the opearnd
731 //----------------------------------------------------------------------------
732 // We can use the following method to get a temporary register to be used
733 // BEFORE any given machine instruction. If there is a register available,
734 // this method will simply return that register and set MIBef = MIAft = NULL.
735 // Otherwise, it will return a register and MIAft and MIBef will contain
736 // two instructions used to free up this returned register.
737 // Returned register number is the UNIFIED register number
738 //----------------------------------------------------------------------------
740 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
742 const MachineInstr *MInst,
743 const ValueSet *LVSetBef,
744 MachineInstr *&MIBef,
745 MachineInstr *&MIAft) {
747 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
751 // we found an unused register, so we can simply use it
752 MIBef = MIAft = NULL;
755 // we couldn't find an unused register. Generate code to free up a reg by
756 // saving it on stack and restoring after the instruction
758 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
760 RegU = getUniRegNotUsedByThisInst(RC, MInst);
761 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
762 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
768 //----------------------------------------------------------------------------
769 // This method is called to get a new unused register that can be used to
770 // accomodate a spilled value.
771 // This method may be called several times for a single machine instruction
772 // if it contains many spilled operands. Each time it is called, it finds
773 // a register which is not live at that instruction and also which is not
774 // used by other spilled operands of the same instruction.
775 // Return register number is relative to the register class. NOT
777 //----------------------------------------------------------------------------
778 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
779 const MachineInstr *MInst,
780 const ValueSet *LVSetBef) {
782 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
784 bool *IsColorUsedArr = RC->getIsColorUsedArr();
786 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
787 IsColorUsedArr[i] = false;
789 ValueSet::const_iterator LIt = LVSetBef->begin();
791 // for each live var in live variable set after machine inst
792 for( ; LIt != LVSetBef->end(); ++LIt) {
794 // get the live range corresponding to live var
795 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
797 // LR can be null if it is a const since a const
798 // doesn't have a dominating def - see Assumptions above
800 if( LRofLV->hasColor() )
801 IsColorUsedArr[ LRofLV->getColor() ] = true;
804 // It is possible that one operand of this MInst was already spilled
805 // and it received some register temporarily. If that's the case,
806 // it is recorded in machine operand. We must skip such registers.
808 setRelRegsUsedByThisInst(RC, MInst);
810 unsigned c; // find first unused color
811 for( c=0; c < NumAvailRegs; c++)
812 if( ! IsColorUsedArr[ c ] ) break;
815 return MRI.getUnifiedRegNum(RC->getID(), c);
823 //----------------------------------------------------------------------------
824 // Get any other register in a register class, other than what is used
825 // by operands of a machine instruction. Returns the unified reg number.
826 //----------------------------------------------------------------------------
827 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
828 const MachineInstr *MInst) {
830 bool *IsColorUsedArr = RC->getIsColorUsedArr();
831 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
834 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
835 IsColorUsedArr[i] = false;
837 setRelRegsUsedByThisInst(RC, MInst);
839 unsigned c; // find first unused color
840 for( c=0; c < RC->getNumOfAvailRegs(); c++)
841 if( ! IsColorUsedArr[ c ] ) break;
844 return MRI.getUnifiedRegNum(RC->getID(), c);
846 assert( 0 && "FATAL: No free register could be found in reg class!!");
851 //----------------------------------------------------------------------------
852 // This method modifies the IsColorUsedArr of the register class passed to it.
853 // It sets the bits corresponding to the registers used by this machine
854 // instructions. Both explicit and implicit operands are set.
855 //----------------------------------------------------------------------------
856 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
857 const MachineInstr *MInst ) {
859 bool *IsColorUsedArr = RC->getIsColorUsedArr();
861 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
863 const MachineOperand& Op = MInst->getOperand(OpNum);
865 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
866 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
868 const Value *const Val = Op.getVRegValue();
871 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
873 if( (Reg=Op.getAllocatedRegNum()) != -1) {
874 IsColorUsedArr[ Reg ] = true;
877 // it is possilbe that this operand still is not marked with
878 // a register but it has a LR and that received a color
880 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
882 if( LROfVal->hasColor() )
883 IsColorUsedArr[ LROfVal->getColor() ] = true;
886 } // if reg classes are the same
888 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
889 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
893 // If there are implicit references, mark them as well
895 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
897 LiveRange *const LRofImpRef =
898 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
900 if(LRofImpRef && LRofImpRef->hasColor())
901 IsColorUsedArr[LRofImpRef->getColor()] = true;
912 //----------------------------------------------------------------------------
913 // If there are delay slots for an instruction, the instructions
914 // added after it must really go after the delayed instruction(s).
915 // So, we move the InstrAfter of that instruction to the
916 // corresponding delayed instruction using the following method.
918 //----------------------------------------------------------------------------
919 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
920 const MachineInstr *DelayedMI) {
922 // "added after" instructions of the original instr
923 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
925 // "added instructions" of the delayed instr
926 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
928 if(! DelayAdI ) { // create a new "added after" if necessary
929 DelayAdI = new AddedInstrns();
930 AddedInstrMap[DelayedMI] = DelayAdI;
933 // "added after" instructions of the delayed instr
934 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
936 // go thru all the "added after instructions" of the original instruction
937 // and append them to the "addded after instructions" of the delayed
939 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
941 // empty the "added after instructions" of the original instruction
945 //----------------------------------------------------------------------------
946 // This method prints the code with registers after register allocation is
948 //----------------------------------------------------------------------------
949 void PhyRegAlloc::printMachineCode()
952 cerr << "\n;************** Method " << Meth->getName()
953 << " *****************\n";
955 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
957 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
959 cerr << "\n"; printLabel( *BBI); cerr << ": ";
961 // get the iterator for machine instructions
962 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
963 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
965 // iterate over all the machine instructions in BB
966 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
968 MachineInstr *const MInst = *MInstIterator;
972 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
975 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
977 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
979 MachineOperand& Op = MInst->getOperand(OpNum);
981 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
982 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
983 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
985 const Value *const Val = Op.getVRegValue () ;
986 // ****this code is temporary till NULL Values are fixed
988 cerr << "\t<*NULL*>";
992 // if a label or a constant
993 if(isa<BasicBlock>(Val)) {
994 cerr << "\t"; printLabel( Op.getVRegValue () );
996 // else it must be a register value
997 const int RegNum = Op.getAllocatedRegNum();
999 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1000 if (Val->hasName() )
1001 cerr << "(" << Val->getName() << ")";
1003 cerr << "(" << Val << ")";
1008 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1010 if( LROfVal->hasSpillOffset() )
1015 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1016 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1020 cerr << "\t" << Op; // use dump field
1025 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1026 if( NumOfImpRefs > 0) {
1027 cerr << "\tImplicit:";
1029 for(unsigned z=0; z < NumOfImpRefs; z++)
1030 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1033 } // for all machine instructions
1045 //----------------------------------------------------------------------------
1047 //----------------------------------------------------------------------------
1049 void PhyRegAlloc::colorCallRetArgs()
1052 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1053 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1055 for( ; It != CallRetInstList.end(); ++It ) {
1057 const MachineInstr *const CRMI = *It;
1058 unsigned OpCode = CRMI->getOpCode();
1060 // get the added instructions for this Call/Ret instruciton
1061 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1063 AI = new AddedInstrns();
1064 AddedInstrMap[ CRMI ] = AI;
1067 // Tmp stack poistions are needed by some calls that have spilled args
1068 // So reset it before we call each such method
1069 //mcInfo.popAllTempValues(TM);
1073 if (TM.getInstrInfo().isCall(OpCode))
1074 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1075 else if (TM.getInstrInfo().isReturn(OpCode))
1076 MRI.colorRetValue( CRMI, LRI, AI );
1078 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1084 //----------------------------------------------------------------------------
1086 //----------------------------------------------------------------------------
1087 void PhyRegAlloc::colorIncomingArgs()
1089 const BasicBlock *const FirstBB = Meth->front();
1090 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1091 assert(FirstMI && "No machine instruction in entry BB");
1093 AddedInstrns *AI = AddedInstrMap[FirstMI];
1095 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1097 MRI.colorMethodArgs(Meth, LRI, AI);
1101 //----------------------------------------------------------------------------
1102 // Used to generate a label for a basic block
1103 //----------------------------------------------------------------------------
1104 void PhyRegAlloc::printLabel(const Value *const Val) {
1106 cerr << Val->getName();
1108 cerr << "Label" << Val;
1112 //----------------------------------------------------------------------------
1113 // This method calls setSugColorUsable method of each live range. This
1114 // will determine whether the suggested color of LR is really usable.
1115 // A suggested color is not usable when the suggested color is volatile
1116 // AND when there are call interferences
1117 //----------------------------------------------------------------------------
1119 void PhyRegAlloc::markUnusableSugColors()
1121 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1123 // hash map iterator
1124 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1125 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1127 for(; HMI != HMIEnd ; ++HMI ) {
1129 LiveRange *L = HMI->second; // get the LiveRange
1131 if(L->hasSuggestedColor()) {
1132 int RCID = L->getRegClass()->getID();
1133 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1134 L->isCallInterference() )
1135 L->setSuggestedColorUsable( false );
1137 L->setSuggestedColorUsable( true );
1139 } // if L->hasSuggestedColor()
1141 } // for all LR's in hash map
1146 //----------------------------------------------------------------------------
1147 // The following method will set the stack offsets of the live ranges that
1148 // are decided to be spillled. This must be called just after coloring the
1149 // LRs using the graph coloring algo. For each live range that is spilled,
1150 // this method allocate a new spill position on the stack.
1151 //----------------------------------------------------------------------------
1153 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1154 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1156 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1157 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1159 for( ; HMI != HMIEnd ; ++HMI) {
1160 if (HMI->first && HMI->second) {
1161 LiveRange *L = HMI->second; // get the LiveRange
1162 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1163 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1165 } // for all LR's in hash map
1170 //----------------------------------------------------------------------------
1171 // The entry pont to Register Allocation
1172 //----------------------------------------------------------------------------
1174 void PhyRegAlloc::allocateRegisters()
1177 // make sure that we put all register classes into the RegClassList
1178 // before we call constructLiveRanges (now done in the constructor of
1179 // PhyRegAlloc class).
1181 LRI.constructLiveRanges(); // create LR info
1184 LRI.printLiveRanges();
1186 createIGNodeListsAndIGs(); // create IGNode list and IGs
1188 buildInterferenceGraphs(); // build IGs in all reg classes
1192 // print all LRs in all reg classes
1193 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1194 RegClassList[ rc ]->printIGNodeList();
1196 // print IGs in all register classes
1197 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1198 RegClassList[ rc ]->printIG();
1202 LRI.coalesceLRs(); // coalesce all live ranges
1206 // print all LRs in all reg classes
1207 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1208 RegClassList[ rc ]->printIGNodeList();
1210 // print IGs in all register classes
1211 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1212 RegClassList[ rc ]->printIG();
1216 // mark un-usable suggested color before graph coloring algorithm.
1217 // When this is done, the graph coloring algo will not reserve
1218 // suggested color unnecessarily - they can be used by another LR
1220 markUnusableSugColors();
1222 // color all register classes using the graph coloring algo
1223 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1224 RegClassList[ rc ]->colorAllRegs();
1226 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1227 // a poistion for such spilled LRs
1229 allocateStackSpace4SpilledLRs();
1231 mcInfo.popAllTempValues(TM); // TODO **Check
1233 // color incoming args - if the correct color was not received
1234 // insert code to copy to the correct register
1236 colorIncomingArgs();
1238 // Now update the machine code with register names and add any
1239 // additional code inserted by the register allocator to the instruction
1242 updateMachineCode();
1245 MachineCodeForMethod::get(Meth).dump();
1246 printMachineCode(); // only for DEBUGGING