1 #include "llvm/CodeGen/PhyRegAlloc.h"
3 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
4 "enable register allocation debugging information",
5 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
6 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
7 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
10 //----------------------------------------------------------------------------
11 // Constructor: Init local composite objects and create register classes.
12 //----------------------------------------------------------------------------
13 PhyRegAlloc::PhyRegAlloc(const Method *const M,
14 const TargetMachine& tm,
15 MethodLiveVarInfo *const Lvi)
17 Meth(M), TM(tm), LVI(Lvi), LRI(M, tm, RegClassList),
18 MRI( tm.getRegInfo() ),
19 NumOfRegClasses(MRI.getNumOfRegClasses()),
23 // **TODO: use an actual reserved color list
24 ReservedColorListType *RCL = new ReservedColorListType();
26 // create each RegisterClass and put in RegClassList
27 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
28 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), RCL) );
32 //----------------------------------------------------------------------------
33 // This method initally creates interference graphs (one in each reg class)
34 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
35 //----------------------------------------------------------------------------
37 void PhyRegAlloc::createIGNodeListsAndIGs()
39 if(DEBUG_RA ) cerr << "Creating LR lists ..." << endl;
42 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
45 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
47 for( ; HMI != HMIEnd ; ++HMI ) {
51 LiveRange *L = (*HMI).second; // get the LiveRange
55 cerr << "\n*?!?Warning: Null liver range found for: ";
56 printValue( (*HMI).first) ; cerr << endl;
60 // if the Value * is not null, and LR
61 // is not yet written to the IGNodeList
62 if( !(L->getUserIGNode()) ) {
64 RegClass *const RC = // RegClass of first value in the LR
65 //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
66 RegClassList[ L->getRegClass()->getID() ];
68 RC-> addLRToIG( L ); // add this LR to an IG
74 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
75 RegClassList[ rc ]->createInterferenceGraph();
78 cerr << "LRLists Created!" << endl;
83 //----------------------------------------------------------------------------
84 // This method will add all interferences at for a given instruction.
85 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
86 // class as that of live var. The live var passed to this function is the
87 // LVset AFTER the instruction
88 //----------------------------------------------------------------------------
90 void PhyRegAlloc::addInterference(const Value *const Def,
91 const LiveVarSet *const LVSet,
92 const bool isCallInst) {
94 LiveVarSet::const_iterator LIt = LVSet->begin();
96 // get the live range of instruction
97 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
99 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
100 assert( IGNodeOfDef );
102 RegClass *const RCOfDef = LROfDef->getRegClass();
104 // for each live var in live variable set
105 for( ; LIt != LVSet->end(); ++LIt) {
108 cerr << "< Def="; printValue(Def);
109 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
112 // get the live range corresponding to live var
113 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
115 // LROfVar can be null if it is a const since a const
116 // doesn't have a dominating def - see Assumptions above
119 if(LROfDef == LROfVar) // do not set interf for same LR
122 // if 2 reg classes are the same set interference
123 if( RCOfDef == LROfVar->getRegClass() ){
124 RCOfDef->setInterference( LROfDef, LROfVar);
128 //the live range of this var interferes with this call
130 LROfVar->addCallInterference( (const Instruction *const) Def );
133 else if(DEBUG_RA > 1) {
134 // we will not have LRs for values not explicitly allocated in the
135 // instruction stream (e.g., constants)
136 cerr << " warning: no live range for " ;
137 printValue( *LIt); cerr << endl; }
143 //----------------------------------------------------------------------------
144 // This method will walk thru code and create interferences in the IG of
146 //----------------------------------------------------------------------------
148 void PhyRegAlloc::buildInterferenceGraphs()
151 if(DEBUG_RA) cerr << "Creating interference graphs ..." << endl;
153 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
155 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
157 // get the iterator for machine instructions
158 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
159 MachineCodeForBasicBlock::const_iterator
160 MInstIterator = MIVec.begin();
162 // iterate over all the machine instructions in BB
163 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
165 const MachineInstr *const MInst = *MInstIterator;
167 // get the LV set after the instruction
168 const LiveVarSet *const LVSetAI =
169 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
171 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
173 // iterate over MI operands to find defs
174 for( MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done(); ++OpI) {
177 // create a new LR iff this operand is a def
178 addInterference(*OpI, LVSetAI, isCallInst );
182 } // for all operands
184 } // for all machine instructions in BB
189 // go thru LLVM instructions in the basic block and record all CALL
190 // instructions and Return instructions in the CallInstrList
191 // This is done because since there are no reverse pointers in machine
192 // instructions to find the llvm instruction, when we encounter a call
193 // or a return whose args must be specailly colored (e.g., %o's for args)
194 BasicBlock::const_iterator InstIt = (*BBI)->begin();
196 for( ; InstIt != (*BBI)->end() ; ++ InstIt) {
197 unsigned OpCode = (*InstIt)->getOpcode();
199 if( OpCode == Instruction::Call )
200 CallInstrList.push_back( *InstIt );
202 else if( OpCode == Instruction::Ret )
203 RetInstrList.push_back( *InstIt );
209 } // for all BBs in method
212 // add interferences for method arguments. Since there are no explict
213 // defs in method for args, we have to add them manually
215 addInterferencesForArgs(); // add interference for method args
218 cerr << "Interference graphs calculted!" << endl;
225 //----------------------------------------------------------------------------
226 // This method will add interferences for incoming arguments to a method.
227 //----------------------------------------------------------------------------
228 void PhyRegAlloc::addInterferencesForArgs()
230 // get the InSet of root BB
231 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
233 // get the argument list
234 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
236 // get an iterator to arg list
237 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
240 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
241 addInterference( *ArgIt, InSet, false ); // add interferences between
242 // args and LVars at start
244 cerr << " - %% adding interference for argument ";
245 printValue( (const Value *) *ArgIt); cerr << endl;
252 //----------------------------------------------------------------------------
254 //----------------------------------------------------------------------------
257 void PhyRegAlloc::insertCallerSavingCode(const MachineInstr *MInst,
258 const BasicBlock *BB )
260 assert( (TM.getInstrInfo()).isCall( MInst->getOpCode() ) );
262 int StackOff = 10; // ****TODO : Change
263 set<unsigned> PushedRegSet();
265 // Now find the LR of the return value of the call
266 // The last *implicit operand* is the return value of a call
267 // Insert it to to he PushedRegSet since we must not save that register
268 // and restore it after the call.
269 // We do this because, we look at the LV set *after* the instruction
270 // to determine, which LRs must be saved across calls. The return value
271 // of the call is live in this set - but we must not save/restore it.
273 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
274 if( NumOfImpRefs > 0 ) {
276 if( MInst->implicitRefIsDefined(NumOfImpRefs-1) ) {
278 const Value *RetVal = CallMI->getImplicitRef(NumOfImpRefs-1);
279 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
280 assert( RetValLR && "No LR for RetValue of call");
283 MRI.getUnifiedRegNum((RetValLR->getRegClass())->getID(),
284 RetValLR->getColor() ) );
290 LiveVarSet *LVSetAft = LVI->getLiveVarSetAfterMInst(MInst, BB);
292 LiveVarSet::const_iterator LIt = LVSetAft->begin();
294 // for each live var in live variable set after machine inst
295 for( ; LIt != LVSetAft->end(); ++LIt) {
297 // get the live range corresponding to live var
298 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
300 // LROfVar can be null if it is a const since a const
301 // doesn't have a dominating def - see Assumptions above
304 if( LR->hasColor() ) {
306 unsigned RCID = (LR->getRegClass())->getID();
307 unsigned Color = LR->getColor();
309 if ( MRI.isRegVolatile(RCID, Color) ) {
311 // if the value is in both LV sets (i.e., live before and after
312 // the call machine instruction)
314 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
316 if( PuhsedRegSet.find(Reg) == PhusedRegSet.end() ) {
318 // if we haven't already pushed that register
321 MRI.saveRegOnStackMI(Reg, MRI.getFPReg(), StackOff );
323 ((AddedInstrMap[MInst])->InstrnsBefore).push_front(AdI);
324 ((AddedInstrMap[MInst])->InstrnsAfter).push_back(AdI);
327 PushedRegSet.insert( Reg );
328 StackOff += 4; // ****TODO: Correct ??????
329 cerr << "Inserted caller saving instr");
331 } // if not already pushed
333 } // if LR has a volatile color
337 } // if there is a LR for Var
339 } // for each value in the LV set after instruction
345 //----------------------------------------------------------------------------
346 // This method is called after register allocation is complete to set the
347 // allocated reisters in the machine code. This code will add register numbers
348 // to MachineOperands that contain a Value.
349 //----------------------------------------------------------------------------
351 void PhyRegAlloc::updateMachineCode()
354 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
356 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
358 // get the iterator for machine instructions
359 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
360 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
362 // iterate over all the machine instructions in BB
363 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
365 MachineInstr *MInst = *MInstIterator;
368 // If there are instructions before to be added, add them now
369 // ***TODO: Add InstrnsAfter as well
370 if( AddedInstrMap[ MInst ] ) {
372 deque<MachineInstr *> &IBef =
373 (AddedInstrMap[MInst])->InstrnsBefore;
375 if( ! IBef.empty() ) {
377 deque<MachineInstr *>::iterator AdIt;
379 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
381 cerr << "*ADDED instr opcode: ";
382 cerr << TargetInstrDescriptors[(*AdIt)->getOpCode()].opCodeString;
385 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
391 // restart from the topmost instruction added
392 //MInst = *MInstIterator;
398 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
400 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
402 MachineOperand& Op = MInst->getOperand(OpNum);
404 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
405 Op.getOperandType() == MachineOperand::MO_CCRegister) {
407 const Value *const Val = Op.getVRegValue();
409 // delete this condition checking later (must assert if Val is null)
412 cerr << "Warning: NULL Value found for operand" << endl;
415 assert( Val && "Value is NULL");
417 const LiveRange *const LR = LRI.getLiveRangeForValue(Val);
421 // nothing to worry if it's a const or a label
424 cerr << "*NO LR for inst opcode: ";
425 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
428 if( Op.getAllocatedRegNum() == -1)
429 Op.setRegForValue( 1000 ); // mark register as invalid
432 if( ((Val->getType())->isLabelType()) ||
433 (Val->getValueType() == Value::ConstantVal) )
436 // The return address is not explicitly defined within a
437 // method. So, it is not colored by usual algorithm. In that case
440 //else if (TM.getInstrInfo().isCall(MInst->getOpCode()))
441 //Op.setRegForValue( MRI.getCallAddressReg() );
443 //TM.getInstrInfo().isReturn(MInst->getOpCode())
444 else if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ) {
445 if (DEBUG_RA) cerr << endl << "RETURN found" << endl;
446 Op.setRegForValue( MRI.getReturnAddressReg() );
450 if (Val->getValueType() == Value::InstructionVal)
452 cerr << "!Warning: No LiveRange for: ";
453 printValue( Val); cerr << " Type: " << Val->getValueType();
454 cerr << " RegVal=" << Op.getAllocatedRegNum() << endl;
462 unsigned RCID = (LR->getRegClass())->getID();
464 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
466 int RegNum = MRI.getUnifiedRegNum(RCID, LR->getColor());
479 //----------------------------------------------------------------------------
480 // This method prints the code with registers after register allocation is
482 //----------------------------------------------------------------------------
483 void PhyRegAlloc::printMachineCode()
486 cerr << endl << ";************** Method ";
487 cerr << Meth->getName() << " *****************" << endl;
489 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
491 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
493 cerr << endl ; printLabel( *BBI); cerr << ": ";
495 // get the iterator for machine instructions
496 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
497 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
499 // iterate over all the machine instructions in BB
500 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
502 MachineInstr *const MInst = *MInstIterator;
505 cerr << endl << "\t";
506 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
509 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
511 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
513 MachineOperand& Op = MInst->getOperand(OpNum);
515 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
516 Op.getOperandType() == MachineOperand::MO_CCRegister ||
517 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp ) {
519 const Value *const Val = Op.getVRegValue () ;
520 // ****this code is temporary till NULL Values are fixed
522 cerr << "\t<*NULL*>";
526 // if a label or a constant
527 if( (Val->getValueType() == Value::BasicBlockVal) ) {
529 cerr << "\t"; printLabel( Op.getVRegValue () );
532 // else it must be a register value
533 const int RegNum = Op.getAllocatedRegNum();
535 //if( RegNum != 1000)
537 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
538 // else cerr << "\t<*NoReg*>";
543 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
544 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
548 cerr << "\t" << Op; // use dump field
561 //----------------------------------------------------------------------------
563 //----------------------------------------------------------------------------
565 void PhyRegAlloc::colorCallRetArgs()
568 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
569 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
571 for( ; It != CallRetInstList.end(); ++It ) {
573 const MachineInstr *const CRMI = *It;
574 unsigned OpCode = CRMI->getOpCode();
576 // get the added instructions for this Call/Ret instruciton
577 AddedInstrns *AI = AddedInstrMap[ CRMI ];
579 AI = new AddedInstrns();
580 AddedInstrMap[ CRMI ] = AI;
583 if( (TM.getInstrInfo()).isCall( OpCode ) )
584 MRI.colorCallArgs( CRMI, LRI, AI );
586 else if ( (TM.getInstrInfo()).isReturn(OpCode) )
587 MRI.colorRetValue( CRMI, LRI, AI );
589 else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
595 //----------------------------------------------------------------------------
597 //----------------------------------------------------------------------------
598 void PhyRegAlloc::colorIncomingArgs()
600 const BasicBlock *const FirstBB = Meth->front();
601 const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
602 assert( FirstMI && "No machine instruction in entry BB");
604 AddedInstrns *AI = AddedInstrMap[ FirstMI ];
606 AI = new AddedInstrns();
607 AddedInstrMap[ FirstMI ] = AI;
610 MRI.colorMethodArgs(Meth, LRI, AI );
614 //----------------------------------------------------------------------------
615 // Used to generate a label for a basic block
616 //----------------------------------------------------------------------------
617 void PhyRegAlloc::printLabel(const Value *const Val)
620 cerr << Val->getName();
622 cerr << "Label" << Val;
626 //----------------------------------------------------------------------------
627 // The entry pont to Register Allocation
628 //----------------------------------------------------------------------------
630 void PhyRegAlloc::allocateRegisters()
633 // make sure that we put all register classes into the RegClassList
634 // before we call constructLiveRanges (now done in the constructor of
635 // PhyRegAlloc class).
637 constructLiveRanges(); // create LR info
640 LRI.printLiveRanges();
642 createIGNodeListsAndIGs(); // create IGNode list and IGs
644 buildInterferenceGraphs(); // build IGs in all reg classes
648 // print all LRs in all reg classes
649 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
650 RegClassList[ rc ]->printIGNodeList();
652 // print IGs in all register classes
653 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
654 RegClassList[ rc ]->printIG();
657 LRI.coalesceLRs(); // coalesce all live ranges
660 // print all LRs in all reg classes
661 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
662 RegClassList[ rc ]->printIGNodeList();
664 // print IGs in all register classes
665 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
666 RegClassList[ rc ]->printIG();
669 // color all register classes
670 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
671 RegClassList[ rc ]->colorAllRegs();
674 // color incoming args and call args
681 // PrintMachineInstructions(Meth);
682 printMachineCode(); // only for DEBUGGING