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/MachineInstrAnnot.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/MachineFrameInfo.h"
22 #include "llvm/BasicBlock.h"
23 #include "llvm/Function.h"
24 #include "llvm/Type.h"
25 #include "llvm/iOther.h"
26 #include "llvm/CodeGen/RegAllocCommon.h"
27 #include "Support/CommandLine.h"
33 RegAllocDebugLevel_t DEBUG_RA;
34 static cl::Enum<RegAllocDebugLevel_t> DEBUG_RA_c(DEBUG_RA, "dregalloc",
36 "enable register allocation debugging information",
37 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
38 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
39 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
42 //----------------------------------------------------------------------------
43 // RegisterAllocation pass front end...
44 //----------------------------------------------------------------------------
46 class RegisterAllocator : public FunctionPass {
47 TargetMachine &Target;
49 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
51 const char *getPassName() const { return "Register Allocation"; }
53 bool runOnFunction(Function &F) {
55 cerr << "\n********* Function "<< F.getName() << " ***********\n";
57 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
58 &getAnalysis<LoopInfo>());
59 PRA.allocateRegisters();
61 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66 AU.addRequired(LoopInfo::ID);
67 AU.addRequired(FunctionLiveVarInfo::ID);
72 Pass *getRegisterAllocator(TargetMachine &T) {
73 return new RegisterAllocator(T);
76 //----------------------------------------------------------------------------
77 // Constructor: Init local composite objects and create register classes.
78 //----------------------------------------------------------------------------
79 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
80 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
82 mcInfo(MachineCodeForMethod::get(F)),
83 LVI(Lvi), LRI(F, tm, RegClassList),
85 NumOfRegClasses(MRI.getNumOfRegClasses()),
88 // create each RegisterClass and put in RegClassList
90 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
91 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
96 //----------------------------------------------------------------------------
97 // Destructor: Deletes register classes
98 //----------------------------------------------------------------------------
99 PhyRegAlloc::~PhyRegAlloc() {
100 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
101 delete RegClassList[rc];
103 AddedInstrMap.clear();
106 //----------------------------------------------------------------------------
107 // This method initally creates interference graphs (one in each reg class)
108 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
109 //----------------------------------------------------------------------------
110 void PhyRegAlloc::createIGNodeListsAndIGs() {
111 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
114 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
117 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
119 for (; HMI != HMIEnd ; ++HMI ) {
121 LiveRange *L = HMI->second; // get the LiveRange
124 cerr << "\n*?!?Warning: Null liver range found for: "
125 << RAV(HMI->first) << "\n";
129 // if the Value * is not null, and LR
130 // is not yet written to the IGNodeList
131 if (!(L->getUserIGNode()) ) {
132 RegClass *const RC = // RegClass of first value in the LR
133 RegClassList[ L->getRegClass()->getID() ];
135 RC->addLRToIG(L); // add this LR to an IG
141 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
142 RegClassList[rc]->createInterferenceGraph();
145 cerr << "LRLists Created!\n";
151 //----------------------------------------------------------------------------
152 // This method will add all interferences at for a given instruction.
153 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
154 // class as that of live var. The live var passed to this function is the
155 // LVset AFTER the instruction
156 //----------------------------------------------------------------------------
157 void PhyRegAlloc::addInterference(const Value *Def,
158 const ValueSet *LVSet,
161 ValueSet::const_iterator LIt = LVSet->begin();
163 // get the live range of instruction
165 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
167 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
168 assert( IGNodeOfDef );
170 RegClass *const RCOfDef = LROfDef->getRegClass();
172 // for each live var in live variable set
174 for ( ; LIt != LVSet->end(); ++LIt) {
177 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
179 // get the live range corresponding to live var
181 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
183 // LROfVar can be null if it is a const since a const
184 // doesn't have a dominating def - see Assumptions above
187 if (LROfDef == LROfVar) // do not set interf for same LR
190 // if 2 reg classes are the same set interference
192 if (RCOfDef == LROfVar->getRegClass()) {
193 RCOfDef->setInterference( LROfDef, LROfVar);
194 } else if (DEBUG_RA > 1) {
195 // we will not have LRs for values not explicitly allocated in the
196 // instruction stream (e.g., constants)
197 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
205 //----------------------------------------------------------------------------
206 // For a call instruction, this method sets the CallInterference flag in
207 // the LR of each variable live int the Live Variable Set live after the
208 // call instruction (except the return value of the call instruction - since
209 // the return value does not interfere with that call itself).
210 //----------------------------------------------------------------------------
212 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
213 const ValueSet *LVSetAft) {
216 cerr << "\n For call inst: " << *MInst;
218 ValueSet::const_iterator LIt = LVSetAft->begin();
220 // for each live var in live variable set after machine inst
222 for ( ; LIt != LVSetAft->end(); ++LIt) {
224 // get the live range corresponding to live var
226 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
228 if (LR && DEBUG_RA) {
229 cerr << "\n\tLR Aft Call: ";
233 // LR can be null if it is a const since a const
234 // doesn't have a dominating def - see Assumptions above
237 LR->setCallInterference();
239 cerr << "\n ++Added call interf for LR: " ;
246 // Now find the LR of the return value of the call
247 // We do this because, we look at the LV set *after* the instruction
248 // to determine, which LRs must be saved across calls. The return value
249 // of the call is live in this set - but it does not interfere with call
250 // (i.e., we can allocate a volatile register to the return value)
252 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
254 if (const Value *RetVal = argDesc->getReturnValue()) {
255 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
256 assert( RetValLR && "No LR for RetValue of call");
257 RetValLR->clearCallInterference();
260 // If the CALL is an indirect call, find the LR of the function pointer.
261 // That has a call interference because it conflicts with outgoing args.
262 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
263 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
264 assert( AddrValLR && "No LR for indirect addr val of call");
265 AddrValLR->setCallInterference();
273 //----------------------------------------------------------------------------
274 // This method will walk thru code and create interferences in the IG of
275 // each RegClass. Also, this method calculates the spill cost of each
276 // Live Range (it is done in this method to save another pass over the code).
277 //----------------------------------------------------------------------------
278 void PhyRegAlloc::buildInterferenceGraphs()
281 if (DEBUG_RA) cerr << "Creating interference graphs ...\n";
283 unsigned BBLoopDepthCost;
284 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
287 // find the 10^(loop_depth) of this BB
289 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
291 // get the iterator for machine instructions
293 const MachineCodeForBasicBlock& MIVec = BBI->getMachineInstrVec();
294 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
296 // iterate over all the machine instructions in BB
298 for ( ; MII != MIVec.end(); ++MII) {
300 const MachineInstr *MInst = *MII;
302 // get the LV set after the instruction
304 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
306 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
309 // set the isCallInterference flag of each live range wich extends
310 // accross this call instruction. This information is used by graph
311 // coloring algo to avoid allocating volatile colors to live ranges
312 // that span across calls (since they have to be saved/restored)
314 setCallInterferences(MInst, &LVSetAI);
318 // iterate over all MI operands to find defs
320 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
321 OpE = MInst->end(); OpI != OpE; ++OpI) {
322 if (OpI.isDef()) // create a new LR iff this operand is a def
323 addInterference(*OpI, &LVSetAI, isCallInst);
325 // Calculate the spill cost of each live range
327 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
328 if (LR) LR->addSpillCost(BBLoopDepthCost);
332 // if there are multiple defs in this instruction e.g. in SETX
334 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
335 addInterf4PseudoInstr(MInst);
338 // Also add interference for any implicit definitions in a machine
339 // instr (currently, only calls have this).
341 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
342 if ( NumOfImpRefs > 0 ) {
343 for (unsigned z=0; z < NumOfImpRefs; z++)
344 if (MInst->implicitRefIsDefined(z) )
345 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
349 } // for all machine instructions in BB
350 } // for all BBs in function
353 // add interferences for function arguments. Since there are no explict
354 // defs in the function for args, we have to add them manually
356 addInterferencesForArgs();
359 cerr << "Interference graphs calculted!\n";
365 //--------------------------------------------------------------------------
366 // Pseudo instructions will be exapnded to multiple instructions by the
367 // assembler. Consequently, all the opernds must get distinct registers.
368 // Therefore, we mark all operands of a pseudo instruction as they interfere
370 //--------------------------------------------------------------------------
371 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
373 bool setInterf = false;
375 // iterate over MI operands to find defs
377 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
378 ItE = MInst->end(); It1 != ItE; ++It1) {
379 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
380 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
382 MachineInstr::const_val_op_iterator It2 = It1;
383 for (++It2; It2 != ItE; ++It2) {
384 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
387 RegClass *RCOfOp1 = LROfOp1->getRegClass();
388 RegClass *RCOfOp2 = LROfOp2->getRegClass();
390 if (RCOfOp1 == RCOfOp2 ){
391 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
395 } // for all other defs in machine instr
396 } // for all operands in an instruction
398 if (!setInterf && MInst->getNumOperands() > 2) {
399 cerr << "\nInterf not set for any operand in pseudo instr:\n";
401 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
407 //----------------------------------------------------------------------------
408 // This method will add interferences for incoming arguments to a function.
409 //----------------------------------------------------------------------------
410 void PhyRegAlloc::addInterferencesForArgs() {
411 // get the InSet of root BB
412 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
414 for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI) {
415 // add interferences between args and LVars at start
416 addInterference(AI, &InSet, false);
419 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
424 //----------------------------------------------------------------------------
425 // This method is called after register allocation is complete to set the
426 // allocated reisters in the machine code. This code will add register numbers
427 // to MachineOperands that contain a Value. Also it calls target specific
428 // methods to produce caller saving instructions. At the end, it adds all
429 // additional instructions produced by the register allocator to the
430 // instruction stream.
431 //----------------------------------------------------------------------------
433 //-----------------------------
434 // Utility functions used below
435 //-----------------------------
437 PrependInstructions(vector<MachineInstr *> &IBef,
438 MachineCodeForBasicBlock& MIVec,
439 MachineCodeForBasicBlock::iterator& MII,
440 const std::string& msg)
444 MachineInstr* OrigMI = *MII;
445 std::vector<MachineInstr *>::iterator AdIt;
446 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
449 if (OrigMI) cerr << "For MInst: " << *OrigMI;
450 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
452 MII = MIVec.insert(MII, *AdIt);
459 AppendInstructions(std::vector<MachineInstr *> &IAft,
460 MachineCodeForBasicBlock& MIVec,
461 MachineCodeForBasicBlock::iterator& MII,
462 const std::string& msg)
466 MachineInstr* OrigMI = *MII;
467 std::vector<MachineInstr *>::iterator AdIt;
468 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
471 if (OrigMI) cerr << "For MInst: " << *OrigMI;
472 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
474 ++MII; // insert before the next instruction
475 MII = MIVec.insert(MII, *AdIt);
481 void PhyRegAlloc::updateMachineCode()
483 MachineCodeForBasicBlock& MIVec = Meth->getEntryNode().getMachineInstrVec();
485 // Insert any instructions needed at method entry
486 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
487 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
488 "At function entry: \n");
489 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
490 "InstrsAfter should be unnecessary since we are just inserting at "
491 "the function entry point here.");
493 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
496 // iterate over all the machine instructions in BB
497 MachineCodeForBasicBlock &MIVec = BBI->getMachineInstrVec();
498 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
499 MII != MIVec.end(); ++MII) {
501 MachineInstr *MInst = *MII;
503 unsigned Opcode = MInst->getOpCode();
505 // do not process Phis
506 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
509 // Now insert speical instructions (if necessary) for call/return
512 if (TM.getInstrInfo().isCall(Opcode) ||
513 TM.getInstrInfo().isReturn(Opcode)) {
515 AddedInstrns &AI = AddedInstrMap[MInst];
517 // Tmp stack poistions are needed by some calls that have spilled args
518 // So reset it before we call each such method
520 mcInfo.popAllTempValues(TM);
522 if (TM.getInstrInfo().isCall(Opcode))
523 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
524 else if (TM.getInstrInfo().isReturn(Opcode))
525 MRI.colorRetValue(MInst, LRI, &AI);
529 /* -- Using above code instead of this
531 // if this machine instr is call, insert caller saving code
533 if ((TM.getInstrInfo()).isCall( MInst->getOpCode()) )
534 MRI.insertCallerSavingCode(MInst, *BBI, *this );
539 // reset the stack offset for temporary variables since we may
540 // need that to spill
541 // mcInfo.popAllTempValues(TM);
542 // TODO ** : do later
544 //for (MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
547 // Now replace set the registers for operands in the machine instruction
549 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
551 MachineOperand& Op = MInst->getOperand(OpNum);
553 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
554 Op.getOperandType() == MachineOperand::MO_CCRegister) {
556 const Value *const Val = Op.getVRegValue();
558 // delete this condition checking later (must assert if Val is null)
561 cerr << "Warning: NULL Value found for operand\n";
564 assert( Val && "Value is NULL");
566 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
570 // nothing to worry if it's a const or a label
573 cerr << "*NO LR for operand : " << Op ;
574 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
575 cerr << " in inst:\t" << *MInst << "\n";
578 // if register is not allocated, mark register as invalid
579 if (Op.getAllocatedRegNum() == -1)
580 Op.setRegForValue( MRI.getInvalidRegNum());
586 unsigned RCID = (LR->getRegClass())->getID();
588 if (LR->hasColor() ) {
589 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
593 // LR did NOT receive a color (register). Now, insert spill code
594 // for spilled opeands in this machine instruction
596 //assert(0 && "LR must be spilled");
597 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
602 } // for each operand
605 // Now add instructions that the register allocator inserts before/after
606 // this machine instructions (done only for calls/rets/incoming args)
607 // We do this here, to ensure that spill for an instruction is inserted
608 // closest as possible to an instruction (see above insertCode4Spill...)
610 // If there are instructions to be added, *before* this machine
611 // instruction, add them now.
613 if (AddedInstrMap.count(MInst)) {
614 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
617 // If there are instructions to be added *after* this machine
618 // instruction, add them now
620 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
622 // if there are delay slots for this instruction, the instructions
623 // added after it must really go after the delayed instruction(s)
624 // So, we move the InstrAfter of the current instruction to the
625 // corresponding delayed instruction
628 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
629 move2DelayedInstr(MInst, *(MII+delay) );
631 if (DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
635 // Here we can add the "instructions after" to the current
636 // instruction since there are no delay slots for this instruction
637 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
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, *MIAft=NULL;
675 vector<MachineInstr*> AdIMid;
677 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
679 // get the added instructions for this instruciton
680 AddedInstrns &AI = AddedInstrMap[MInst];
683 // for a USE, we have to load the value of LR from stack to a TmpReg
684 // and use the TmpReg as one operand of instruction
686 // actual loading instruction
687 MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType, AdIMid);
688 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(),
689 AdIMid.begin(), AdIMid.end());
692 AI.InstrnsBefore.push_back(MIBef);
695 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
697 } else { // if this is a Def
698 // for a DEF, we have to store the value produced by this instruction
699 // on the stack position allocated for this LR
701 // actual storing instruction
702 MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType, AdIMid);
705 AI.InstrnsBefore.push_back(MIBef);
707 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(),
708 AdIMid.begin(), AdIMid.end());
711 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft);
716 cerr << "\nFor Inst " << *MInst;
717 cerr << " - SPILLED LR: "; printSet(*LR);
718 cerr << "\n - Added Instructions:";
719 if (MIBef) cerr << *MIBef;
720 for (vector<MachineInstr*>::const_iterator II=AdIMid.begin();
721 II != AdIMid.end(); ++II)
723 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);
762 vector<MachineInstr*> mvec;
764 MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType, mvec);
765 assert(mvec.size() == 1 && "Need to return a vector here too");
766 MIBef = * mvec.begin();
768 MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType, mvec);
769 assert(mvec.size() == 1 && "Need to return a vector here too");
770 MIAft = * mvec.begin();
776 //----------------------------------------------------------------------------
777 // This method is called to get a new unused register that can be used to
778 // accomodate a spilled value.
779 // This method may be called several times for a single machine instruction
780 // if it contains many spilled operands. Each time it is called, it finds
781 // a register which is not live at that instruction and also which is not
782 // used by other spilled operands of the same instruction.
783 // Return register number is relative to the register class. NOT
785 //----------------------------------------------------------------------------
786 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
787 const MachineInstr *MInst,
788 const ValueSet *LVSetBef) {
790 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
792 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
794 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
795 IsColorUsedArr[i] = false;
797 ValueSet::const_iterator LIt = LVSetBef->begin();
799 // for each live var in live variable set after machine inst
800 for ( ; LIt != LVSetBef->end(); ++LIt) {
802 // get the live range corresponding to live var
803 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
805 // LR can be null if it is a const since a const
806 // doesn't have a dominating def - see Assumptions above
807 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
808 IsColorUsedArr[ LRofLV->getColor() ] = true;
811 // It is possible that one operand of this MInst was already spilled
812 // and it received some register temporarily. If that's the case,
813 // it is recorded in machine operand. We must skip such registers.
815 setRelRegsUsedByThisInst(RC, MInst);
817 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
818 if (!IsColorUsedArr[c])
819 return MRI.getUnifiedRegNum(RC->getID(), c);
825 //----------------------------------------------------------------------------
826 // Get any other register in a register class, other than what is used
827 // by operands of a machine instruction. Returns the unified reg number.
828 //----------------------------------------------------------------------------
829 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
830 const MachineInstr *MInst) {
832 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
833 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
836 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
837 IsColorUsedArr[i] = false;
839 setRelRegsUsedByThisInst(RC, MInst);
841 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
842 if (!IsColorUsedArr[c])
843 return MRI.getUnifiedRegNum(RC->getID(), c);
845 assert(0 && "FATAL: No free register could be found in reg class!!");
850 //----------------------------------------------------------------------------
851 // This method modifies the IsColorUsedArr of the register class passed to it.
852 // It sets the bits corresponding to the registers used by this machine
853 // instructions. Both explicit and implicit operands are set.
854 //----------------------------------------------------------------------------
855 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
856 const MachineInstr *MInst ) {
858 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
860 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
862 const MachineOperand& Op = MInst->getOperand(OpNum);
864 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
865 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
867 const Value *const Val = Op.getVRegValue();
870 if (MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
872 if ((Reg=Op.getAllocatedRegNum()) != -1) {
873 IsColorUsedArr[Reg] = true;
876 // it is possilbe that this operand still is not marked with
877 // a register but it has a LR and that received a color
879 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
881 if (LROfVal->hasColor() )
882 IsColorUsedArr[LROfVal->getColor()] = true;
885 } // if reg classes are the same
887 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
888 assert((unsigned)Op.getMachineRegNum() < IsColorUsedArr.size());
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::vector<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::vector<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 &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 rc=0; rc < NumOfRegClasses ; rc++)
1172 RegClassList[rc]->printIGNodeList();
1174 // print IGs in all register classes
1175 for ( unsigned 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 rc=0; rc < NumOfRegClasses ; rc++)
1186 RegClassList[ rc ]->printIGNodeList();
1188 // print IGs in all register classes
1189 for ( unsigned 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 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