1 //***************************************************************************
6 // Register allocation for LLVM.
9 // 9/10/01 - Ruchira Sasanka - created.
10 //**************************************************************************/
12 #include "llvm/CodeGen/RegisterAllocation.h"
13 #include "llvm/CodeGen/PhyRegAlloc.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/CodeGen/MachineInstrAnnot.h"
16 #include "llvm/CodeGen/MachineCodeForMethod.h"
17 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.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"
24 #include "llvm/iOther.h"
25 #include "llvm/CodeGen/RegAllocCommon.h"
26 #include "Support/CommandLine.h"
32 RegAllocDebugLevel_t DEBUG_RA;
33 static cl::Enum<RegAllocDebugLevel_t> DEBUG_RA_c(DEBUG_RA, "dregalloc",
35 "enable register allocation debugging information",
36 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
37 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
38 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
41 //----------------------------------------------------------------------------
42 // RegisterAllocation pass front end...
43 //----------------------------------------------------------------------------
45 class RegisterAllocator : public FunctionPass {
46 TargetMachine &Target;
48 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
50 const char *getPassName() const { return "Register Allocation"; }
52 bool runOnFunction(Function &F) {
54 cerr << "\n********* Function "<< F.getName() << " ***********\n";
56 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
57 &getAnalysis<LoopInfo>());
58 PRA.allocateRegisters();
60 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired(LoopInfo::ID);
66 AU.addRequired(FunctionLiveVarInfo::ID);
71 Pass *getRegisterAllocator(TargetMachine &T) {
72 return new RegisterAllocator(T);
75 //----------------------------------------------------------------------------
76 // Constructor: Init local composite objects and create register classes.
77 //----------------------------------------------------------------------------
78 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
79 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
81 mcInfo(MachineCodeForMethod::get(F)),
82 LVI(Lvi), LRI(F, tm, RegClassList),
84 NumOfRegClasses(MRI.getNumOfRegClasses()),
87 // create each RegisterClass and put in RegClassList
89 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
90 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
95 //----------------------------------------------------------------------------
96 // Destructor: Deletes register classes
97 //----------------------------------------------------------------------------
98 PhyRegAlloc::~PhyRegAlloc() {
99 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
100 delete RegClassList[rc];
102 AddedInstrMap.clear();
105 //----------------------------------------------------------------------------
106 // This method initally creates interference graphs (one in each reg class)
107 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
108 //----------------------------------------------------------------------------
109 void PhyRegAlloc::createIGNodeListsAndIGs() {
110 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
113 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
116 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
118 for (; HMI != HMIEnd ; ++HMI ) {
120 LiveRange *L = HMI->second; // get the LiveRange
123 cerr << "\n*?!?Warning: Null liver range found for: "
124 << RAV(HMI->first) << "\n";
128 // if the Value * is not null, and LR
129 // is not yet written to the IGNodeList
130 if (!(L->getUserIGNode()) ) {
131 RegClass *const RC = // RegClass of first value in the LR
132 RegClassList[ L->getRegClass()->getID() ];
134 RC->addLRToIG(L); // add this LR to an IG
140 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
141 RegClassList[rc]->createInterferenceGraph();
144 cerr << "LRLists Created!\n";
150 //----------------------------------------------------------------------------
151 // This method will add all interferences at for a given instruction.
152 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
153 // class as that of live var. The live var passed to this function is the
154 // LVset AFTER the instruction
155 //----------------------------------------------------------------------------
156 void PhyRegAlloc::addInterference(const Value *Def,
157 const ValueSet *LVSet,
160 ValueSet::const_iterator LIt = LVSet->begin();
162 // get the live range of instruction
164 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
166 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
167 assert( IGNodeOfDef );
169 RegClass *const RCOfDef = LROfDef->getRegClass();
171 // for each live var in live variable set
173 for ( ; LIt != LVSet->end(); ++LIt) {
176 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
178 // get the live range corresponding to live var
180 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
182 // LROfVar can be null if it is a const since a const
183 // doesn't have a dominating def - see Assumptions above
186 if (LROfDef == LROfVar) // do not set interf for same LR
189 // if 2 reg classes are the same set interference
191 if (RCOfDef == LROfVar->getRegClass()) {
192 RCOfDef->setInterference( LROfDef, LROfVar);
193 } else if (DEBUG_RA > 1) {
194 // we will not have LRs for values not explicitly allocated in the
195 // instruction stream (e.g., constants)
196 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
204 //----------------------------------------------------------------------------
205 // For a call instruction, this method sets the CallInterference flag in
206 // the LR of each variable live int the Live Variable Set live after the
207 // call instruction (except the return value of the call instruction - since
208 // the return value does not interfere with that call itself).
209 //----------------------------------------------------------------------------
211 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
212 const ValueSet *LVSetAft) {
215 cerr << "\n For call inst: " << *MInst;
217 ValueSet::const_iterator LIt = LVSetAft->begin();
219 // for each live var in live variable set after machine inst
221 for ( ; LIt != LVSetAft->end(); ++LIt) {
223 // get the live range corresponding to live var
225 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
227 if (LR && DEBUG_RA) {
228 cerr << "\n\tLR Aft Call: ";
232 // LR can be null if it is a const since a const
233 // doesn't have a dominating def - see Assumptions above
236 LR->setCallInterference();
238 cerr << "\n ++Added call interf for LR: " ;
245 // Now find the LR of the return value of the call
246 // We do this because, we look at the LV set *after* the instruction
247 // to determine, which LRs must be saved across calls. The return value
248 // of the call is live in this set - but it does not interfere with call
249 // (i.e., we can allocate a volatile register to the return value)
251 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
253 if (const Value *RetVal = argDesc->getReturnValue()) {
254 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
255 assert( RetValLR && "No LR for RetValue of call");
256 RetValLR->clearCallInterference();
259 // If the CALL is an indirect call, find the LR of the function pointer.
260 // That has a call interference because it conflicts with outgoing args.
261 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
262 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
263 assert( AddrValLR && "No LR for indirect addr val of call");
264 AddrValLR->setCallInterference();
272 //----------------------------------------------------------------------------
273 // This method will walk thru code and create interferences in the IG of
274 // each RegClass. Also, this method calculates the spill cost of each
275 // Live Range (it is done in this method to save another pass over the code).
276 //----------------------------------------------------------------------------
277 void PhyRegAlloc::buildInterferenceGraphs()
280 if (DEBUG_RA) cerr << "Creating interference graphs ...\n";
282 unsigned BBLoopDepthCost;
283 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
286 // find the 10^(loop_depth) of this BB
288 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
290 // get the iterator for machine instructions
292 const MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
293 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
295 // iterate over all the machine instructions in BB
297 for ( ; MII != MIVec.end(); ++MII) {
299 const MachineInstr *MInst = *MII;
301 // get the LV set after the instruction
303 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
305 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
308 // set the isCallInterference flag of each live range wich extends
309 // accross this call instruction. This information is used by graph
310 // coloring algo to avoid allocating volatile colors to live ranges
311 // that span across calls (since they have to be saved/restored)
313 setCallInterferences(MInst, &LVSetAI);
317 // iterate over all MI operands to find defs
319 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
320 OpE = MInst->end(); OpI != OpE; ++OpI) {
321 if (OpI.isDef()) // create a new LR iff this operand is a def
322 addInterference(*OpI, &LVSetAI, isCallInst);
324 // Calculate the spill cost of each live range
326 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
327 if (LR) LR->addSpillCost(BBLoopDepthCost);
331 // if there are multiple defs in this instruction e.g. in SETX
333 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
334 addInterf4PseudoInstr(MInst);
337 // Also add interference for any implicit definitions in a machine
338 // instr (currently, only calls have this).
340 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
341 if ( NumOfImpRefs > 0 ) {
342 for (unsigned z=0; z < NumOfImpRefs; z++)
343 if (MInst->implicitRefIsDefined(z) )
344 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
348 } // for all machine instructions in BB
349 } // for all BBs in function
352 // add interferences for function arguments. Since there are no explict
353 // defs in the function for args, we have to add them manually
355 addInterferencesForArgs();
358 cerr << "Interference graphs calculted!\n";
364 //--------------------------------------------------------------------------
365 // Pseudo instructions will be exapnded to multiple instructions by the
366 // assembler. Consequently, all the opernds must get distinct registers.
367 // Therefore, we mark all operands of a pseudo instruction as they interfere
369 //--------------------------------------------------------------------------
370 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
372 bool setInterf = false;
374 // iterate over MI operands to find defs
376 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
377 ItE = MInst->end(); It1 != ItE; ++It1) {
378 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
379 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
381 MachineInstr::const_val_op_iterator It2 = It1;
382 for (++It2; It2 != ItE; ++It2) {
383 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
386 RegClass *RCOfOp1 = LROfOp1->getRegClass();
387 RegClass *RCOfOp2 = LROfOp2->getRegClass();
389 if (RCOfOp1 == RCOfOp2 ){
390 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
394 } // for all other defs in machine instr
395 } // for all operands in an instruction
397 if (!setInterf && MInst->getNumOperands() > 2) {
398 cerr << "\nInterf not set for any operand in pseudo instr:\n";
400 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
406 //----------------------------------------------------------------------------
407 // This method will add interferences for incoming arguments to a function.
408 //----------------------------------------------------------------------------
409 void PhyRegAlloc::addInterferencesForArgs() {
410 // get the InSet of root BB
411 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
413 for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI) {
414 // add interferences between args and LVars at start
415 addInterference(AI, &InSet, false);
418 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
423 //----------------------------------------------------------------------------
424 // This method is called after register allocation is complete to set the
425 // allocated reisters in the machine code. This code will add register numbers
426 // to MachineOperands that contain a Value. Also it calls target specific
427 // methods to produce caller saving instructions. At the end, it adds all
428 // additional instructions produced by the register allocator to the
429 // instruction stream.
430 //----------------------------------------------------------------------------
432 //-----------------------------
433 // Utility functions used below
434 //-----------------------------
436 PrependInstructions(vector<MachineInstr *> &IBef,
437 MachineCodeForBasicBlock& MIVec,
438 MachineCodeForBasicBlock::iterator& MII,
439 const std::string& msg)
443 MachineInstr* OrigMI = *MII;
444 std::vector<MachineInstr *>::iterator AdIt;
445 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
448 if (OrigMI) cerr << "For MInst: " << *OrigMI;
449 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
451 MII = MIVec.insert(MII, *AdIt);
458 AppendInstructions(std::vector<MachineInstr *> &IAft,
459 MachineCodeForBasicBlock& MIVec,
460 MachineCodeForBasicBlock::iterator& MII,
461 const std::string& msg)
465 MachineInstr* OrigMI = *MII;
466 std::vector<MachineInstr *>::iterator AdIt;
467 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
470 if (OrigMI) cerr << "For MInst: " << *OrigMI;
471 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
473 ++MII; // insert before the next instruction
474 MII = MIVec.insert(MII, *AdIt);
480 void PhyRegAlloc::updateMachineCode()
482 MachineCodeForBasicBlock& MIVec = Meth->getEntryNode().getMachineInstrVec();
484 // Insert any instructions needed at method entry
485 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
486 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
487 "At function entry: \n");
488 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
489 "InstrsAfter should be unnecessary since we are just inserting at "
490 "the function entry point here.");
492 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
495 // iterate over all the machine instructions in BB
496 MachineCodeForBasicBlock &MIVec = BBI->getMachineInstrVec();
497 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
498 MII != MIVec.end(); ++MII) {
500 MachineInstr *MInst = *MII;
502 unsigned Opcode = MInst->getOpCode();
504 // do not process Phis
505 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
508 // Now insert speical instructions (if necessary) for call/return
511 if (TM.getInstrInfo().isCall(Opcode) ||
512 TM.getInstrInfo().isReturn(Opcode)) {
514 AddedInstrns &AI = AddedInstrMap[MInst];
516 // Tmp stack poistions are needed by some calls that have spilled args
517 // So reset it before we call each such method
519 mcInfo.popAllTempValues(TM);
521 if (TM.getInstrInfo().isCall(Opcode))
522 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
523 else if (TM.getInstrInfo().isReturn(Opcode))
524 MRI.colorRetValue(MInst, LRI, &AI);
528 /* -- Using above code instead of this
530 // if this machine instr is call, insert caller saving code
532 if ((TM.getInstrInfo()).isCall( MInst->getOpCode()) )
533 MRI.insertCallerSavingCode(MInst, *BBI, *this );
538 // reset the stack offset for temporary variables since we may
539 // need that to spill
540 // mcInfo.popAllTempValues(TM);
541 // TODO ** : do later
543 //for (MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
546 // Now replace set the registers for operands in the machine instruction
548 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
550 MachineOperand& Op = MInst->getOperand(OpNum);
552 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
553 Op.getOperandType() == MachineOperand::MO_CCRegister) {
555 const Value *const Val = Op.getVRegValue();
557 // delete this condition checking later (must assert if Val is null)
560 cerr << "Warning: NULL Value found for operand\n";
563 assert( Val && "Value is NULL");
565 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
569 // nothing to worry if it's a const or a label
572 cerr << "*NO LR for operand : " << Op ;
573 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
574 cerr << " in inst:\t" << *MInst << "\n";
577 // if register is not allocated, mark register as invalid
578 if (Op.getAllocatedRegNum() == -1)
579 Op.setRegForValue( MRI.getInvalidRegNum());
585 unsigned RCID = (LR->getRegClass())->getID();
587 if (LR->hasColor() ) {
588 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
592 // LR did NOT receive a color (register). Now, insert spill code
593 // for spilled opeands in this machine instruction
595 //assert(0 && "LR must be spilled");
596 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
601 } // for each operand
604 // Now add instructions that the register allocator inserts before/after
605 // this machine instructions (done only for calls/rets/incoming args)
606 // We do this here, to ensure that spill for an instruction is inserted
607 // closest as possible to an instruction (see above insertCode4Spill...)
609 // If there are instructions to be added, *before* this machine
610 // instruction, add them now.
612 if (AddedInstrMap.count(MInst)) {
613 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
616 // If there are instructions to be added *after* this machine
617 // instruction, add them now
619 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
621 // if there are delay slots for this instruction, the instructions
622 // added after it must really go after the delayed instruction(s)
623 // So, we move the InstrAfter of the current instruction to the
624 // corresponding delayed instruction
627 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
628 move2DelayedInstr(MInst, *(MII+delay) );
630 if (DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
634 // Here we can add the "instructions after" to the current
635 // instruction since there are no delay slots for this instruction
636 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
641 } // for each machine instruction
647 //----------------------------------------------------------------------------
648 // This method inserts spill code for AN operand whose LR was spilled.
649 // This method may be called several times for a single machine instruction
650 // if it contains many spilled operands. Each time it is called, it finds
651 // a register which is not live at that instruction and also which is not
652 // used by other spilled operands of the same instruction. Then it uses
653 // this register temporarily to accomodate the spilled value.
654 //----------------------------------------------------------------------------
655 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
657 const BasicBlock *BB,
658 const unsigned OpNum) {
660 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
661 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
662 "Arg of a call/ret must be handled elsewhere");
664 MachineOperand& Op = MInst->getOperand(OpNum);
665 bool isDef = MInst->operandIsDefined(OpNum);
666 unsigned RegType = MRI.getRegType( LR );
667 int SpillOff = LR->getSpillOffFromFP();
668 RegClass *RC = LR->getRegClass();
669 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
671 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
673 MachineInstr *MIBef=NULL, *MIAft=NULL;
674 vector<MachineInstr*> AdIMid;
676 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
678 // get the added instructions for this instruciton
679 AddedInstrns &AI = AddedInstrMap[MInst];
682 // for a USE, we have to load the value of LR from stack to a TmpReg
683 // and use the TmpReg as one operand of instruction
685 // actual loading instruction
686 MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType, AdIMid);
687 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(),
688 AdIMid.begin(), AdIMid.end());
691 AI.InstrnsBefore.push_back(MIBef);
694 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
696 } else { // if this is a Def
697 // for a DEF, we have to store the value produced by this instruction
698 // on the stack position allocated for this LR
700 // actual storing instruction
701 MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType, AdIMid);
704 AI.InstrnsBefore.push_back(MIBef);
706 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(),
707 AdIMid.begin(), AdIMid.end());
710 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
715 cerr << "\nFor Inst " << *MInst;
716 cerr << " - SPILLED LR: "; printSet(*LR);
717 cerr << "\n - Added Instructions:";
718 if (MIBef) cerr << *MIBef;
719 for (vector<MachineInstr*>::const_iterator II=AdIMid.begin();
720 II != AdIMid.end(); ++II)
722 if (MIAft) cerr << *MIAft;
725 Op.setRegForValue(TmpRegU); // set the opearnd
730 //----------------------------------------------------------------------------
731 // We can use the following method to get a temporary register to be used
732 // BEFORE any given machine instruction. If there is a register available,
733 // this method will simply return that register and set MIBef = MIAft = NULL.
734 // Otherwise, it will return a register and MIAft and MIBef will contain
735 // two instructions used to free up this returned register.
736 // Returned register number is the UNIFIED register number
737 //----------------------------------------------------------------------------
739 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
741 const MachineInstr *MInst,
742 const ValueSet *LVSetBef,
743 MachineInstr *&MIBef,
744 MachineInstr *&MIAft) {
746 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
750 // we found an unused register, so we can simply use it
751 MIBef = MIAft = NULL;
754 // we couldn't find an unused register. Generate code to free up a reg by
755 // saving it on stack and restoring after the instruction
757 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
759 RegU = getUniRegNotUsedByThisInst(RC, MInst);
761 vector<MachineInstr*> mvec;
763 MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType, mvec);
764 assert(mvec.size() == 1 && "Need to return a vector here too");
765 MIBef = * mvec.begin();
767 MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType, mvec);
768 assert(mvec.size() == 1 && "Need to return a vector here too");
769 MIAft = * mvec.begin();
775 //----------------------------------------------------------------------------
776 // This method is called to get a new unused register that can be used to
777 // accomodate a spilled value.
778 // This method may be called several times for a single machine instruction
779 // if it contains many spilled operands. Each time it is called, it finds
780 // a register which is not live at that instruction and also which is not
781 // used by other spilled operands of the same instruction.
782 // Return register number is relative to the register class. NOT
784 //----------------------------------------------------------------------------
785 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
786 const MachineInstr *MInst,
787 const ValueSet *LVSetBef) {
789 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
791 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
793 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
794 IsColorUsedArr[i] = false;
796 ValueSet::const_iterator LIt = LVSetBef->begin();
798 // for each live var in live variable set after machine inst
799 for ( ; LIt != LVSetBef->end(); ++LIt) {
801 // get the live range corresponding to live var
802 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
804 // LR can be null if it is a const since a const
805 // doesn't have a dominating def - see Assumptions above
806 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
807 IsColorUsedArr[ LRofLV->getColor() ] = true;
810 // It is possible that one operand of this MInst was already spilled
811 // and it received some register temporarily. If that's the case,
812 // it is recorded in machine operand. We must skip such registers.
814 setRelRegsUsedByThisInst(RC, MInst);
816 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
817 if (!IsColorUsedArr[c])
818 return MRI.getUnifiedRegNum(RC->getID(), c);
824 //----------------------------------------------------------------------------
825 // Get any other register in a register class, other than what is used
826 // by operands of a machine instruction. Returns the unified reg number.
827 //----------------------------------------------------------------------------
828 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
829 const MachineInstr *MInst) {
831 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
832 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
835 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
836 IsColorUsedArr[i] = false;
838 setRelRegsUsedByThisInst(RC, MInst);
840 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
841 if (!IsColorUsedArr[c])
842 return MRI.getUnifiedRegNum(RC->getID(), c);
844 assert(0 && "FATAL: No free register could be found in reg class!!");
849 //----------------------------------------------------------------------------
850 // This method modifies the IsColorUsedArr of the register class passed to it.
851 // It sets the bits corresponding to the registers used by this machine
852 // instructions. Both explicit and implicit operands are set.
853 //----------------------------------------------------------------------------
854 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
855 const MachineInstr *MInst ) {
857 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
859 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
861 const MachineOperand& Op = MInst->getOperand(OpNum);
863 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
864 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
866 const Value *const Val = Op.getVRegValue();
869 if (MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
871 if ((Reg=Op.getAllocatedRegNum()) != -1) {
872 IsColorUsedArr[Reg] = true;
875 // it is possilbe that this operand still is not marked with
876 // a register but it has a LR and that received a color
878 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
880 if (LROfVal->hasColor() )
881 IsColorUsedArr[LROfVal->getColor()] = true;
884 } // if reg classes are the same
886 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
887 assert((unsigned)Op.getMachineRegNum() < IsColorUsedArr.size());
888 IsColorUsedArr[Op.getMachineRegNum()] = true;
892 // If there are implicit references, mark them as well
894 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
896 LiveRange *const LRofImpRef =
897 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
899 if (LRofImpRef && LRofImpRef->hasColor())
900 IsColorUsedArr[LRofImpRef->getColor()] = true;
911 //----------------------------------------------------------------------------
912 // If there are delay slots for an instruction, the instructions
913 // added after it must really go after the delayed instruction(s).
914 // So, we move the InstrAfter of that instruction to the
915 // corresponding delayed instruction using the following method.
917 //----------------------------------------------------------------------------
918 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
919 const MachineInstr *DelayedMI) {
921 // "added after" instructions of the original instr
922 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
924 // "added instructions" of the delayed instr
925 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
927 // "added after" instructions of the delayed instr
928 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
930 // go thru all the "added after instructions" of the original instruction
931 // and append them to the "addded after instructions" of the delayed
933 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
935 // empty the "added after instructions" of the original instruction
939 //----------------------------------------------------------------------------
940 // This method prints the code with registers after register allocation is
942 //----------------------------------------------------------------------------
943 void PhyRegAlloc::printMachineCode()
946 cerr << "\n;************** Function " << Meth->getName()
947 << " *****************\n";
949 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
951 cerr << "\n"; printLabel(BBI); cerr << ": ";
953 // get the iterator for machine instructions
954 MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
955 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
957 // iterate over all the machine instructions in BB
958 for ( ; MII != MIVec.end(); ++MII) {
959 MachineInstr *const MInst = *MII;
962 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
964 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
965 MachineOperand& Op = MInst->getOperand(OpNum);
967 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
968 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
969 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
971 const Value *const Val = Op.getVRegValue () ;
972 // ****this code is temporary till NULL Values are fixed
974 cerr << "\t<*NULL*>";
978 // if a label or a constant
979 if (isa<BasicBlock>(Val)) {
980 cerr << "\t"; printLabel( Op.getVRegValue () );
982 // else it must be a register value
983 const int RegNum = Op.getAllocatedRegNum();
985 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
987 cerr << "(" << Val->getName() << ")";
989 cerr << "(" << Val << ")";
994 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
996 if (LROfVal->hasSpillOffset() )
1001 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1002 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1006 cerr << "\t" << Op; // use dump field
1011 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1012 if (NumOfImpRefs > 0) {
1013 cerr << "\tImplicit:";
1015 for (unsigned z=0; z < NumOfImpRefs; z++)
1016 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1019 } // for all machine instructions
1031 //----------------------------------------------------------------------------
1033 //----------------------------------------------------------------------------
1035 void PhyRegAlloc::colorCallRetArgs()
1038 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1039 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1041 for ( ; It != CallRetInstList.end(); ++It ) {
1043 const MachineInstr *const CRMI = *It;
1044 unsigned OpCode = CRMI->getOpCode();
1046 // get the added instructions for this Call/Ret instruciton
1047 AddedInstrns &AI = AddedInstrMap[CRMI];
1049 // Tmp stack positions are needed by some calls that have spilled args
1050 // So reset it before we call each such method
1051 //mcInfo.popAllTempValues(TM);
1054 if (TM.getInstrInfo().isCall(OpCode))
1055 MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1056 else if (TM.getInstrInfo().isReturn(OpCode))
1057 MRI.colorRetValue(CRMI, LRI, &AI);
1059 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1065 //----------------------------------------------------------------------------
1067 //----------------------------------------------------------------------------
1068 void PhyRegAlloc::colorIncomingArgs()
1070 const BasicBlock &FirstBB = Meth->front();
1071 const MachineInstr *FirstMI = FirstBB.getMachineInstrVec().front();
1072 assert(FirstMI && "No machine instruction in entry BB");
1074 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1078 //----------------------------------------------------------------------------
1079 // Used to generate a label for a basic block
1080 //----------------------------------------------------------------------------
1081 void PhyRegAlloc::printLabel(const Value *const Val) {
1083 cerr << Val->getName();
1085 cerr << "Label" << Val;
1089 //----------------------------------------------------------------------------
1090 // This method calls setSugColorUsable method of each live range. This
1091 // will determine whether the suggested color of LR is really usable.
1092 // A suggested color is not usable when the suggested color is volatile
1093 // AND when there are call interferences
1094 //----------------------------------------------------------------------------
1096 void PhyRegAlloc::markUnusableSugColors()
1098 if (DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1100 // hash map iterator
1101 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1102 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1104 for (; HMI != HMIEnd ; ++HMI ) {
1106 LiveRange *L = HMI->second; // get the LiveRange
1108 if (L->hasSuggestedColor()) {
1109 int RCID = L->getRegClass()->getID();
1110 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1111 L->isCallInterference() )
1112 L->setSuggestedColorUsable( false );
1114 L->setSuggestedColorUsable( true );
1116 } // if L->hasSuggestedColor()
1118 } // for all LR's in hash map
1123 //----------------------------------------------------------------------------
1124 // The following method will set the stack offsets of the live ranges that
1125 // are decided to be spillled. This must be called just after coloring the
1126 // LRs using the graph coloring algo. For each live range that is spilled,
1127 // this method allocate a new spill position on the stack.
1128 //----------------------------------------------------------------------------
1130 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1131 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1133 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1134 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1136 for ( ; HMI != HMIEnd ; ++HMI) {
1137 if (HMI->first && HMI->second) {
1138 LiveRange *L = HMI->second; // get the LiveRange
1139 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1140 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1142 } // for all LR's in hash map
1147 //----------------------------------------------------------------------------
1148 // The entry pont to Register Allocation
1149 //----------------------------------------------------------------------------
1151 void PhyRegAlloc::allocateRegisters()
1154 // make sure that we put all register classes into the RegClassList
1155 // before we call constructLiveRanges (now done in the constructor of
1156 // PhyRegAlloc class).
1158 LRI.constructLiveRanges(); // create LR info
1161 LRI.printLiveRanges();
1163 createIGNodeListsAndIGs(); // create IGNode list and IGs
1165 buildInterferenceGraphs(); // build IGs in all reg classes
1169 // print all LRs in all reg classes
1170 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1171 RegClassList[rc]->printIGNodeList();
1173 // print IGs in all register classes
1174 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1175 RegClassList[rc]->printIG();
1179 LRI.coalesceLRs(); // coalesce all live ranges
1183 // print all LRs in all reg classes
1184 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1185 RegClassList[ rc ]->printIGNodeList();
1187 // print IGs in all register classes
1188 for ( unsigned 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
1197 markUnusableSugColors();
1199 // color all register classes using the graph coloring algo
1200 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1201 RegClassList[ rc ]->colorAllRegs();
1203 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1204 // a poistion for such spilled LRs
1206 allocateStackSpace4SpilledLRs();
1208 mcInfo.popAllTempValues(TM); // TODO **Check
1210 // color incoming args - if the correct color was not received
1211 // insert code to copy to the correct register
1213 colorIncomingArgs();
1215 // Now update the machine code with register names and add any
1216 // additional code inserted by the register allocator to the instruction
1219 updateMachineCode();
1222 MachineCodeForMethod::get(Meth).dump();
1223 printMachineCode(); // only for DEBUGGING