1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "PhyRegAlloc.h"
9 #include "RegAllocCommon.h"
12 #include "llvm/CodeGen/MachineInstrBuilder.h"
13 #include "llvm/CodeGen/MachineInstrAnnot.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionInfo.h"
16 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegInfo.h"
23 #include "llvm/Function.h"
24 #include "llvm/Type.h"
25 #include "llvm/iOther.h"
26 #include "Support/STLExtras.h"
27 #include "Support/SetOperations.h"
28 #include "Support/CommandLine.h"
31 RegAllocDebugLevel_t DEBUG_RA;
33 static cl::opt<RegAllocDebugLevel_t, true>
34 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
35 cl::desc("enable register allocation debugging information"),
37 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
38 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
39 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
40 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
41 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
42 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
45 //----------------------------------------------------------------------------
46 // RegisterAllocation pass front end...
47 //----------------------------------------------------------------------------
49 class RegisterAllocator : public FunctionPass {
50 TargetMachine &Target;
52 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
54 const char *getPassName() const { return "Register Allocation"; }
56 bool runOnFunction(Function &F) {
58 std::cerr << "\n********* Function "<< F.getName() << " ***********\n";
60 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
61 &getAnalysis<LoopInfo>());
62 PRA.allocateRegisters();
64 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<LoopInfo>();
70 AU.addRequired<FunctionLiveVarInfo>();
75 FunctionPass *getRegisterAllocator(TargetMachine &T) {
76 return new RegisterAllocator(T);
79 //----------------------------------------------------------------------------
80 // Constructor: Init local composite objects and create register classes.
81 //----------------------------------------------------------------------------
82 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
83 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
84 : TM(tm), Fn(F), MF(MachineFunction::get(F)), LVI(Lvi),
85 LRI(F, tm, RegClassList), MRI(tm.getRegInfo()),
86 NumOfRegClasses(MRI.getNumOfRegClasses()), LoopDepthCalc(LDC) {
88 // create each RegisterClass and put in RegClassList
90 for (unsigned rc=0; rc != NumOfRegClasses; rc++)
91 RegClassList.push_back(new RegClass(F, &tm.getRegInfo(),
92 MRI.getMachineRegClass(rc)));
96 //----------------------------------------------------------------------------
97 // Destructor: Deletes register classes
98 //----------------------------------------------------------------------------
99 PhyRegAlloc::~PhyRegAlloc() {
100 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
101 delete RegClassList[rc];
103 AddedInstrMap.clear();
106 //----------------------------------------------------------------------------
107 // This method initially creates interference graphs (one in each reg class)
108 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
109 //----------------------------------------------------------------------------
110 void PhyRegAlloc::createIGNodeListsAndIGs() {
111 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
114 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
117 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
119 for (; HMI != HMIEnd ; ++HMI ) {
121 LiveRange *L = HMI->second; // get the LiveRange
124 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
125 << RAV(HMI->first) << "****\n";
129 // if the Value * is not null, and LR is not yet written to the IGNodeList
130 if (!(L->getUserIGNode()) ) {
131 RegClass *const RC = // RegClass of first value in the LR
132 RegClassList[ L->getRegClass()->getID() ];
133 RC->addLRToIG(L); // add this LR to an IG
139 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
140 RegClassList[rc]->createInterferenceGraph();
142 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
146 //----------------------------------------------------------------------------
147 // This method will add all interferences at for a given instruction.
148 // Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
149 // class as that of live var. The live var passed to this function is the
150 // LVset AFTER the instruction
151 //----------------------------------------------------------------------------
153 void PhyRegAlloc::addInterference(const Value *Def,
154 const ValueSet *LVSet,
157 ValueSet::const_iterator LIt = LVSet->begin();
159 // get the live range of instruction
161 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
163 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
164 assert( IGNodeOfDef );
166 RegClass *const RCOfDef = LROfDef->getRegClass();
168 // for each live var in live variable set
170 for ( ; LIt != LVSet->end(); ++LIt) {
172 if (DEBUG_RA >= RA_DEBUG_Verbose)
173 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
175 // get the live range corresponding to live var
177 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
179 // LROfVar can be null if it is a const since a const
180 // doesn't have a dominating def - see Assumptions above
183 if (LROfDef != LROfVar) // do not set interf for same LR
184 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
185 RCOfDef->setInterference( LROfDef, LROfVar);
191 //----------------------------------------------------------------------------
192 // For a call instruction, this method sets the CallInterference flag in
193 // the LR of each variable live int the Live Variable Set live after the
194 // call instruction (except the return value of the call instruction - since
195 // the return value does not interfere with that call itself).
196 //----------------------------------------------------------------------------
198 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
199 const ValueSet *LVSetAft) {
201 if (DEBUG_RA >= RA_DEBUG_Interference)
202 std::cerr << "\n For call inst: " << *MInst;
204 // for each live var in live variable set after machine inst
206 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
207 LIt != LEnd; ++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 std::cerr << "\n\tLR after Call: ";
221 LR->setCallInterference();
222 if (DEBUG_RA >= RA_DEBUG_Interference) {
223 std::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 std::cerr << "Creating interference graphs ...\n";
268 unsigned BBLoopDepthCost;
269 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
271 const MachineBasicBlock &MBB = *BBI;
272 const BasicBlock *BB = MBB.getBasicBlock();
274 // find the 10^(loop_depth) of this BB
276 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
278 // get the iterator for machine instructions
280 MachineBasicBlock::const_iterator MII = MBB.begin();
282 // iterate over all the machine instructions in BB
284 for ( ; MII != MBB.end(); ++MII) {
285 const MachineInstr *MInst = *MII;
287 // get the LV set after the instruction
289 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
290 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
293 // set the isCallInterference flag of each live range which extends
294 // across this call instruction. This information is used by graph
295 // coloring algorithm to avoid allocating volatile colors to live ranges
296 // that span across calls (since they have to be saved/restored)
298 setCallInterferences(MInst, &LVSetAI);
301 // iterate over all MI operands to find defs
303 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
304 OpE = MInst->end(); OpI != OpE; ++OpI) {
305 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
306 addInterference(*OpI, &LVSetAI, isCallInst);
308 // Calculate the spill cost of each live range
310 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
311 if (LR) LR->addSpillCost(BBLoopDepthCost);
315 // if there are multiple defs in this instruction e.g. in SETX
317 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
318 addInterf4PseudoInstr(MInst);
321 // Also add interference for any implicit definitions in a machine
322 // instr (currently, only calls have this).
324 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
325 for (unsigned z=0; z < NumOfImpRefs; z++)
326 if (MInst->getImplicitOp(z).opIsDefOnly() ||
327 MInst->getImplicitOp(z).opIsDefAndUse())
328 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
330 } // for all machine instructions in BB
331 } // for all BBs in function
334 // add interferences for function arguments. Since there are no explicit
335 // defs in the function for args, we have to add them manually
337 addInterferencesForArgs();
339 if (DEBUG_RA >= RA_DEBUG_Interference)
340 std::cerr << "Interference graphs calculated!\n";
345 //--------------------------------------------------------------------------
346 // Pseudo-instructions will be expanded to multiple instructions by the
347 // assembler. Consequently, all the opernds must get distinct registers.
348 // Therefore, we mark all operands of a pseudo instruction as they interfere
350 //--------------------------------------------------------------------------
351 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
353 bool setInterf = false;
355 // iterate over MI operands to find defs
357 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
358 ItE = MInst->end(); It1 != ItE; ++It1) {
359 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
360 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
362 MachineInstr::const_val_op_iterator It2 = It1;
363 for (++It2; It2 != ItE; ++It2) {
364 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
367 RegClass *RCOfOp1 = LROfOp1->getRegClass();
368 RegClass *RCOfOp2 = LROfOp2->getRegClass();
370 if (RCOfOp1 == RCOfOp2 ){
371 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
375 } // for all other defs in machine instr
376 } // for all operands in an instruction
378 if (!setInterf && MInst->getNumOperands() > 2) {
379 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
381 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
387 //----------------------------------------------------------------------------
388 // This method will add interferences for incoming arguments to a function.
389 //----------------------------------------------------------------------------
391 void PhyRegAlloc::addInterferencesForArgs() {
392 // get the InSet of root BB
393 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
395 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
396 // add interferences between args and LVars at start
397 addInterference(AI, &InSet, false);
399 if (DEBUG_RA >= RA_DEBUG_Interference)
400 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
405 //----------------------------------------------------------------------------
406 // This method is called after register allocation is complete to set the
407 // allocated registers in the machine code. This code will add register numbers
408 // to MachineOperands that contain a Value. Also it calls target specific
409 // methods to produce caller saving instructions. At the end, it adds all
410 // additional instructions produced by the register allocator to the
411 // instruction stream.
412 //----------------------------------------------------------------------------
414 //-----------------------------
415 // Utility functions used below
416 //-----------------------------
418 InsertBefore(MachineInstr* newMI,
419 MachineBasicBlock& MBB,
420 MachineBasicBlock::iterator& MII)
422 MII = MBB.insert(MII, newMI);
427 InsertAfter(MachineInstr* newMI,
428 MachineBasicBlock& MBB,
429 MachineBasicBlock::iterator& MII)
431 ++MII; // insert before the next instruction
432 MII = MBB.insert(MII, newMI);
436 DeleteInstruction(MachineBasicBlock& MBB,
437 MachineBasicBlock::iterator& MII)
439 MII = MBB.erase(MII);
443 SubstituteInPlace(MachineInstr* newMI,
444 MachineBasicBlock& MBB,
445 MachineBasicBlock::iterator MII)
451 PrependInstructions(std::vector<MachineInstr *> &IBef,
452 MachineBasicBlock& MBB,
453 MachineBasicBlock::iterator& MII,
454 const std::string& msg)
458 MachineInstr* OrigMI = *MII;
459 std::vector<MachineInstr *>::iterator AdIt;
460 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
463 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
464 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
466 InsertBefore(*AdIt, MBB, MII);
472 AppendInstructions(std::vector<MachineInstr *> &IAft,
473 MachineBasicBlock& MBB,
474 MachineBasicBlock::iterator& MII,
475 const std::string& msg)
479 MachineInstr* OrigMI = *MII;
480 std::vector<MachineInstr *>::iterator AdIt;
481 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
484 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
485 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
487 InsertAfter(*AdIt, MBB, MII);
492 static bool MarkAllocatedRegs(MachineInstr* MInst,
494 const TargetRegInfo& MRI)
496 bool instrNeedsSpills = false;
498 // First, set the registers for operands in the machine instruction
499 // if a register was successfully allocated. Do this first because we
500 // will need to know which registers are already used by this instr'n.
502 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
504 MachineOperand& Op = MInst->getOperand(OpNum);
505 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
506 Op.getType() == MachineOperand::MO_CCRegister)
508 const Value *const Val = Op.getVRegValue();
509 if (const LiveRange* LR = LRI.getLiveRangeForValue(Val)) {
510 // Remember if any operand needs spilling
511 instrNeedsSpills |= LR->isMarkedForSpill();
513 // An operand may have a color whether or not it needs spilling
515 MInst->SetRegForOperand(OpNum,
516 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
520 } // for each operand
522 return instrNeedsSpills;
525 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
526 MachineBasicBlock &MBB)
528 MachineInstr* MInst = *MII;
529 unsigned Opcode = MInst->getOpCode();
531 // Reset tmp stack positions so they can be reused for each machine instr.
532 MF.getInfo()->popAllTempValues();
534 // Mark the operands for which regs have been allocated.
535 bool instrNeedsSpills = MarkAllocatedRegs(*MII, LRI, MRI);
538 // Mark that the operands have been updated. Later,
539 // setRelRegsUsedByThisInst() is called to find registers used by each
540 // MachineInst, and it should not be used for an instruction until
541 // this is done. This flag just serves as a sanity check.
542 OperandsColoredMap[MInst] = true;
545 // Now insert caller-saving code before/after the call.
546 // Do this before inserting spill code since some registers must be
547 // used by save/restore and spill code should not use those registers.
549 if (TM.getInstrInfo().isCall(Opcode)) {
550 AddedInstrns &AI = AddedInstrMap[MInst];
551 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
552 MBB.getBasicBlock());
555 // Now insert spill code for remaining operands not allocated to
556 // registers. This must be done even for call return instructions
557 // since those are not handled by the special code above.
558 if (instrNeedsSpills)
559 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
561 MachineOperand& Op = MInst->getOperand(OpNum);
562 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
563 Op.getType() == MachineOperand::MO_CCRegister)
565 const Value* Val = Op.getVRegValue();
566 if (const LiveRange *LR = LRI.getLiveRangeForValue(Val))
567 if (LR->isMarkedForSpill())
568 insertCode4SpilledLR(LR, MII, MBB, OpNum);
570 } // for each operand
573 void PhyRegAlloc::updateMachineCode()
575 // Insert any instructions needed at method entry
576 MachineBasicBlock::iterator MII = MF.front().begin();
577 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF.front(), MII,
578 "At function entry: \n");
579 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
580 "InstrsAfter should be unnecessary since we are just inserting at "
581 "the function entry point here.");
583 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
586 MachineBasicBlock &MBB = *BBI;
588 // Iterate over all machine instructions in BB and mark operands with
589 // their assigned registers or insert spill code, as appropriate.
590 // Also, fix operands of call/return instructions.
591 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
592 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
593 updateInstruction(MII, MBB);
595 // Now, move code out of delay slots of branches and returns if needed.
596 // (Also, move "after" code from calls to the last delay slot instruction.)
597 // Moving code out of delay slots is needed in 2 situations:
598 // (1) If this is a branch and it needs instructions inserted after it,
599 // move any existing instructions out of the delay slot so that the
600 // instructions can go into the delay slot. This only supports the
601 // case that #instrsAfter <= #delay slots.
603 // (2) If any instruction in the delay slot needs
604 // instructions inserted, move it out of the delay slot and before the
605 // branch because putting code before or after it would be VERY BAD!
607 // If the annul bit of the branch is set, neither of these is legal!
608 // If so, we need to handle spill differently but annulling is not yet used.
610 for (MachineBasicBlock::iterator MII = MBB.begin();
611 MII != MBB.end(); ++MII)
612 if (unsigned delaySlots =
613 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
615 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
617 // Check the 2 conditions above:
618 // (1) Does a branch need instructions added after it?
619 // (2) O/w does delay slot instr. need instrns before or after?
620 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
621 TM.getInstrInfo().isReturn(MInst->getOpCode()));
622 bool cond1 = (isBranch &&
623 AddedInstrMap.count(MInst) &&
624 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
625 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
626 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
627 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
631 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
632 "FIXME: Moving an annulled delay slot instruction!");
633 assert(delaySlots==1 &&
634 "InsertBefore does not yet handle >1 delay slots!");
635 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
637 // In case (1), delete it and don't replace with anything!
638 // Otherwise (i.e., case (2) only) replace it with a NOP.
640 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
641 --MII; // reset MII for ++MII of loop
644 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
645 MBB, MII+1); // replace with NOP
648 std::cerr << "\nRegAlloc: Moved instr. with added code: "
650 << " out of delay slots of instr: " << *MInst;
654 // For non-branch instr with delay slots (probably a call), move
655 // InstrAfter to the instr. in the last delay slot.
656 move2DelayedInstr(*MII, *(MII+delaySlots));
659 // Finally iterate over all instructions in BB and insert before/after
661 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
662 MachineInstr *MInst = *MII;
664 // do not process Phis
665 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
668 // if there are any added instructions...
669 if (AddedInstrMap.count(MInst)) {
670 AddedInstrns &CallAI = AddedInstrMap[MInst];
673 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
674 TM.getInstrInfo().isReturn(MInst->getOpCode()));
676 AddedInstrMap[MInst].InstrnsAfter.size() <=
677 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
678 "Cannot put more than #delaySlots instrns after "
679 "branch or return! Need to handle temps differently.");
683 // Temporary sanity checking code to detect whether the same machine
684 // instruction is ever inserted twice before/after a call.
685 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
687 std::set<const MachineInstr*> instrsSeen;
688 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
689 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
690 "Duplicate machine instruction in InstrnsBefore!");
691 instrsSeen.insert(CallAI.InstrnsBefore[i]);
693 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
694 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
695 "Duplicate machine instruction in InstrnsBefore/After!");
696 instrsSeen.insert(CallAI.InstrnsAfter[i]);
700 // Now add the instructions before/after this MI.
701 // We do this here to ensure that spill for an instruction is inserted
702 // as close as possible to an instruction (see above insertCode4Spill)
704 if (! CallAI.InstrnsBefore.empty())
705 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
707 if (! CallAI.InstrnsAfter.empty())
708 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
710 } // if there are any added instructions
712 } // for each machine instruction
719 //----------------------------------------------------------------------------
720 // This method inserts spill code for AN operand whose LR was spilled.
721 // This method may be called several times for a single machine instruction
722 // if it contains many spilled operands. Each time it is called, it finds
723 // a register which is not live at that instruction and also which is not
724 // used by other spilled operands of the same instruction. Then it uses
725 // this register temporarily to accommodate the spilled value.
726 //----------------------------------------------------------------------------
728 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
729 MachineBasicBlock::iterator& MII,
730 MachineBasicBlock &MBB,
731 const unsigned OpNum) {
733 MachineInstr *MInst = *MII;
734 const BasicBlock *BB = MBB.getBasicBlock();
736 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
737 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
738 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
739 "Return value of a ret must be handled elsewhere");
741 MachineOperand& Op = MInst->getOperand(OpNum);
742 bool isDef = Op.opIsDefOnly();
743 bool isDefAndUse = Op.opIsDefAndUse();
744 unsigned RegType = MRI.getRegTypeForLR(LR);
745 int SpillOff = LR->getSpillOffFromFP();
746 RegClass *RC = LR->getRegClass();
748 // Get the live-variable set to find registers free before this instr.
749 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
752 // If this instr. is in the delay slot of a branch or return, we need to
753 // include all live variables before that branch or return -- we don't want to
754 // trample those! Verify that the set is included in the LV set before MInst.
756 if (MII != MBB.begin()) {
757 MachineInstr *PredMI = *(MII-1);
758 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
759 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
760 .empty() && "Live-var set before branch should be included in "
761 "live-var set of each delay slot instruction!");
765 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
767 std::vector<MachineInstr*> MIBef, MIAft;
768 std::vector<MachineInstr*> AdIMid;
770 // Choose a register to hold the spilled value, if one was not preallocated.
771 // This may insert code before and after MInst to free up the value. If so,
772 // this code should be first/last in the spill sequence before/after MInst.
773 int TmpRegU=(LR->hasColor()
774 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
775 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
777 // Set the operand first so that it this register does not get used
778 // as a scratch register for later calls to getUsableUniRegAtMI below
779 MInst->SetRegForOperand(OpNum, TmpRegU);
781 // get the added instructions for this instruction
782 AddedInstrns &AI = AddedInstrMap[MInst];
784 // We may need a scratch register to copy the spilled value to/from memory.
785 // This may itself have to insert code to free up a scratch register.
786 // Any such code should go before (after) the spill code for a load (store).
787 // The scratch reg is not marked as used because it is only used
788 // for the copy and not used across MInst.
789 int scratchRegType = -1;
791 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
793 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
794 MInst, MIBef, MIAft);
795 assert(scratchReg != MRI.getInvalidRegNum());
798 if (!isDef || isDefAndUse) {
799 // for a USE, we have to load the value of LR from stack to a TmpReg
800 // and use the TmpReg as one operand of instruction
802 // actual loading instruction(s)
803 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
804 RegType, scratchReg);
806 // the actual load should be after the instructions to free up TmpRegU
807 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
811 if (isDef || isDefAndUse) { // if this is a Def
812 // for a DEF, we have to store the value produced by this instruction
813 // on the stack position allocated for this LR
815 // actual storing instruction(s)
816 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
817 RegType, scratchReg);
819 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
822 // Finally, insert the entire spill code sequences before/after MInst
823 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
824 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
827 std::cerr << "\nFor Inst:\n " << *MInst;
828 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
829 std::cerr << "; added Instructions:";
830 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
831 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
837 //----------------------------------------------------------------------------
838 // This method inserts caller saving/restoring instructions before/after
839 // a call machine instruction. The caller saving/restoring instructions are
841 // ** caller saving instructions
842 // other instructions inserted for the call by ColorCallArg
844 // other instructions inserted for the call ColorCallArg
845 // ** caller restoring instructions
846 //----------------------------------------------------------------------------
849 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
850 std::vector<MachineInstr*> &instrnsAfter,
851 MachineInstr *CallMI,
852 const BasicBlock *BB)
854 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
856 // has set to record which registers were saved/restored
858 hash_set<unsigned> PushedRegSet;
860 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
862 // if the call is to a instrumentation function, do not insert save and
863 // restore instructions the instrumentation function takes care of save
864 // restore for volatile regs.
866 // FIXME: this should be made general, not specific to the reoptimizer!
868 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
869 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
871 // Now check if the call has a return value (using argDesc) and if so,
872 // find the LR of the TmpInstruction representing the return value register.
873 // (using the last or second-last *implicit operand* of the call MI).
874 // Insert it to to the PushedRegSet since we must not save that register
875 // and restore it after the call.
876 // We do this because, we look at the LV set *after* the instruction
877 // to determine, which LRs must be saved across calls. The return value
878 // of the call is live in this set - but we must not save/restore it.
880 if (const Value *origRetVal = argDesc->getReturnValue()) {
881 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
882 (argDesc->getIndirectFuncPtr()? 1 : 2));
883 const TmpInstruction* tmpRetVal =
884 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
885 assert(tmpRetVal->getOperand(0) == origRetVal &&
886 tmpRetVal->getType() == origRetVal->getType() &&
887 "Wrong implicit ref?");
888 LiveRange *RetValLR = LRI.getLiveRangeForValue(tmpRetVal);
889 assert(RetValLR && "No LR for RetValue of call");
891 if (! RetValLR->isMarkedForSpill())
892 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
893 RetValLR->getColor()));
896 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
897 ValueSet::const_iterator LIt = LVSetAft.begin();
899 // for each live var in live variable set after machine inst
900 for( ; LIt != LVSetAft.end(); ++LIt) {
902 // get the live range corresponding to live var
903 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt);
905 // LR can be null if it is a const since a const
906 // doesn't have a dominating def - see Assumptions above
909 if(! LR->isMarkedForSpill()) {
911 assert(LR->hasColor() && "LR is neither spilled nor colored?");
912 unsigned RCID = LR->getRegClassID();
913 unsigned Color = LR->getColor();
915 if (MRI.isRegVolatile(RCID, Color) ) {
917 //if the function is special LLVM function,
918 //And the register is not modified by call, don't save and restore
919 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
922 // if the value is in both LV sets (i.e., live before and after
923 // the call machine instruction)
925 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
927 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
929 // if we haven't already pushed that register
931 unsigned RegType = MRI.getRegTypeForLR(LR);
933 // Now get two instructions - to push on stack and pop from stack
934 // and add them to InstrnsBefore and InstrnsAfter of the
938 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
940 //---- Insert code for pushing the reg on stack ----------
942 std::vector<MachineInstr*> AdIBef, AdIAft;
944 // We may need a scratch register to copy the saved value
945 // to/from memory. This may itself have to insert code to
946 // free up a scratch register. Any such code should go before
947 // the save code. The scratch register, if any, is by default
948 // temporary and not "used" by the instruction unless the
949 // copy code itself decides to keep the value in the scratch reg.
950 int scratchRegType = -1;
952 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
953 { // Find a register not live in the LVSet before CallMI
954 const ValueSet &LVSetBef =
955 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
956 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
957 CallMI, AdIBef, AdIAft);
958 assert(scratchReg != MRI.getInvalidRegNum());
961 if (AdIBef.size() > 0)
962 instrnsBefore.insert(instrnsBefore.end(),
963 AdIBef.begin(), AdIBef.end());
965 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
966 StackOff, RegType, scratchReg);
968 if (AdIAft.size() > 0)
969 instrnsBefore.insert(instrnsBefore.end(),
970 AdIAft.begin(), AdIAft.end());
972 //---- Insert code for popping the reg from the stack ----------
976 // We may need a scratch register to copy the saved value
977 // from memory. This may itself have to insert code to
978 // free up a scratch register. Any such code should go
979 // after the save code. As above, scratch is not marked "used".
983 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
984 { // Find a register not live in the LVSet after CallMI
985 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
986 CallMI, AdIBef, AdIAft);
987 assert(scratchReg != MRI.getInvalidRegNum());
990 if (AdIBef.size() > 0)
991 instrnsAfter.insert(instrnsAfter.end(),
992 AdIBef.begin(), AdIBef.end());
994 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
995 Reg, RegType, scratchReg);
997 if (AdIAft.size() > 0)
998 instrnsAfter.insert(instrnsAfter.end(),
999 AdIAft.begin(), AdIAft.end());
1001 PushedRegSet.insert(Reg);
1004 std::cerr << "\nFor call inst:" << *CallMI;
1005 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1006 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1007 std::mem_fun(&MachineInstr::dump));
1008 std::cerr << " -and After:\n\t ";
1009 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1010 std::mem_fun(&MachineInstr::dump));
1012 } // if not already pushed
1014 } // if LR has a volatile color
1016 } // if LR has color
1018 } // if there is a LR for Var
1020 } // for each value in the LV set after instruction
1024 //----------------------------------------------------------------------------
1025 // We can use the following method to get a temporary register to be used
1026 // BEFORE any given machine instruction. If there is a register available,
1027 // this method will simply return that register and set MIBef = MIAft = NULL.
1028 // Otherwise, it will return a register and MIAft and MIBef will contain
1029 // two instructions used to free up this returned register.
1030 // Returned register number is the UNIFIED register number
1031 //----------------------------------------------------------------------------
1033 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
1034 const ValueSet *LVSetBef,
1035 MachineInstr *MInst,
1036 std::vector<MachineInstr*>& MIBef,
1037 std::vector<MachineInstr*>& MIAft) {
1039 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
1041 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
1044 // we couldn't find an unused register. Generate code to free up a reg by
1045 // saving it on stack and restoring after the instruction
1047 int TmpOff = MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
1049 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
1051 // Check if we need a scratch register to copy this register to memory.
1052 int scratchRegType = -1;
1053 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
1055 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
1056 MInst, MIBef, MIAft);
1057 assert(scratchReg != MRI.getInvalidRegNum());
1059 // We may as well hold the value in the scratch register instead
1060 // of copying it to memory and back. But we have to mark the
1061 // register as used by this instruction, so it does not get used
1062 // as a scratch reg. by another operand or anyone else.
1063 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
1064 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
1065 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
1068 { // the register can be copied directly to/from memory so do it.
1069 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
1070 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
1078 //----------------------------------------------------------------------------
1079 // This method is called to get a new unused register that can be used
1080 // to accommodate a temporary value. This method may be called several times
1081 // for a single machine instruction. Each time it is called, it finds a
1082 // register which is not live at that instruction and also which is not used
1083 // by other spilled operands of the same instruction. Return register number
1084 // is relative to the register class, NOT the unified number.
1085 //----------------------------------------------------------------------------
1087 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
1089 const MachineInstr *MInst,
1090 const ValueSet* LVSetBef) {
1092 RC->clearColorsUsed(); // Reset array
1094 if (LVSetBef == NULL) {
1095 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
1096 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1099 ValueSet::const_iterator LIt = LVSetBef->begin();
1101 // for each live var in live variable set after machine inst
1102 for ( ; LIt != LVSetBef->end(); ++LIt) {
1104 // get the live range corresponding to live var, and its RegClass
1105 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
1107 // LR can be null if it is a const since a const
1108 // doesn't have a dominating def - see Assumptions above
1109 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1110 RC->markColorsUsed(LRofLV->getColor(),
1111 MRI.getRegTypeForLR(LRofLV), RegType);
1114 // It is possible that one operand of this MInst was already spilled
1115 // and it received some register temporarily. If that's the case,
1116 // it is recorded in machine operand. We must skip such registers.
1118 setRelRegsUsedByThisInst(RC, RegType, MInst);
1120 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1122 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1128 //----------------------------------------------------------------------------
1129 // Get any other register in a register class, other than what is used
1130 // by operands of a machine instruction. Returns the unified reg number.
1131 //----------------------------------------------------------------------------
1132 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
1134 const MachineInstr *MInst) {
1135 RC->clearColorsUsed();
1137 setRelRegsUsedByThisInst(RC, RegType, MInst);
1139 // find the first unused color
1140 int unusedReg = RC->getUnusedColor(RegType);
1141 assert(unusedReg >= 0 &&
1142 "FATAL: No free register could be found in reg class!!");
1144 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1148 //----------------------------------------------------------------------------
1149 // This method modifies the IsColorUsedArr of the register class passed to it.
1150 // It sets the bits corresponding to the registers used by this machine
1151 // instructions. Both explicit and implicit operands are set.
1152 //----------------------------------------------------------------------------
1154 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1155 const TargetRegInfo &TRI) {
1156 unsigned classId = 0;
1157 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1158 if (RC->getID() == classId)
1159 RC->markColorsUsed(classRegNum, RegType, RegType);
1162 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1163 const MachineInstr *MI)
1165 assert(OperandsColoredMap[MI] == true &&
1166 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1167 "are marked for an instruction.");
1169 // Add the registers already marked as used by the instruction.
1170 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1171 if (MI->getOperand(i).hasAllocatedReg())
1172 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1174 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1175 if (MI->getImplicitOp(i).hasAllocatedReg())
1176 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1179 // Add all of the scratch registers that are used to save values across the
1180 // instruction (e.g., for saving state register values).
1181 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1182 IR = ScratchRegsUsed.equal_range(MI);
1183 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1184 markRegisterUsed(I->second, RC, RegType, MRI);
1186 // If there are implicit references, mark their allocated regs as well
1188 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1189 if (const LiveRange*
1190 LRofImpRef = LRI.getLiveRangeForValue(MI->getImplicitRef(z)))
1191 if (LRofImpRef->hasColor())
1192 // this implicit reference is in a LR that received a color
1193 RC->markColorsUsed(LRofImpRef->getColor(),
1194 MRI.getRegTypeForLR(LRofImpRef), RegType);
1198 //----------------------------------------------------------------------------
1199 // If there are delay slots for an instruction, the instructions
1200 // added after it must really go after the delayed instruction(s).
1201 // So, we move the InstrAfter of that instruction to the
1202 // corresponding delayed instruction using the following method.
1203 //----------------------------------------------------------------------------
1205 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1206 const MachineInstr *DelayedMI)
1208 // "added after" instructions of the original instr
1209 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1211 if (DEBUG_RA && OrigAft.size() > 0) {
1212 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1213 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1216 // "added after" instructions of the delayed instr
1217 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1219 // go thru all the "added after instructions" of the original instruction
1220 // and append them to the "added after instructions" of the delayed
1222 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1224 // empty the "added after instructions" of the original instruction
1228 //----------------------------------------------------------------------------
1229 // This method prints the code with registers after register allocation is
1231 //----------------------------------------------------------------------------
1232 void PhyRegAlloc::printMachineCode()
1235 std::cerr << "\n;************** Function " << Fn->getName()
1236 << " *****************\n";
1238 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
1239 BBI != BBE; ++BBI) {
1240 std::cerr << "\n"; printLabel(BBI->getBasicBlock()); std::cerr << ": ";
1242 // get the iterator for machine instructions
1243 MachineBasicBlock& MBB = *BBI;
1244 MachineBasicBlock::iterator MII = MBB.begin();
1246 // iterate over all the machine instructions in BB
1247 for ( ; MII != MBB.end(); ++MII) {
1248 MachineInstr *MInst = *MII;
1250 std::cerr << "\n\t";
1251 std::cerr << TM.getInstrInfo().getName(MInst->getOpCode());
1253 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1254 MachineOperand& Op = MInst->getOperand(OpNum);
1256 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
1257 Op.getType() == MachineOperand::MO_CCRegister /*||
1258 Op.getType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1260 const Value *const Val = Op.getVRegValue () ;
1261 // ****this code is temporary till NULL Values are fixed
1263 std::cerr << "\t<*NULL*>";
1267 // if a label or a constant
1268 if (isa<BasicBlock>(Val)) {
1269 std::cerr << "\t"; printLabel( Op.getVRegValue () );
1271 // else it must be a register value
1272 const int RegNum = Op.getAllocatedRegNum();
1274 std::cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1275 if (Val->hasName() )
1276 std::cerr << "(" << Val->getName() << ")";
1278 std::cerr << "(" << Val << ")";
1280 if (Op.opIsDefOnly() || Op.opIsDefAndUse())
1283 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1285 if (LROfVal->hasSpillOffset() )
1290 else if (Op.getType() == MachineOperand::MO_MachineRegister) {
1291 std::cerr << "\t%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1295 std::cerr << "\t" << Op; // use dump field
1300 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1301 if (NumOfImpRefs > 0) {
1302 std::cerr << "\tImplicit:";
1304 for (unsigned z=0; z < NumOfImpRefs; z++)
1305 std::cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1308 } // for all machine instructions
1318 //----------------------------------------------------------------------------
1320 //----------------------------------------------------------------------------
1321 void PhyRegAlloc::colorIncomingArgs()
1323 MRI.colorMethodArgs(Fn, LRI, AddedInstrAtEntry.InstrnsBefore,
1324 AddedInstrAtEntry.InstrnsAfter);
1328 //----------------------------------------------------------------------------
1329 // Used to generate a label for a basic block
1330 //----------------------------------------------------------------------------
1331 void PhyRegAlloc::printLabel(const Value *Val) {
1333 std::cerr << Val->getName();
1335 std::cerr << "Label" << Val;
1339 //----------------------------------------------------------------------------
1340 // This method calls setSugColorUsable method of each live range. This
1341 // will determine whether the suggested color of LR is really usable.
1342 // A suggested color is not usable when the suggested color is volatile
1343 // AND when there are call interferences
1344 //----------------------------------------------------------------------------
1346 void PhyRegAlloc::markUnusableSugColors()
1348 // hash map iterator
1349 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1350 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1352 for (; HMI != HMIEnd ; ++HMI ) {
1354 LiveRange *L = HMI->second; // get the LiveRange
1356 if (L->hasSuggestedColor()) {
1357 int RCID = L->getRegClass()->getID();
1358 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1359 L->isCallInterference() )
1360 L->setSuggestedColorUsable( false );
1362 L->setSuggestedColorUsable( true );
1364 } // if L->hasSuggestedColor()
1366 } // for all LR's in hash map
1371 //----------------------------------------------------------------------------
1372 // The following method will set the stack offsets of the live ranges that
1373 // are decided to be spilled. This must be called just after coloring the
1374 // LRs using the graph coloring algo. For each live range that is spilled,
1375 // this method allocate a new spill position on the stack.
1376 //----------------------------------------------------------------------------
1378 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1379 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1381 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1382 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1384 for ( ; HMI != HMIEnd ; ++HMI) {
1385 if (HMI->first && HMI->second) {
1386 LiveRange *L = HMI->second; // get the LiveRange
1387 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1388 int stackOffset = MF.getInfo()->allocateSpilledValue(Type::LongTy);
1389 L->setSpillOffFromFP(stackOffset);
1391 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1392 << ": stack-offset = " << stackOffset << "\n";
1395 } // for all LR's in hash map
1399 //----------------------------------------------------------------------------
1400 // The entry pont to Register Allocation
1401 //----------------------------------------------------------------------------
1403 void PhyRegAlloc::allocateRegisters()
1406 // make sure that we put all register classes into the RegClassList
1407 // before we call constructLiveRanges (now done in the constructor of
1408 // PhyRegAlloc class).
1410 LRI.constructLiveRanges(); // create LR info
1412 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1413 LRI.printLiveRanges();
1415 createIGNodeListsAndIGs(); // create IGNode list and IGs
1417 buildInterferenceGraphs(); // build IGs in all reg classes
1420 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1421 // print all LRs in all reg classes
1422 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1423 RegClassList[rc]->printIGNodeList();
1425 // print IGs in all register classes
1426 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1427 RegClassList[rc]->printIG();
1430 LRI.coalesceLRs(); // coalesce all live ranges
1432 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1433 // print all LRs in all reg classes
1434 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1435 RegClassList[rc]->printIGNodeList();
1437 // print IGs in all register classes
1438 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1439 RegClassList[rc]->printIG();
1443 // mark un-usable suggested color before graph coloring algorithm.
1444 // When this is done, the graph coloring algo will not reserve
1445 // suggested color unnecessarily - they can be used by another LR
1447 markUnusableSugColors();
1449 // color all register classes using the graph coloring algo
1450 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1451 RegClassList[rc]->colorAllRegs();
1453 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1454 // a position for such spilled LRs
1456 allocateStackSpace4SpilledLRs();
1458 // Reset the temp. area on the stack before use by the first instruction.
1459 // This will also happen after updating each instruction.
1460 MF.getInfo()->popAllTempValues();
1462 // color incoming args - if the correct color was not received
1463 // insert code to copy to the correct register
1465 colorIncomingArgs();
1467 // Now update the machine code with register names and add any
1468 // additional code inserted by the register allocator to the instruction
1471 updateMachineCode();
1474 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";