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/Function.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 FunctionPass {
44 TargetMachine &Target;
46 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
48 bool runOnFunction(Function *F) {
50 cerr << "\n******************** Function "<< F->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(F, Target, &getAnalysis<MethodLiveVarInfo>(),
54 &getAnalysis<cfg::LoopInfo>());
55 PRA.allocateRegisters();
57 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired(cfg::LoopInfo::ID);
63 AU.addRequired(MethodLiveVarInfo::ID);
68 Pass *getRegisterAllocator(TargetMachine &T) {
69 return new RegisterAllocator(T);
72 //----------------------------------------------------------------------------
73 // Constructor: Init local composite objects and create register classes.
74 //----------------------------------------------------------------------------
75 PhyRegAlloc::PhyRegAlloc(Function *F,
76 const TargetMachine& tm,
77 MethodLiveVarInfo *Lvi,
80 mcInfo(MachineCodeForMethod::get(F)),
81 LVI(Lvi), LRI(F, tm, RegClassList),
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(F, 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];
101 AddedInstrMap.clear();
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) {
214 cerr << "\n For call inst: " << *MInst;
216 ValueSet::const_iterator LIt = LVSetAft->begin();
218 // for each live var in live variable set after machine inst
220 for( ; LIt != LVSetAft->end(); ++LIt) {
222 // get the live range corresponding to live var
224 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
226 if( LR && DEBUG_RA) {
227 cerr << "\n\tLR Aft Call: ";
231 // LR can be null if it is a const since a const
232 // doesn't have a dominating def - see Assumptions above
235 LR->setCallInterference();
237 cerr << "\n ++Added call interf for LR: " ;
244 // Now find the LR of the return value of the call
245 // We do this because, we look at the LV set *after* the instruction
246 // to determine, which LRs must be saved across calls. The return value
247 // of the call is live in this set - but it does not interfere with call
248 // (i.e., we can allocate a volatile register to the return value)
250 if( const Value *RetVal = MRI.getCallInstRetVal( MInst )) {
251 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
252 assert( RetValLR && "No LR for RetValue of call");
253 RetValLR->clearCallInterference();
256 // If the CALL is an indirect call, find the LR of the function pointer.
257 // That has a call interference because it conflicts with outgoing args.
258 if( const Value *AddrVal = MRI.getCallInstIndirectAddrVal( MInst )) {
259 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
260 assert( AddrValLR && "No LR for indirect addr val of call");
261 AddrValLR->setCallInterference();
269 //----------------------------------------------------------------------------
270 // This method will walk thru code and create interferences in the IG of
271 // each RegClass. Also, this method calculates the spill cost of each
272 // Live Range (it is done in this method to save another pass over the code).
273 //----------------------------------------------------------------------------
274 void PhyRegAlloc::buildInterferenceGraphs()
277 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
279 unsigned BBLoopDepthCost;
280 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
283 // find the 10^(loop_depth) of this BB
285 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
287 // get the iterator for machine instructions
289 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
290 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
292 // iterate over all the machine instructions in BB
294 for( ; MII != MIVec.end(); ++MII) {
296 const MachineInstr *MInst = *MII;
298 // get the LV set after the instruction
300 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
302 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
305 // set the isCallInterference flag of each live range wich extends
306 // accross this call instruction. This information is used by graph
307 // coloring algo to avoid allocating volatile colors to live ranges
308 // that span across calls (since they have to be saved/restored)
310 setCallInterferences(MInst, &LVSetAI);
314 // iterate over all MI operands to find defs
316 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
317 OpE = MInst->end(); OpI != OpE; ++OpI) {
318 if (OpI.isDef()) // create a new LR iff this operand is a def
319 addInterference(*OpI, &LVSetAI, isCallInst);
321 // Calculate the spill cost of each live range
323 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
324 if (LR) LR->addSpillCost(BBLoopDepthCost);
328 // if there are multiple defs in this instruction e.g. in SETX
330 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
331 addInterf4PseudoInstr(MInst);
334 // Also add interference for any implicit definitions in a machine
335 // instr (currently, only calls have this).
337 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
338 if( NumOfImpRefs > 0 ) {
339 for(unsigned z=0; z < NumOfImpRefs; z++)
340 if( MInst->implicitRefIsDefined(z) )
341 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
345 } // for all machine instructions in BB
346 } // for all BBs in function
349 // add interferences for function arguments. Since there are no explict
350 // defs in the function for args, we have to add them manually
352 addInterferencesForArgs();
355 cerr << "Interference graphs calculted!\n";
361 //--------------------------------------------------------------------------
362 // Pseudo instructions will be exapnded to multiple instructions by the
363 // assembler. Consequently, all the opernds must get distinct registers.
364 // Therefore, we mark all operands of a pseudo instruction as they interfere
366 //--------------------------------------------------------------------------
367 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
369 bool setInterf = false;
371 // iterate over MI operands to find defs
373 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
374 ItE = MInst->end(); It1 != ItE; ++It1) {
375 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
376 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
378 MachineInstr::const_val_op_iterator It2 = It1;
379 for(++It2; It2 != ItE; ++It2) {
380 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
383 RegClass *RCOfOp1 = LROfOp1->getRegClass();
384 RegClass *RCOfOp2 = LROfOp2->getRegClass();
386 if( RCOfOp1 == RCOfOp2 ){
387 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
391 } // for all other defs in machine instr
392 } // for all operands in an instruction
394 if (!setInterf && MInst->getNumOperands() > 2) {
395 cerr << "\nInterf not set for any operand in pseudo instr:\n";
397 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
403 //----------------------------------------------------------------------------
404 // This method will add interferences for incoming arguments to a function.
405 //----------------------------------------------------------------------------
406 void PhyRegAlloc::addInterferencesForArgs() {
407 // get the InSet of root BB
408 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
410 // get the argument list
411 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
413 // get an iterator to arg list
414 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
417 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
418 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
419 // args and LVars at start
421 cerr << " - %% adding interference for argument "
422 << 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 //----------------------------------------------------------------------------
436 //-----------------------------
437 // Utility functions used below
438 //-----------------------------
440 PrependInstructions(std::deque<MachineInstr *> &IBef,
441 MachineCodeForBasicBlock& MIVec,
442 MachineCodeForBasicBlock::iterator& MII,
443 const std::string& msg)
447 MachineInstr* OrigMI = *MII;
448 std::deque<MachineInstr *>::iterator AdIt;
449 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
452 if (OrigMI) cerr << "For MInst: " << *OrigMI;
453 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
455 MII = MIVec.insert(MII, *AdIt);
462 AppendInstructions(std::deque<MachineInstr *> &IAft,
463 MachineCodeForBasicBlock& MIVec,
464 MachineCodeForBasicBlock::iterator& MII,
465 const std::string& msg)
469 MachineInstr* OrigMI = *MII;
470 std::deque<MachineInstr *>::iterator AdIt;
471 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
474 if (OrigMI) cerr << "For MInst: " << *OrigMI;
475 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
477 ++MII; // insert before the next instruction
478 MII = MIVec.insert(MII, *AdIt);
484 void PhyRegAlloc::updateMachineCode()
486 const BasicBlock* entryBB = Meth->getEntryNode();
488 MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
489 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
491 // Insert any instructions needed at method entry
492 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
493 "At function entry: \n");
494 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
495 "InstrsAfter should be unnecessary since we are just inserting at "
496 "the function entry point here.");
499 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
502 // iterate over all the machine instructions in BB
503 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
504 for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
505 MII != MIVec.end(); ++MII) {
507 MachineInstr *MInst = *MII;
509 unsigned Opcode = MInst->getOpCode();
511 // do not process Phis
512 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
515 // Now insert speical instructions (if necessary) for call/return
518 if (TM.getInstrInfo().isCall(Opcode) ||
519 TM.getInstrInfo().isReturn(Opcode)) {
521 AddedInstrns &AI = AddedInstrMap[MInst];
523 // Tmp stack poistions are needed by some calls that have spilled args
524 // So reset it before we call each such method
526 mcInfo.popAllTempValues(TM);
528 if (TM.getInstrInfo().isCall(Opcode))
529 MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
530 else if (TM.getInstrInfo().isReturn(Opcode))
531 MRI.colorRetValue(MInst, LRI, &AI);
535 /* -- Using above code instead of this
537 // if this machine instr is call, insert caller saving code
539 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
540 MRI.insertCallerSavingCode(MInst, *BBI, *this );
545 // reset the stack offset for temporary variables since we may
546 // need that to spill
547 // mcInfo.popAllTempValues(TM);
548 // TODO ** : do later
550 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
553 // Now replace set the registers for operands in the machine instruction
555 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
557 MachineOperand& Op = MInst->getOperand(OpNum);
559 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
560 Op.getOperandType() == MachineOperand::MO_CCRegister) {
562 const Value *const Val = Op.getVRegValue();
564 // delete this condition checking later (must assert if Val is null)
567 cerr << "Warning: NULL Value found for operand\n";
570 assert( Val && "Value is NULL");
572 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
576 // nothing to worry if it's a const or a label
579 cerr << "*NO LR for operand : " << Op ;
580 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
581 cerr << " in inst:\t" << *MInst << "\n";
584 // if register is not allocated, mark register as invalid
585 if( Op.getAllocatedRegNum() == -1)
586 Op.setRegForValue( MRI.getInvalidRegNum());
592 unsigned RCID = (LR->getRegClass())->getID();
594 if( LR->hasColor() ) {
595 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
599 // LR did NOT receive a color (register). Now, insert spill code
600 // for spilled opeands in this machine instruction
602 //assert(0 && "LR must be spilled");
603 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
608 } // for each operand
611 // Now add instructions that the register allocator inserts before/after
612 // this machine instructions (done only for calls/rets/incoming args)
613 // We do this here, to ensure that spill for an instruction is inserted
614 // closest as possible to an instruction (see above insertCode4Spill...)
616 // If there are instructions to be added, *before* this machine
617 // instruction, add them now.
619 if(AddedInstrMap.count(MInst)) {
620 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
623 // If there are instructions to be added *after* this machine
624 // instruction, add them now
626 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
628 // if there are delay slots for this instruction, the instructions
629 // added after it must really go after the delayed instruction(s)
630 // So, we move the InstrAfter of the current instruction to the
631 // corresponding delayed instruction
634 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
635 move2DelayedInstr(MInst, *(MII+delay) );
637 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
641 // Here we can add the "instructions after" to the current
642 // instruction since there are no delay slots for this instruction
643 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
648 } // for each machine instruction
654 //----------------------------------------------------------------------------
655 // This method inserts spill code for AN operand whose LR was spilled.
656 // This method may be called several times for a single machine instruction
657 // if it contains many spilled operands. Each time it is called, it finds
658 // a register which is not live at that instruction and also which is not
659 // used by other spilled operands of the same instruction. Then it uses
660 // this register temporarily to accomodate the spilled value.
661 //----------------------------------------------------------------------------
662 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
664 const BasicBlock *BB,
665 const unsigned OpNum) {
667 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
668 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
669 "Arg of a call/ret must be handled elsewhere");
671 MachineOperand& Op = MInst->getOperand(OpNum);
672 bool isDef = MInst->operandIsDefined(OpNum);
673 unsigned RegType = MRI.getRegType( LR );
674 int SpillOff = LR->getSpillOffFromFP();
675 RegClass *RC = LR->getRegClass();
676 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
678 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
680 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
682 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
684 // get the added instructions for this instruciton
685 AddedInstrns &AI = AddedInstrMap[MInst];
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 // "added after" instructions of the delayed instr
929 std::deque<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
931 // go thru all the "added after instructions" of the original instruction
932 // and append them to the "addded after instructions" of the delayed
934 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
936 // empty the "added after instructions" of the original instruction
940 //----------------------------------------------------------------------------
941 // This method prints the code with registers after register allocation is
943 //----------------------------------------------------------------------------
944 void PhyRegAlloc::printMachineCode()
947 cerr << "\n;************** Function " << Meth->getName()
948 << " *****************\n";
950 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
952 cerr << "\n"; printLabel(*BBI); cerr << ": ";
954 // get the iterator for machine instructions
955 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
956 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
958 // iterate over all the machine instructions in BB
959 for( ; MII != MIVec.end(); ++MII) {
960 MachineInstr *const MInst = *MII;
963 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
965 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
966 MachineOperand& Op = MInst->getOperand(OpNum);
968 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
969 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
970 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
972 const Value *const Val = Op.getVRegValue () ;
973 // ****this code is temporary till NULL Values are fixed
975 cerr << "\t<*NULL*>";
979 // if a label or a constant
980 if(isa<BasicBlock>(Val)) {
981 cerr << "\t"; printLabel( Op.getVRegValue () );
983 // else it must be a register value
984 const int RegNum = Op.getAllocatedRegNum();
986 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
988 cerr << "(" << Val->getName() << ")";
990 cerr << "(" << Val << ")";
995 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
997 if( LROfVal->hasSpillOffset() )
1002 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1003 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1007 cerr << "\t" << Op; // use dump field
1012 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1013 if( NumOfImpRefs > 0) {
1014 cerr << "\tImplicit:";
1016 for(unsigned z=0; z < NumOfImpRefs; z++)
1017 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1020 } // for all machine instructions
1032 //----------------------------------------------------------------------------
1034 //----------------------------------------------------------------------------
1036 void PhyRegAlloc::colorCallRetArgs()
1039 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1040 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1042 for( ; It != CallRetInstList.end(); ++It ) {
1044 const MachineInstr *const CRMI = *It;
1045 unsigned OpCode = CRMI->getOpCode();
1047 // get the added instructions for this Call/Ret instruciton
1048 AddedInstrns &AI = AddedInstrMap[CRMI];
1050 // Tmp stack positions are needed by some calls that have spilled args
1051 // So reset it before we call each such method
1052 //mcInfo.popAllTempValues(TM);
1055 if (TM.getInstrInfo().isCall(OpCode))
1056 MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1057 else if (TM.getInstrInfo().isReturn(OpCode))
1058 MRI.colorRetValue(CRMI, LRI, &AI);
1060 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1066 //----------------------------------------------------------------------------
1068 //----------------------------------------------------------------------------
1069 void PhyRegAlloc::colorIncomingArgs()
1071 const BasicBlock *const FirstBB = Meth->front();
1072 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1073 assert(FirstMI && "No machine instruction in entry BB");
1075 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1079 //----------------------------------------------------------------------------
1080 // Used to generate a label for a basic block
1081 //----------------------------------------------------------------------------
1082 void PhyRegAlloc::printLabel(const Value *const Val) {
1084 cerr << Val->getName();
1086 cerr << "Label" << Val;
1090 //----------------------------------------------------------------------------
1091 // This method calls setSugColorUsable method of each live range. This
1092 // will determine whether the suggested color of LR is really usable.
1093 // A suggested color is not usable when the suggested color is volatile
1094 // AND when there are call interferences
1095 //----------------------------------------------------------------------------
1097 void PhyRegAlloc::markUnusableSugColors()
1099 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1101 // hash map iterator
1102 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1103 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1105 for(; HMI != HMIEnd ; ++HMI ) {
1107 LiveRange *L = HMI->second; // get the LiveRange
1109 if(L->hasSuggestedColor()) {
1110 int RCID = L->getRegClass()->getID();
1111 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1112 L->isCallInterference() )
1113 L->setSuggestedColorUsable( false );
1115 L->setSuggestedColorUsable( true );
1117 } // if L->hasSuggestedColor()
1119 } // for all LR's in hash map
1124 //----------------------------------------------------------------------------
1125 // The following method will set the stack offsets of the live ranges that
1126 // are decided to be spillled. This must be called just after coloring the
1127 // LRs using the graph coloring algo. For each live range that is spilled,
1128 // this method allocate a new spill position on the stack.
1129 //----------------------------------------------------------------------------
1131 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1132 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1134 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1135 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1137 for( ; HMI != HMIEnd ; ++HMI) {
1138 if (HMI->first && HMI->second) {
1139 LiveRange *L = HMI->second; // get the LiveRange
1140 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1141 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1143 } // for all LR's in hash map
1148 //----------------------------------------------------------------------------
1149 // The entry pont to Register Allocation
1150 //----------------------------------------------------------------------------
1152 void PhyRegAlloc::allocateRegisters()
1155 // make sure that we put all register classes into the RegClassList
1156 // before we call constructLiveRanges (now done in the constructor of
1157 // PhyRegAlloc class).
1159 LRI.constructLiveRanges(); // create LR info
1162 LRI.printLiveRanges();
1164 createIGNodeListsAndIGs(); // create IGNode list and IGs
1166 buildInterferenceGraphs(); // build IGs in all reg classes
1170 // print all LRs in all reg classes
1171 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1172 RegClassList[ rc ]->printIGNodeList();
1174 // print IGs in all register classes
1175 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1176 RegClassList[ rc ]->printIG();
1180 LRI.coalesceLRs(); // coalesce all live ranges
1184 // print all LRs in all reg classes
1185 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1186 RegClassList[ rc ]->printIGNodeList();
1188 // print IGs in all register classes
1189 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1190 RegClassList[ rc ]->printIG();
1194 // mark un-usable suggested color before graph coloring algorithm.
1195 // When this is done, the graph coloring algo will not reserve
1196 // suggested color unnecessarily - they can be used by another LR
1198 markUnusableSugColors();
1200 // color all register classes using the graph coloring algo
1201 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1202 RegClassList[ rc ]->colorAllRegs();
1204 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1205 // a poistion for such spilled LRs
1207 allocateStackSpace4SpilledLRs();
1209 mcInfo.popAllTempValues(TM); // TODO **Check
1211 // color incoming args - if the correct color was not received
1212 // insert code to copy to the correct register
1214 colorIncomingArgs();
1216 // Now update the machine code with register names and add any
1217 // additional code inserted by the register allocator to the instruction
1220 updateMachineCode();
1223 MachineCodeForMethod::get(Meth).dump();
1224 printMachineCode(); // only for DEBUGGING