1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "llvm/CodeGen/RegAllocCommon.h"
9 #include "llvm/CodeGen/PhyRegAlloc.h"
10 #include "llvm/CodeGen/MachineInstr.h"
11 #include "llvm/CodeGen/MachineInstrAnnot.h"
12 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
13 #include "llvm/CodeGen/MachineCodeForMethod.h"
14 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/MachineFrameInfo.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/iOther.h"
21 #include "Support/STLExtras.h"
26 RegAllocDebugLevel_t DEBUG_RA;
28 static cl::opt<RegAllocDebugLevel_t, true>
29 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
30 cl::desc("enable register allocation debugging information"),
32 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
33 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
34 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
35 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
36 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
37 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
40 //----------------------------------------------------------------------------
41 // RegisterAllocation pass front end...
42 //----------------------------------------------------------------------------
44 class RegisterAllocator : public FunctionPass {
45 TargetMachine &Target;
47 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
49 const char *getPassName() const { return "Register Allocation"; }
51 bool runOnFunction(Function &F) {
53 cerr << "\n********* Function "<< F.getName() << " ***********\n";
55 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
56 &getAnalysis<LoopInfo>());
57 PRA.allocateRegisters();
59 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<LoopInfo>();
65 AU.addRequired<FunctionLiveVarInfo>();
70 Pass *getRegisterAllocator(TargetMachine &T) {
71 return new RegisterAllocator(T);
74 //----------------------------------------------------------------------------
75 // Constructor: Init local composite objects and create register classes.
76 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
78 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
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 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 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 >= RA_DEBUG_LiveRanges) 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 LIVE RANGE FOUND FOR: "
123 << RAV(HMI->first) << "****\n";
127 // if the Value * is not null, and LR is not yet written to the IGNodeList
128 if (!(L->getUserIGNode()) ) {
129 RegClass *const RC = // RegClass of first value in the LR
130 RegClassList[ L->getRegClass()->getID() ];
131 RC->addLRToIG(L); // add this LR to an IG
137 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
138 RegClassList[rc]->createInterferenceGraph();
140 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
144 //----------------------------------------------------------------------------
145 // This method will add all interferences at for a given instruction.
146 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
147 // class as that of live var. The live var passed to this function is the
148 // LVset AFTER the instruction
149 //----------------------------------------------------------------------------
151 void PhyRegAlloc::addInterference(const Value *Def,
152 const ValueSet *LVSet,
155 ValueSet::const_iterator LIt = LVSet->begin();
157 // get the live range of instruction
159 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
161 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
162 assert( IGNodeOfDef );
164 RegClass *const RCOfDef = LROfDef->getRegClass();
166 // for each live var in live variable set
168 for ( ; LIt != LVSet->end(); ++LIt) {
170 if (DEBUG_RA >= RA_DEBUG_Verbose)
171 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
173 // get the live range corresponding to live var
175 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
177 // LROfVar can be null if it is a const since a const
178 // doesn't have a dominating def - see Assumptions above
181 if (LROfDef != LROfVar) // do not set interf for same LR
182 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
183 RCOfDef->setInterference( LROfDef, LROfVar);
189 //----------------------------------------------------------------------------
190 // For a call instruction, this method sets the CallInterference flag in
191 // the LR of each variable live int the Live Variable Set live after the
192 // call instruction (except the return value of the call instruction - since
193 // the return value does not interfere with that call itself).
194 //----------------------------------------------------------------------------
196 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
197 const ValueSet *LVSetAft) {
199 if (DEBUG_RA >= RA_DEBUG_Interference)
200 cerr << "\n For call inst: " << *MInst;
202 ValueSet::const_iterator LIt = LVSetAft->begin();
204 // for each live var in live variable set after machine inst
206 for ( ; LIt != LVSetAft->end(); ++LIt) {
208 // get the live range corresponding to live var
210 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
212 // LR can be null if it is a const since a const
213 // doesn't have a dominating def - see Assumptions above
216 if (DEBUG_RA >= RA_DEBUG_Interference) {
217 cerr << "\n\tLR after Call: ";
220 LR->setCallInterference();
221 if (DEBUG_RA >= RA_DEBUG_Interference) {
222 cerr << "\n ++After adding call interference for LR: " ;
229 // Now find the LR of the return value of the call
230 // We do this because, we look at the LV set *after* the instruction
231 // to determine, which LRs must be saved across calls. The return value
232 // of the call is live in this set - but it does not interfere with call
233 // (i.e., we can allocate a volatile register to the return value)
235 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
237 if (const Value *RetVal = argDesc->getReturnValue()) {
238 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
239 assert( RetValLR && "No LR for RetValue of call");
240 RetValLR->clearCallInterference();
243 // If the CALL is an indirect call, find the LR of the function pointer.
244 // That has a call interference because it conflicts with outgoing args.
245 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
246 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
247 assert( AddrValLR && "No LR for indirect addr val of call");
248 AddrValLR->setCallInterference();
256 //----------------------------------------------------------------------------
257 // This method will walk thru code and create interferences in the IG of
258 // each RegClass. Also, this method calculates the spill cost of each
259 // Live Range (it is done in this method to save another pass over the code).
260 //----------------------------------------------------------------------------
261 void PhyRegAlloc::buildInterferenceGraphs()
264 if (DEBUG_RA >= RA_DEBUG_Interference)
265 cerr << "Creating interference graphs ...\n";
267 unsigned BBLoopDepthCost;
268 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
271 // find the 10^(loop_depth) of this BB
273 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
275 // get the iterator for machine instructions
277 const MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
278 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
280 // iterate over all the machine instructions in BB
282 for ( ; MII != MIVec.end(); ++MII) {
284 const MachineInstr *MInst = *MII;
286 // get the LV set after the instruction
288 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
290 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
293 // set the isCallInterference flag of each live range wich extends
294 // accross this call instruction. This information is used by graph
295 // coloring algo to avoid allocating volatile colors to live ranges
296 // that span across calls (since they have to be saved/restored)
298 setCallInterferences(MInst, &LVSetAI);
302 // iterate over all MI operands to find defs
304 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
305 OpE = MInst->end(); OpI != OpE; ++OpI) {
306 if (OpI.isDef()) // create a new LR iff this operand is a def
307 addInterference(*OpI, &LVSetAI, isCallInst);
309 // Calculate the spill cost of each live range
311 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
312 if (LR) LR->addSpillCost(BBLoopDepthCost);
316 // if there are multiple defs in this instruction e.g. in SETX
318 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
319 addInterf4PseudoInstr(MInst);
322 // Also add interference for any implicit definitions in a machine
323 // instr (currently, only calls have this).
325 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
326 if ( NumOfImpRefs > 0 ) {
327 for (unsigned z=0; z < NumOfImpRefs; z++)
328 if (MInst->implicitRefIsDefined(z) )
329 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
333 } // for all machine instructions in BB
334 } // for all BBs in function
337 // add interferences for function arguments. Since there are no explict
338 // defs in the function for args, we have to add them manually
340 addInterferencesForArgs();
342 if (DEBUG_RA >= RA_DEBUG_Interference)
343 cerr << "Interference graphs calculated!\n";
348 //--------------------------------------------------------------------------
349 // Pseudo instructions will be exapnded to multiple instructions by the
350 // assembler. Consequently, all the opernds must get distinct registers.
351 // Therefore, we mark all operands of a pseudo instruction as they interfere
353 //--------------------------------------------------------------------------
354 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
356 bool setInterf = false;
358 // iterate over MI operands to find defs
360 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
361 ItE = MInst->end(); It1 != ItE; ++It1) {
362 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
363 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
365 MachineInstr::const_val_op_iterator It2 = It1;
366 for (++It2; It2 != ItE; ++It2) {
367 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
370 RegClass *RCOfOp1 = LROfOp1->getRegClass();
371 RegClass *RCOfOp2 = LROfOp2->getRegClass();
373 if (RCOfOp1 == RCOfOp2 ){
374 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
378 } // for all other defs in machine instr
379 } // for all operands in an instruction
381 if (!setInterf && MInst->getNumOperands() > 2) {
382 cerr << "\nInterf not set for any operand in pseudo instr:\n";
384 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
390 //----------------------------------------------------------------------------
391 // This method will add interferences for incoming arguments to a function.
392 //----------------------------------------------------------------------------
394 void PhyRegAlloc::addInterferencesForArgs() {
395 // get the InSet of root BB
396 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
398 for (Function::const_aiterator AI=Meth->abegin(); AI != Meth->aend(); ++AI) {
399 // add interferences between args and LVars at start
400 addInterference(AI, &InSet, false);
402 if (DEBUG_RA >= RA_DEBUG_Interference)
403 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
408 //----------------------------------------------------------------------------
409 // This method is called after register allocation is complete to set the
410 // allocated reisters in the machine code. This code will add register numbers
411 // to MachineOperands that contain a Value. Also it calls target specific
412 // methods to produce caller saving instructions. At the end, it adds all
413 // additional instructions produced by the register allocator to the
414 // instruction stream.
415 //----------------------------------------------------------------------------
417 //-----------------------------
418 // Utility functions used below
419 //-----------------------------
421 PrependInstructions(vector<MachineInstr *> &IBef,
422 MachineCodeForBasicBlock& MIVec,
423 MachineCodeForBasicBlock::iterator& MII,
424 const std::string& msg)
428 MachineInstr* OrigMI = *MII;
429 std::vector<MachineInstr *>::iterator AdIt;
430 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
433 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
434 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
436 MII = MIVec.insert(MII, *AdIt);
443 AppendInstructions(std::vector<MachineInstr *> &IAft,
444 MachineCodeForBasicBlock& MIVec,
445 MachineCodeForBasicBlock::iterator& MII,
446 const std::string& msg)
450 MachineInstr* OrigMI = *MII;
451 std::vector<MachineInstr *>::iterator AdIt;
452 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
455 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
456 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
458 ++MII; // insert before the next instruction
459 MII = MIVec.insert(MII, *AdIt);
465 void PhyRegAlloc::updateMachineCode()
467 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(&Meth->getEntryNode());
469 // Insert any instructions needed at method entry
470 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
471 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
472 "At function entry: \n");
473 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
474 "InstrsAfter should be unnecessary since we are just inserting at "
475 "the function entry point here.");
477 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
480 // iterate over all the machine instructions in BB
481 MachineCodeForBasicBlock &MIVec = MachineCodeForBasicBlock::get(BBI);
482 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
483 MII != MIVec.end(); ++MII) {
485 MachineInstr *MInst = *MII;
487 unsigned Opcode = MInst->getOpCode();
489 // do not process Phis
490 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
493 // Reset tmp stack positions so they can be reused for each machine instr.
494 mcInfo.popAllTempValues(TM);
496 // Now insert speical instructions (if necessary) for call/return
499 if (TM.getInstrInfo().isCall(Opcode) ||
500 TM.getInstrInfo().isReturn(Opcode)) {
502 AddedInstrns &AI = AddedInstrMap[MInst];
504 if (TM.getInstrInfo().isCall(Opcode))
505 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
506 else if (TM.getInstrInfo().isReturn(Opcode))
507 MRI.colorRetValue(MInst, LRI, &AI);
510 // Set the registers for operands in the machine instruction
511 // if a register was successfully allocated. If not, insert
512 // code to spill the register value.
514 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
516 MachineOperand& Op = MInst->getOperand(OpNum);
517 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
518 Op.getOperandType() == MachineOperand::MO_CCRegister)
520 const Value *const Val = Op.getVRegValue();
522 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
523 if (!LR) // consts or labels will have no live range
525 // if register is not allocated, mark register as invalid
526 if (Op.getAllocatedRegNum() == -1)
527 MInst->SetRegForOperand(OpNum, MRI.getInvalidRegNum());
532 MInst->SetRegForOperand(OpNum,
533 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
536 // LR did NOT receive a color (register). Insert spill code.
537 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
539 } // for each operand
542 // Now add instructions that the register allocator inserts before/after
543 // this machine instructions (done only for calls/rets/incoming args)
544 // We do this here, to ensure that spill for an instruction is inserted
545 // closest as possible to an instruction (see above insertCode4Spill...)
547 // If there are instructions to be added, *before* this machine
548 // instruction, add them now.
550 if (AddedInstrMap.count(MInst)) {
551 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
554 // If there are instructions to be added *after* this machine
555 // instruction, add them now
557 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
559 // if there are delay slots for this instruction, the instructions
560 // added after it must really go after the delayed instruction(s)
561 // So, we move the InstrAfter of the current instruction to the
562 // corresponding delayed instruction
565 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
566 move2DelayedInstr(MInst, *(MII+delay) );
569 // Here we can add the "instructions after" to the current
570 // instruction since there are no delay slots for this instruction
571 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
575 } // for each machine instruction
581 //----------------------------------------------------------------------------
582 // This method inserts spill code for AN operand whose LR was spilled.
583 // This method may be called several times for a single machine instruction
584 // if it contains many spilled operands. Each time it is called, it finds
585 // a register which is not live at that instruction and also which is not
586 // used by other spilled operands of the same instruction. Then it uses
587 // this register temporarily to accomodate the spilled value.
588 //----------------------------------------------------------------------------
589 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
591 const BasicBlock *BB,
592 const unsigned OpNum) {
594 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
595 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
596 "Arg of a call/ret must be handled elsewhere");
598 MachineOperand& Op = MInst->getOperand(OpNum);
599 bool isDef = MInst->operandIsDefined(OpNum);
600 bool isDefAndUse = MInst->operandIsDefinedAndUsed(OpNum);
601 unsigned RegType = MRI.getRegType( LR );
602 int SpillOff = LR->getSpillOffFromFP();
603 RegClass *RC = LR->getRegClass();
604 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
606 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
608 vector<MachineInstr*> MIBef, MIAft;
609 vector<MachineInstr*> AdIMid;
611 // Choose a register to hold the spilled value. This may insert code
612 // before and after MInst to free up the value. If so, this code should
613 // be first and last in the spill sequence before/after MInst.
614 int TmpRegU = getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef, MIAft);
616 // Set the operand first so that it this register does not get used
617 // as a scratch register for later calls to getUsableUniRegAtMI below
618 MInst->SetRegForOperand(OpNum, TmpRegU);
620 // get the added instructions for this instruction
621 AddedInstrns &AI = AddedInstrMap[MInst];
623 // We may need a scratch register to copy the spilled value to/from memory.
624 // This may itself have to insert code to free up a scratch register.
625 // Any such code should go before (after) the spill code for a load (store).
626 int scratchRegType = -1;
628 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
630 scratchReg = this->getUsableUniRegAtMI(scratchRegType, &LVSetBef,
631 MInst, MIBef, MIAft);
632 assert(scratchReg != MRI.getInvalidRegNum());
633 MInst->getRegsUsed().insert(scratchReg);
636 if (!isDef || isDefAndUse) {
637 // for a USE, we have to load the value of LR from stack to a TmpReg
638 // and use the TmpReg as one operand of instruction
640 // actual loading instruction(s)
641 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU, RegType,
644 // the actual load should be after the instructions to free up TmpRegU
645 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
649 if (isDef) { // if this is a Def
650 // for a DEF, we have to store the value produced by this instruction
651 // on the stack position allocated for this LR
653 // actual storing instruction(s)
654 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff, RegType,
657 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
660 // Finally, insert the entire spill code sequences before/after MInst
661 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
662 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
665 cerr << "\nFor Inst:\n " << *MInst;
666 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
667 cerr << "; added Instructions:";
668 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
669 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
674 //----------------------------------------------------------------------------
675 // We can use the following method to get a temporary register to be used
676 // BEFORE any given machine instruction. If there is a register available,
677 // this method will simply return that register and set MIBef = MIAft = NULL.
678 // Otherwise, it will return a register and MIAft and MIBef will contain
679 // two instructions used to free up this returned register.
680 // Returned register number is the UNIFIED register number
681 //----------------------------------------------------------------------------
683 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
684 const ValueSet *LVSetBef,
686 std::vector<MachineInstr*>& MIBef,
687 std::vector<MachineInstr*>& MIAft) {
689 RegClass* RC = this->getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
691 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
694 // we couldn't find an unused register. Generate code to free up a reg by
695 // saving it on stack and restoring after the instruction
697 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
699 RegU = getUniRegNotUsedByThisInst(RC, MInst);
701 // Check if we need a scratch register to copy this register to memory.
702 int scratchRegType = -1;
703 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
705 int scratchReg = this->getUsableUniRegAtMI(scratchRegType, LVSetBef,
706 MInst, MIBef, MIAft);
707 assert(scratchReg != MRI.getInvalidRegNum());
709 // We may as well hold the value in the scratch register instead
710 // of copying it to memory and back. But we have to mark the
711 // register as used by this instruction, so it does not get used
712 // as a scratch reg. by another operand or anyone else.
713 MInst->getRegsUsed().insert(scratchReg);
714 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
715 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
718 { // the register can be copied directly to/from memory so do it.
719 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
720 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
727 //----------------------------------------------------------------------------
728 // This method is called to get a new unused register that can be used to
729 // accomodate a spilled value.
730 // This method may be called several times for a single machine instruction
731 // if it contains many spilled operands. Each time it is called, it finds
732 // a register which is not live at that instruction and also which is not
733 // used by other spilled operands of the same instruction.
734 // Return register number is relative to the register class. NOT
736 //----------------------------------------------------------------------------
737 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
738 const MachineInstr *MInst,
739 const ValueSet *LVSetBef) {
741 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
743 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
745 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
746 IsColorUsedArr[i] = false;
748 ValueSet::const_iterator LIt = LVSetBef->begin();
750 // for each live var in live variable set after machine inst
751 for ( ; LIt != LVSetBef->end(); ++LIt) {
753 // get the live range corresponding to live var
754 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
756 // LR can be null if it is a const since a const
757 // doesn't have a dominating def - see Assumptions above
758 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
759 IsColorUsedArr[ LRofLV->getColor() ] = true;
762 // It is possible that one operand of this MInst was already spilled
763 // and it received some register temporarily. If that's the case,
764 // it is recorded in machine operand. We must skip such registers.
766 setRelRegsUsedByThisInst(RC, MInst);
768 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
769 if (!IsColorUsedArr[c])
770 return MRI.getUnifiedRegNum(RC->getID(), c);
776 //----------------------------------------------------------------------------
777 // Get any other register in a register class, other than what is used
778 // by operands of a machine instruction. Returns the unified reg number.
779 //----------------------------------------------------------------------------
780 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
781 const MachineInstr *MInst) {
783 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
784 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
786 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
787 IsColorUsedArr[i] = false;
789 setRelRegsUsedByThisInst(RC, MInst);
791 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
792 if (!IsColorUsedArr[c])
793 return MRI.getUnifiedRegNum(RC->getID(), c);
795 assert(0 && "FATAL: No free register could be found in reg class!!");
800 //----------------------------------------------------------------------------
801 // This method modifies the IsColorUsedArr of the register class passed to it.
802 // It sets the bits corresponding to the registers used by this machine
803 // instructions. Both explicit and implicit operands are set.
804 //----------------------------------------------------------------------------
805 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
806 const MachineInstr *MInst ) {
808 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
810 // Add the registers already marked as used by the instruction.
811 // This should include any scratch registers that are used to save
812 // values across the instruction (e.g., for saving state register values).
813 const hash_set<int>& regsUsed = MInst->getRegsUsed();
814 for (hash_set<int>::const_iterator SI=regsUsed.begin(), SE=regsUsed.end();
817 unsigned classId = 0;
818 int classRegNum = MRI.getClassRegNum(*SI, classId);
819 if (RC->getID() == classId)
821 assert(classRegNum < (int) IsColorUsedArr.size() &&
822 "Illegal register number for this reg class?");
823 IsColorUsedArr[classRegNum] = true;
827 // Now add registers allocated to the live ranges of values used in
828 // the instruction. These are not yet recorded in the instruction.
829 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
831 const MachineOperand& Op = MInst->getOperand(OpNum);
833 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
834 Op.getOperandType() == MachineOperand::MO_CCRegister)
835 if (const Value* Val = Op.getVRegValue())
836 if (MRI.getRegClassIDOfValue(Val) == RC->getID())
837 if (Op.getAllocatedRegNum() == -1)
838 if (LiveRange *LROfVal = LRI.getLiveRangeForValue(Val))
839 if (LROfVal->hasColor() )
840 // this operand is in a LR that received a color
841 IsColorUsedArr[LROfVal->getColor()] = true;
844 // If there are implicit references, mark their allocated regs as well
846 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++)
848 LRofImpRef = LRI.getLiveRangeForValue(MInst->getImplicitRef(z)))
849 if (LRofImpRef->hasColor())
850 // this implicit reference is in a LR that received a color
851 IsColorUsedArr[LRofImpRef->getColor()] = true;
855 //----------------------------------------------------------------------------
856 // If there are delay slots for an instruction, the instructions
857 // added after it must really go after the delayed instruction(s).
858 // So, we move the InstrAfter of that instruction to the
859 // corresponding delayed instruction using the following method.
861 //----------------------------------------------------------------------------
862 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
863 const MachineInstr *DelayedMI) {
865 // "added after" instructions of the original instr
866 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
868 // "added instructions" of the delayed instr
869 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
871 // "added after" instructions of the delayed instr
872 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
874 // go thru all the "added after instructions" of the original instruction
875 // and append them to the "addded after instructions" of the delayed
877 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
879 // empty the "added after instructions" of the original instruction
883 //----------------------------------------------------------------------------
884 // This method prints the code with registers after register allocation is
886 //----------------------------------------------------------------------------
887 void PhyRegAlloc::printMachineCode()
890 cerr << "\n;************** Function " << Meth->getName()
891 << " *****************\n";
893 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
895 cerr << "\n"; printLabel(BBI); cerr << ": ";
897 // get the iterator for machine instructions
898 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
899 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
901 // iterate over all the machine instructions in BB
902 for ( ; MII != MIVec.end(); ++MII) {
903 MachineInstr *const MInst = *MII;
906 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
908 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
909 MachineOperand& Op = MInst->getOperand(OpNum);
911 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
912 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
913 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
915 const Value *const Val = Op.getVRegValue () ;
916 // ****this code is temporary till NULL Values are fixed
918 cerr << "\t<*NULL*>";
922 // if a label or a constant
923 if (isa<BasicBlock>(Val)) {
924 cerr << "\t"; printLabel( Op.getVRegValue () );
926 // else it must be a register value
927 const int RegNum = Op.getAllocatedRegNum();
929 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
931 cerr << "(" << Val->getName() << ")";
933 cerr << "(" << Val << ")";
938 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
940 if (LROfVal->hasSpillOffset() )
945 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
946 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
950 cerr << "\t" << Op; // use dump field
955 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
956 if (NumOfImpRefs > 0) {
957 cerr << "\tImplicit:";
959 for (unsigned z=0; z < NumOfImpRefs; z++)
960 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
963 } // for all machine instructions
973 //----------------------------------------------------------------------------
975 //----------------------------------------------------------------------------
976 void PhyRegAlloc::colorIncomingArgs()
978 const BasicBlock &FirstBB = Meth->front();
979 const MachineInstr *FirstMI = MachineCodeForBasicBlock::get(&FirstBB).front();
980 assert(FirstMI && "No machine instruction in entry BB");
982 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
986 //----------------------------------------------------------------------------
987 // Used to generate a label for a basic block
988 //----------------------------------------------------------------------------
989 void PhyRegAlloc::printLabel(const Value *const Val) {
991 cerr << Val->getName();
993 cerr << "Label" << Val;
997 //----------------------------------------------------------------------------
998 // This method calls setSugColorUsable method of each live range. This
999 // will determine whether the suggested color of LR is really usable.
1000 // A suggested color is not usable when the suggested color is volatile
1001 // AND when there are call interferences
1002 //----------------------------------------------------------------------------
1004 void PhyRegAlloc::markUnusableSugColors()
1006 // hash map iterator
1007 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1008 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1010 for (; HMI != HMIEnd ; ++HMI ) {
1012 LiveRange *L = HMI->second; // get the LiveRange
1014 if (L->hasSuggestedColor()) {
1015 int RCID = L->getRegClass()->getID();
1016 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1017 L->isCallInterference() )
1018 L->setSuggestedColorUsable( false );
1020 L->setSuggestedColorUsable( true );
1022 } // if L->hasSuggestedColor()
1024 } // for all LR's in hash map
1029 //----------------------------------------------------------------------------
1030 // The following method will set the stack offsets of the live ranges that
1031 // are decided to be spillled. This must be called just after coloring the
1032 // LRs using the graph coloring algo. For each live range that is spilled,
1033 // this method allocate a new spill position on the stack.
1034 //----------------------------------------------------------------------------
1036 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1037 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1039 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1040 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1042 for ( ; HMI != HMIEnd ; ++HMI) {
1043 if (HMI->first && HMI->second) {
1044 LiveRange *L = HMI->second; // get the LiveRange
1045 if (!L->hasColor()) { // NOTE: ** allocating the size of long Type **
1046 int stackOffset = mcInfo.allocateSpilledValue(TM, Type::LongTy);
1047 L->setSpillOffFromFP(stackOffset);
1049 cerr << " LR# " << L->getUserIGNode()->getIndex()
1050 << ": stack-offset = " << stackOffset << "\n";
1053 } // for all LR's in hash map
1058 //----------------------------------------------------------------------------
1059 // The entry pont to Register Allocation
1060 //----------------------------------------------------------------------------
1062 void PhyRegAlloc::allocateRegisters()
1065 // make sure that we put all register classes into the RegClassList
1066 // before we call constructLiveRanges (now done in the constructor of
1067 // PhyRegAlloc class).
1069 LRI.constructLiveRanges(); // create LR info
1071 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1072 LRI.printLiveRanges();
1074 createIGNodeListsAndIGs(); // create IGNode list and IGs
1076 buildInterferenceGraphs(); // build IGs in all reg classes
1079 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1080 // print all LRs in all reg classes
1081 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1082 RegClassList[rc]->printIGNodeList();
1084 // print IGs in all register classes
1085 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1086 RegClassList[rc]->printIG();
1090 LRI.coalesceLRs(); // coalesce all live ranges
1093 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1094 // print all LRs in all reg classes
1095 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1096 RegClassList[ rc ]->printIGNodeList();
1098 // print IGs in all register classes
1099 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1100 RegClassList[ rc ]->printIG();
1104 // mark un-usable suggested color before graph coloring algorithm.
1105 // When this is done, the graph coloring algo will not reserve
1106 // suggested color unnecessarily - they can be used by another LR
1108 markUnusableSugColors();
1110 // color all register classes using the graph coloring algo
1111 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1112 RegClassList[ rc ]->colorAllRegs();
1114 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1115 // a poistion for such spilled LRs
1117 allocateStackSpace4SpilledLRs();
1119 mcInfo.popAllTempValues(TM); // TODO **Check
1121 // color incoming args - if the correct color was not received
1122 // insert code to copy to the correct register
1124 colorIncomingArgs();
1126 // Now update the machine code with register names and add any
1127 // additional code inserted by the register allocator to the instruction
1130 updateMachineCode();
1133 cerr << "\n**** Machine Code After Register Allocation:\n\n";
1134 MachineCodeForMethod::get(Meth).dump();