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/MachineFunction.h"
13 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineFrameInfo.h"
17 #include "llvm/Target/MachineInstrInfo.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/iOther.h"
21 #include "Support/STLExtras.h"
22 #include "Support/CommandLine.h"
27 RegAllocDebugLevel_t DEBUG_RA;
29 static cl::opt<RegAllocDebugLevel_t, true>
30 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
31 cl::desc("enable register allocation debugging information"),
33 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
34 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
35 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
36 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
37 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
38 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
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>();
66 AU.addRequired<FunctionLiveVarInfo>();
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(MachineFunction::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 >= RA_DEBUG_LiveRanges) 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 LIVE RANGE FOUND FOR: "
124 << RAV(HMI->first) << "****\n";
128 // if the Value * is not null, and LR is not yet written to the IGNodeList
129 if (!(L->getUserIGNode()) ) {
130 RegClass *const RC = // RegClass of first value in the LR
131 RegClassList[ L->getRegClass()->getID() ];
132 RC->addLRToIG(L); // add this LR to an IG
138 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
139 RegClassList[rc]->createInterferenceGraph();
141 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
145 //----------------------------------------------------------------------------
146 // This method will add all interferences at for a given instruction.
147 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
148 // class as that of live var. The live var passed to this function is the
149 // LVset AFTER the instruction
150 //----------------------------------------------------------------------------
152 void PhyRegAlloc::addInterference(const Value *Def,
153 const ValueSet *LVSet,
156 ValueSet::const_iterator LIt = LVSet->begin();
158 // get the live range of instruction
160 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
162 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
163 assert( IGNodeOfDef );
165 RegClass *const RCOfDef = LROfDef->getRegClass();
167 // for each live var in live variable set
169 for ( ; LIt != LVSet->end(); ++LIt) {
171 if (DEBUG_RA >= RA_DEBUG_Verbose)
172 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
174 // get the live range corresponding to live var
176 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
178 // LROfVar can be null if it is a const since a const
179 // doesn't have a dominating def - see Assumptions above
182 if (LROfDef != LROfVar) // do not set interf for same LR
183 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
184 RCOfDef->setInterference( LROfDef, LROfVar);
190 //----------------------------------------------------------------------------
191 // For a call instruction, this method sets the CallInterference flag in
192 // the LR of each variable live int the Live Variable Set live after the
193 // call instruction (except the return value of the call instruction - since
194 // the return value does not interfere with that call itself).
195 //----------------------------------------------------------------------------
197 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
198 const ValueSet *LVSetAft) {
200 if (DEBUG_RA >= RA_DEBUG_Interference)
201 cerr << "\n For call inst: " << *MInst;
203 ValueSet::const_iterator LIt = LVSetAft->begin();
205 // for each live var in live variable set after machine inst
207 for ( ; LIt != LVSetAft->end(); ++LIt) {
209 // get the live range corresponding to live var
211 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
213 // LR can be null if it is a const since a const
214 // doesn't have a dominating def - see Assumptions above
217 if (DEBUG_RA >= RA_DEBUG_Interference) {
218 cerr << "\n\tLR after Call: ";
221 LR->setCallInterference();
222 if (DEBUG_RA >= RA_DEBUG_Interference) {
223 cerr << "\n ++After adding call interference for LR: " ;
230 // Now find the LR of the return value of the call
231 // We do this because, we look at the LV set *after* the instruction
232 // to determine, which LRs must be saved across calls. The return value
233 // of the call is live in this set - but it does not interfere with call
234 // (i.e., we can allocate a volatile register to the return value)
236 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
238 if (const Value *RetVal = argDesc->getReturnValue()) {
239 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
240 assert( RetValLR && "No LR for RetValue of call");
241 RetValLR->clearCallInterference();
244 // If the CALL is an indirect call, find the LR of the function pointer.
245 // That has a call interference because it conflicts with outgoing args.
246 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
247 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
248 assert( AddrValLR && "No LR for indirect addr val of call");
249 AddrValLR->setCallInterference();
257 //----------------------------------------------------------------------------
258 // This method will walk thru code and create interferences in the IG of
259 // each RegClass. Also, this method calculates the spill cost of each
260 // Live Range (it is done in this method to save another pass over the code).
261 //----------------------------------------------------------------------------
262 void PhyRegAlloc::buildInterferenceGraphs()
265 if (DEBUG_RA >= RA_DEBUG_Interference)
266 cerr << "Creating interference graphs ...\n";
268 unsigned BBLoopDepthCost;
269 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
272 // find the 10^(loop_depth) of this BB
274 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
276 // get the iterator for machine instructions
278 const MachineBasicBlock& MIVec = MachineBasicBlock::get(BBI);
279 MachineBasicBlock::const_iterator MII = MIVec.begin();
281 // iterate over all the machine instructions in BB
283 for ( ; MII != MIVec.end(); ++MII) {
285 const MachineInstr *MInst = *MII;
287 // get the LV set after the instruction
289 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
291 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
294 // set the isCallInterference flag of each live range wich extends
295 // accross this call instruction. This information is used by graph
296 // coloring algo to avoid allocating volatile colors to live ranges
297 // that span across calls (since they have to be saved/restored)
299 setCallInterferences(MInst, &LVSetAI);
303 // iterate over all MI operands to find defs
305 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
306 OpE = MInst->end(); OpI != OpE; ++OpI) {
307 if (OpI.isDef()) // create a new LR iff this operand is a def
308 addInterference(*OpI, &LVSetAI, isCallInst);
310 // Calculate the spill cost of each live range
312 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
313 if (LR) LR->addSpillCost(BBLoopDepthCost);
317 // if there are multiple defs in this instruction e.g. in SETX
319 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
320 addInterf4PseudoInstr(MInst);
323 // Also add interference for any implicit definitions in a machine
324 // instr (currently, only calls have this).
326 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
327 if ( NumOfImpRefs > 0 ) {
328 for (unsigned z=0; z < NumOfImpRefs; z++)
329 if (MInst->implicitRefIsDefined(z) )
330 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
334 } // for all machine instructions in BB
335 } // for all BBs in function
338 // add interferences for function arguments. Since there are no explict
339 // defs in the function for args, we have to add them manually
341 addInterferencesForArgs();
343 if (DEBUG_RA >= RA_DEBUG_Interference)
344 cerr << "Interference graphs calculated!\n";
349 //--------------------------------------------------------------------------
350 // Pseudo instructions will be exapnded to multiple instructions by the
351 // assembler. Consequently, all the opernds must get distinct registers.
352 // Therefore, we mark all operands of a pseudo instruction as they interfere
354 //--------------------------------------------------------------------------
355 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
357 bool setInterf = false;
359 // iterate over MI operands to find defs
361 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
362 ItE = MInst->end(); It1 != ItE; ++It1) {
363 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
364 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
366 MachineInstr::const_val_op_iterator It2 = It1;
367 for (++It2; It2 != ItE; ++It2) {
368 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
371 RegClass *RCOfOp1 = LROfOp1->getRegClass();
372 RegClass *RCOfOp2 = LROfOp2->getRegClass();
374 if (RCOfOp1 == RCOfOp2 ){
375 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
379 } // for all other defs in machine instr
380 } // for all operands in an instruction
382 if (!setInterf && MInst->getNumOperands() > 2) {
383 cerr << "\nInterf not set for any operand in pseudo instr:\n";
385 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
391 //----------------------------------------------------------------------------
392 // This method will add interferences for incoming arguments to a function.
393 //----------------------------------------------------------------------------
395 void PhyRegAlloc::addInterferencesForArgs() {
396 // get the InSet of root BB
397 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
399 for (Function::const_aiterator AI=Meth->abegin(); AI != Meth->aend(); ++AI) {
400 // add interferences between args and LVars at start
401 addInterference(AI, &InSet, false);
403 if (DEBUG_RA >= RA_DEBUG_Interference)
404 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
409 //----------------------------------------------------------------------------
410 // This method is called after register allocation is complete to set the
411 // allocated reisters in the machine code. This code will add register numbers
412 // to MachineOperands that contain a Value. Also it calls target specific
413 // methods to produce caller saving instructions. At the end, it adds all
414 // additional instructions produced by the register allocator to the
415 // instruction stream.
416 //----------------------------------------------------------------------------
418 //-----------------------------
419 // Utility functions used below
420 //-----------------------------
422 InsertBefore(MachineInstr* newMI,
423 MachineBasicBlock& MIVec,
424 MachineBasicBlock::iterator& MII)
426 MII = MIVec.insert(MII, newMI);
431 InsertAfter(MachineInstr* newMI,
432 MachineBasicBlock& MIVec,
433 MachineBasicBlock::iterator& MII)
435 ++MII; // insert before the next instruction
436 MII = MIVec.insert(MII, newMI);
440 SubstituteInPlace(MachineInstr* newMI,
441 MachineBasicBlock& MIVec,
442 MachineBasicBlock::iterator MII)
448 PrependInstructions(vector<MachineInstr *> &IBef,
449 MachineBasicBlock& MIVec,
450 MachineBasicBlock::iterator& MII,
451 const std::string& msg)
455 MachineInstr* OrigMI = *MII;
456 std::vector<MachineInstr *>::iterator AdIt;
457 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
460 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
461 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
463 InsertBefore(*AdIt, MIVec, MII);
469 AppendInstructions(std::vector<MachineInstr *> &IAft,
470 MachineBasicBlock& MIVec,
471 MachineBasicBlock::iterator& MII,
472 const std::string& msg)
476 MachineInstr* OrigMI = *MII;
477 std::vector<MachineInstr *>::iterator AdIt;
478 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
481 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
482 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
484 InsertAfter(*AdIt, MIVec, MII);
490 void PhyRegAlloc::updateMachineCode()
492 MachineBasicBlock& MIVec = MachineBasicBlock::get(&Meth->getEntryNode());
494 // Insert any instructions needed at method entry
495 MachineBasicBlock::iterator MII = MIVec.begin();
496 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
497 "At function entry: \n");
498 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
499 "InstrsAfter should be unnecessary since we are just inserting at "
500 "the function entry point here.");
502 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
505 // iterate over all the machine instructions in BB
506 MachineBasicBlock &MIVec = MachineBasicBlock::get(BBI);
507 for (MachineBasicBlock::iterator MII = MIVec.begin();
508 MII != MIVec.end(); ++MII) {
510 MachineInstr *MInst = *MII;
512 unsigned Opcode = MInst->getOpCode();
514 // do not process Phis
515 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
518 // Reset tmp stack positions so they can be reused for each machine instr.
519 mcInfo.popAllTempValues(TM);
521 // Now insert speical instructions (if necessary) for call/return
524 if (TM.getInstrInfo().isCall(Opcode) ||
525 TM.getInstrInfo().isReturn(Opcode)) {
527 AddedInstrns &AI = AddedInstrMap[MInst];
529 if (TM.getInstrInfo().isCall(Opcode))
530 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
531 else if (TM.getInstrInfo().isReturn(Opcode))
532 MRI.colorRetValue(MInst, LRI, &AI);
535 // Set the registers for operands in the machine instruction
536 // if a register was successfully allocated. If not, insert
537 // code to spill the register value.
539 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
541 MachineOperand& Op = MInst->getOperand(OpNum);
542 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
543 Op.getType() == MachineOperand::MO_CCRegister)
545 const Value *const Val = Op.getVRegValue();
547 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
548 if (!LR) // consts or labels will have no live range
550 // if register is not allocated, mark register as invalid
551 if (Op.getAllocatedRegNum() == -1)
552 MInst->SetRegForOperand(OpNum, MRI.getInvalidRegNum());
557 MInst->SetRegForOperand(OpNum,
558 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
561 // LR did NOT receive a color (register). Insert spill code.
562 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
564 } // for each operand
566 // Now add instructions that the register allocator inserts before/after
567 // this machine instructions (done only for calls/rets/incoming args)
568 // We do this here, to ensure that spill for an instruction is inserted
569 // closest as possible to an instruction (see above insertCode4Spill...)
571 // First, if the instruction in the delay slot of a branch needs
572 // instructions inserted, move it out of the delay slot and before the
573 // branch because putting code before or after it would be VERY BAD!
575 unsigned bumpIteratorBy = 0;
576 if (MII != MIVec.begin())
577 if (unsigned predDelaySlots =
578 TM.getInstrInfo().getNumDelaySlots((*(MII-1))->getOpCode()))
580 assert(predDelaySlots==1 && "Not handling multiple delay slots!");
581 if (TM.getInstrInfo().isBranch((*(MII-1))->getOpCode())
582 && (AddedInstrMap.count(MInst) ||
583 AddedInstrMap[MInst].InstrnsAfter.size() > 0))
585 // Current instruction is in the delay slot of a branch and it
586 // needs spill code inserted before or after it.
587 // Move it before the preceding branch.
588 InsertBefore(MInst, MIVec, --MII);
590 new MachineInstr(TM.getInstrInfo().getNOPOpCode());
591 SubstituteInPlace(nopI, MIVec, MII+1); // replace orig with NOP
592 --MII; // point to MInst in new location
593 bumpIteratorBy = 2; // later skip the branch and the NOP!
597 // If there are instructions to be added, *before* this machine
598 // instruction, add them now.
600 if (AddedInstrMap.count(MInst)) {
601 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
604 // If there are instructions to be added *after* this machine
605 // instruction, add them now
607 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
609 // if there are delay slots for this instruction, the instructions
610 // added after it must really go after the delayed instruction(s)
611 // So, we move the InstrAfter of the current instruction to the
612 // corresponding delayed instruction
614 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) {
616 // Delayed instructions are typically branches or calls. Let's make
617 // sure this is not a branch, otherwise "insert-after" is meaningless,
618 // and should never happen for any reason (spill code, register
620 assert(! TM.getInstrInfo().isBranch(MInst->getOpCode()) &&
621 ! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
622 "INTERNAL ERROR: Register allocator should not be inserting "
623 "any code after a branch or return!");
625 move2DelayedInstr(MInst, *(MII+delay) );
628 // Here we can add the "instructions after" to the current
629 // instruction since there are no delay slots for this instruction
630 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
634 // If we mucked with the instruction order above, adjust the loop iterator
636 MII = MII + bumpIteratorBy;
638 } // for each machine instruction
644 //----------------------------------------------------------------------------
645 // This method inserts spill code for AN operand whose LR was spilled.
646 // This method may be called several times for a single machine instruction
647 // if it contains many spilled operands. Each time it is called, it finds
648 // a register which is not live at that instruction and also which is not
649 // used by other spilled operands of the same instruction. Then it uses
650 // this register temporarily to accomodate the spilled value.
651 //----------------------------------------------------------------------------
652 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
654 const BasicBlock *BB,
655 const unsigned OpNum) {
657 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
658 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
659 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
660 "Return value of a ret must be handled elsewhere");
662 MachineOperand& Op = MInst->getOperand(OpNum);
663 bool isDef = MInst->operandIsDefined(OpNum);
664 bool isDefAndUse = MInst->operandIsDefinedAndUsed(OpNum);
665 unsigned RegType = MRI.getRegType( LR );
666 int SpillOff = LR->getSpillOffFromFP();
667 RegClass *RC = LR->getRegClass();
668 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
670 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
672 vector<MachineInstr*> MIBef, MIAft;
673 vector<MachineInstr*> AdIMid;
675 // Choose a register to hold the spilled value. This may insert code
676 // before and after MInst to free up the value. If so, this code should
677 // be first and last in the spill sequence before/after MInst.
678 int TmpRegU = getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef, MIAft);
680 // Set the operand first so that it this register does not get used
681 // as a scratch register for later calls to getUsableUniRegAtMI below
682 MInst->SetRegForOperand(OpNum, TmpRegU);
684 // get the added instructions for this instruction
685 AddedInstrns &AI = AddedInstrMap[MInst];
687 // We may need a scratch register to copy the spilled value to/from memory.
688 // This may itself have to insert code to free up a scratch register.
689 // Any such code should go before (after) the spill code for a load (store).
690 int scratchRegType = -1;
692 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
694 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
695 MInst, MIBef, MIAft);
696 assert(scratchReg != MRI.getInvalidRegNum());
697 MInst->insertUsedReg(scratchReg);
700 if (!isDef || isDefAndUse) {
701 // for a USE, we have to load the value of LR from stack to a TmpReg
702 // and use the TmpReg as one operand of instruction
704 // actual loading instruction(s)
705 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU, RegType,
708 // the actual load should be after the instructions to free up TmpRegU
709 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
713 if (isDef) { // if this is a Def
714 // for a DEF, we have to store the value produced by this instruction
715 // on the stack position allocated for this LR
717 // actual storing instruction(s)
718 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff, RegType,
721 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
724 // Finally, insert the entire spill code sequences before/after MInst
725 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
726 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
729 cerr << "\nFor Inst:\n " << *MInst;
730 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
731 cerr << "; added Instructions:";
732 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
733 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
738 //----------------------------------------------------------------------------
739 // We can use the following method to get a temporary register to be used
740 // BEFORE any given machine instruction. If there is a register available,
741 // this method will simply return that register and set MIBef = MIAft = NULL.
742 // Otherwise, it will return a register and MIAft and MIBef will contain
743 // two instructions used to free up this returned register.
744 // Returned register number is the UNIFIED register number
745 //----------------------------------------------------------------------------
747 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
748 const ValueSet *LVSetBef,
750 std::vector<MachineInstr*>& MIBef,
751 std::vector<MachineInstr*>& MIAft) {
753 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
755 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
758 // we couldn't find an unused register. Generate code to free up a reg by
759 // saving it on stack and restoring after the instruction
761 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
763 RegU = getUniRegNotUsedByThisInst(RC, MInst);
765 // Check if we need a scratch register to copy this register to memory.
766 int scratchRegType = -1;
767 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
769 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
770 MInst, MIBef, MIAft);
771 assert(scratchReg != MRI.getInvalidRegNum());
773 // We may as well hold the value in the scratch register instead
774 // of copying it to memory and back. But we have to mark the
775 // register as used by this instruction, so it does not get used
776 // as a scratch reg. by another operand or anyone else.
777 MInst->insertUsedReg(scratchReg);
778 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
779 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
782 { // the register can be copied directly to/from memory so do it.
783 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
784 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
791 //----------------------------------------------------------------------------
792 // This method is called to get a new unused register that can be used to
793 // accomodate a spilled value.
794 // This method may be called several times for a single machine instruction
795 // if it contains many spilled operands. Each time it is called, it finds
796 // a register which is not live at that instruction and also which is not
797 // used by other spilled operands of the same instruction.
798 // Return register number is relative to the register class. NOT
800 //----------------------------------------------------------------------------
801 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
802 const MachineInstr *MInst,
803 const ValueSet *LVSetBef) {
805 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
807 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
809 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
810 IsColorUsedArr[i] = false;
812 ValueSet::const_iterator LIt = LVSetBef->begin();
814 // for each live var in live variable set after machine inst
815 for ( ; LIt != LVSetBef->end(); ++LIt) {
817 // get the live range corresponding to live var
818 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
820 // LR can be null if it is a const since a const
821 // doesn't have a dominating def - see Assumptions above
822 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
823 IsColorUsedArr[ LRofLV->getColor() ] = true;
826 // It is possible that one operand of this MInst was already spilled
827 // and it received some register temporarily. If that's the case,
828 // it is recorded in machine operand. We must skip such registers.
830 setRelRegsUsedByThisInst(RC, MInst);
832 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
833 if (!IsColorUsedArr[c])
834 return MRI.getUnifiedRegNum(RC->getID(), c);
840 //----------------------------------------------------------------------------
841 // Get any other register in a register class, other than what is used
842 // by operands of a machine instruction. Returns the unified reg number.
843 //----------------------------------------------------------------------------
844 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
845 const MachineInstr *MInst) {
847 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
848 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
850 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
851 IsColorUsedArr[i] = false;
853 setRelRegsUsedByThisInst(RC, MInst);
855 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
856 if (!IsColorUsedArr[c])
857 return MRI.getUnifiedRegNum(RC->getID(), c);
859 assert(0 && "FATAL: No free register could be found in reg class!!");
864 //----------------------------------------------------------------------------
865 // This method modifies the IsColorUsedArr of the register class passed to it.
866 // It sets the bits corresponding to the registers used by this machine
867 // instructions. Both explicit and implicit operands are set.
868 //----------------------------------------------------------------------------
869 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
870 const MachineInstr *MInst ) {
872 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
874 // Add the registers already marked as used by the instruction.
875 // This should include any scratch registers that are used to save
876 // values across the instruction (e.g., for saving state register values).
877 const vector<bool> ®sUsed = MInst->getRegsUsed();
878 for (unsigned i = 0, e = regsUsed.size(); i != e; ++i)
880 unsigned classId = 0;
881 int classRegNum = MRI.getClassRegNum(i, classId);
882 if (RC->getID() == classId)
884 assert(classRegNum < (int) IsColorUsedArr.size() &&
885 "Illegal register number for this reg class?");
886 IsColorUsedArr[classRegNum] = true;
890 // Now add registers allocated to the live ranges of values used in
891 // the instruction. These are not yet recorded in the instruction.
892 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
894 const MachineOperand& Op = MInst->getOperand(OpNum);
896 if (MInst->getOperandType(OpNum) == MachineOperand::MO_VirtualRegister ||
897 MInst->getOperandType(OpNum) == MachineOperand::MO_CCRegister)
898 if (const Value* Val = Op.getVRegValue())
899 if (MRI.getRegClassIDOfValue(Val) == RC->getID())
900 if (Op.getAllocatedRegNum() == -1)
901 if (LiveRange *LROfVal = LRI.getLiveRangeForValue(Val))
902 if (LROfVal->hasColor() )
903 // this operand is in a LR that received a color
904 IsColorUsedArr[LROfVal->getColor()] = true;
907 // If there are implicit references, mark their allocated regs as well
909 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++)
911 LRofImpRef = LRI.getLiveRangeForValue(MInst->getImplicitRef(z)))
912 if (LRofImpRef->hasColor())
913 // this implicit reference is in a LR that received a color
914 IsColorUsedArr[LRofImpRef->getColor()] = true;
918 //----------------------------------------------------------------------------
919 // If there are delay slots for an instruction, the instructions
920 // added after it must really go after the delayed instruction(s).
921 // So, we move the InstrAfter of that instruction to the
922 // corresponding delayed instruction using the following method.
924 //----------------------------------------------------------------------------
925 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
926 const MachineInstr *DelayedMI) {
928 // "added after" instructions of the original instr
929 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
931 // "added instructions" of the delayed instr
932 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
934 // "added after" instructions of the delayed instr
935 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
937 // go thru all the "added after instructions" of the original instruction
938 // and append them to the "addded after instructions" of the delayed
940 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
942 // empty the "added after instructions" of the original instruction
946 //----------------------------------------------------------------------------
947 // This method prints the code with registers after register allocation is
949 //----------------------------------------------------------------------------
950 void PhyRegAlloc::printMachineCode()
953 cerr << "\n;************** Function " << Meth->getName()
954 << " *****************\n";
956 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
958 cerr << "\n"; printLabel(BBI); cerr << ": ";
960 // get the iterator for machine instructions
961 MachineBasicBlock& MIVec = MachineBasicBlock::get(BBI);
962 MachineBasicBlock::iterator MII = MIVec.begin();
964 // iterate over all the machine instructions in BB
965 for ( ; MII != MIVec.end(); ++MII) {
966 MachineInstr *const MInst = *MII;
969 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
971 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
972 MachineOperand& Op = MInst->getOperand(OpNum);
974 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
975 Op.getType() == MachineOperand::MO_CCRegister /*||
976 Op.getType() == MachineOperand::MO_PCRelativeDisp*/ ) {
978 const Value *const Val = Op.getVRegValue () ;
979 // ****this code is temporary till NULL Values are fixed
981 cerr << "\t<*NULL*>";
985 // if a label or a constant
986 if (isa<BasicBlock>(Val)) {
987 cerr << "\t"; printLabel( Op.getVRegValue () );
989 // else it must be a register value
990 const int RegNum = Op.getAllocatedRegNum();
992 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
994 cerr << "(" << Val->getName() << ")";
996 cerr << "(" << Val << ")";
1001 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1003 if (LROfVal->hasSpillOffset() )
1008 else if (Op.getType() == MachineOperand::MO_MachineRegister) {
1009 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1013 cerr << "\t" << Op; // use dump field
1018 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1019 if (NumOfImpRefs > 0) {
1020 cerr << "\tImplicit:";
1022 for (unsigned z=0; z < NumOfImpRefs; z++)
1023 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1026 } // for all machine instructions
1036 //----------------------------------------------------------------------------
1038 //----------------------------------------------------------------------------
1039 void PhyRegAlloc::colorIncomingArgs()
1041 const BasicBlock &FirstBB = Meth->front();
1042 const MachineInstr *FirstMI = MachineBasicBlock::get(&FirstBB).front();
1043 assert(FirstMI && "No machine instruction in entry BB");
1045 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1049 //----------------------------------------------------------------------------
1050 // Used to generate a label for a basic block
1051 //----------------------------------------------------------------------------
1052 void PhyRegAlloc::printLabel(const Value *const Val) {
1054 cerr << Val->getName();
1056 cerr << "Label" << Val;
1060 //----------------------------------------------------------------------------
1061 // This method calls setSugColorUsable method of each live range. This
1062 // will determine whether the suggested color of LR is really usable.
1063 // A suggested color is not usable when the suggested color is volatile
1064 // AND when there are call interferences
1065 //----------------------------------------------------------------------------
1067 void PhyRegAlloc::markUnusableSugColors()
1069 // hash map iterator
1070 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1071 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1073 for (; HMI != HMIEnd ; ++HMI ) {
1075 LiveRange *L = HMI->second; // get the LiveRange
1077 if (L->hasSuggestedColor()) {
1078 int RCID = L->getRegClass()->getID();
1079 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1080 L->isCallInterference() )
1081 L->setSuggestedColorUsable( false );
1083 L->setSuggestedColorUsable( true );
1085 } // if L->hasSuggestedColor()
1087 } // for all LR's in hash map
1092 //----------------------------------------------------------------------------
1093 // The following method will set the stack offsets of the live ranges that
1094 // are decided to be spillled. This must be called just after coloring the
1095 // LRs using the graph coloring algo. For each live range that is spilled,
1096 // this method allocate a new spill position on the stack.
1097 //----------------------------------------------------------------------------
1099 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1100 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1102 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1103 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1105 for ( ; HMI != HMIEnd ; ++HMI) {
1106 if (HMI->first && HMI->second) {
1107 LiveRange *L = HMI->second; // get the LiveRange
1108 if (!L->hasColor()) { // NOTE: ** allocating the size of long Type **
1109 int stackOffset = mcInfo.allocateSpilledValue(TM, Type::LongTy);
1110 L->setSpillOffFromFP(stackOffset);
1112 cerr << " LR# " << L->getUserIGNode()->getIndex()
1113 << ": stack-offset = " << stackOffset << "\n";
1116 } // for all LR's in hash map
1121 //----------------------------------------------------------------------------
1122 // The entry pont to Register Allocation
1123 //----------------------------------------------------------------------------
1125 void PhyRegAlloc::allocateRegisters()
1128 // make sure that we put all register classes into the RegClassList
1129 // before we call constructLiveRanges (now done in the constructor of
1130 // PhyRegAlloc class).
1132 LRI.constructLiveRanges(); // create LR info
1134 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1135 LRI.printLiveRanges();
1137 createIGNodeListsAndIGs(); // create IGNode list and IGs
1139 buildInterferenceGraphs(); // build IGs in all reg classes
1142 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1143 // print all LRs in all reg classes
1144 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1145 RegClassList[rc]->printIGNodeList();
1147 // print IGs in all register classes
1148 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1149 RegClassList[rc]->printIG();
1153 LRI.coalesceLRs(); // coalesce all live ranges
1156 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1157 // print all LRs in all reg classes
1158 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1159 RegClassList[ rc ]->printIGNodeList();
1161 // print IGs in all register classes
1162 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1163 RegClassList[ rc ]->printIG();
1167 // mark un-usable suggested color before graph coloring algorithm.
1168 // When this is done, the graph coloring algo will not reserve
1169 // suggested color unnecessarily - they can be used by another LR
1171 markUnusableSugColors();
1173 // color all register classes using the graph coloring algo
1174 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1175 RegClassList[ rc ]->colorAllRegs();
1177 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1178 // a poistion for such spilled LRs
1180 allocateStackSpace4SpilledLRs();
1182 mcInfo.popAllTempValues(TM); // TODO **Check
1184 // color incoming args - if the correct color was not received
1185 // insert code to copy to the correct register
1187 colorIncomingArgs();
1189 // Now update the machine code with register names and add any
1190 // additional code inserted by the register allocator to the instruction
1193 updateMachineCode();
1196 cerr << "\n**** Machine Code After Register Allocation:\n\n";
1197 MachineFunction::get(Meth).dump();