1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "RegAllocCommon.h"
10 #include "llvm/CodeGen/IGNode.h"
11 #include "llvm/CodeGen/PhyRegAlloc.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"
33 RegAllocDebugLevel_t DEBUG_RA;
35 static cl::opt<RegAllocDebugLevel_t, true>
36 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
37 cl::desc("enable register allocation debugging information"),
39 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
40 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
41 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
42 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
43 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
44 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
47 //----------------------------------------------------------------------------
48 // RegisterAllocation pass front end...
49 //----------------------------------------------------------------------------
51 class RegisterAllocator : public FunctionPass {
52 TargetMachine &Target;
54 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
56 const char *getPassName() const { return "Register Allocation"; }
58 bool runOnFunction(Function &F) {
60 cerr << "\n********* Function "<< F.getName() << " ***********\n";
62 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
63 &getAnalysis<LoopInfo>());
64 PRA.allocateRegisters();
66 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<LoopInfo>();
72 AU.addRequired<FunctionLiveVarInfo>();
77 Pass *getRegisterAllocator(TargetMachine &T) {
78 return new RegisterAllocator(T);
81 //----------------------------------------------------------------------------
82 // Constructor: Init local composite objects and create register classes.
83 //----------------------------------------------------------------------------
84 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
85 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
86 : TM(tm), Fn(F), MF(MachineFunction::get(F)), LVI(Lvi),
87 LRI(F, tm, RegClassList), MRI(tm.getRegInfo()),
88 NumOfRegClasses(MRI.getNumOfRegClasses()), LoopDepthCalc(LDC) {
90 // create each RegisterClass and put in RegClassList
92 for (unsigned rc=0; rc != NumOfRegClasses; rc++)
93 RegClassList.push_back(new RegClass(F, &tm.getRegInfo(),
94 MRI.getMachineRegClass(rc)));
98 //----------------------------------------------------------------------------
99 // Destructor: Deletes register classes
100 //----------------------------------------------------------------------------
101 PhyRegAlloc::~PhyRegAlloc() {
102 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
103 delete RegClassList[rc];
105 AddedInstrMap.clear();
108 //----------------------------------------------------------------------------
109 // This method initally creates interference graphs (one in each reg class)
110 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
111 //----------------------------------------------------------------------------
112 void PhyRegAlloc::createIGNodeListsAndIGs() {
113 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "Creating LR lists ...\n";
116 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
119 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
121 for (; HMI != HMIEnd ; ++HMI ) {
123 LiveRange *L = HMI->second; // get the LiveRange
126 cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
127 << RAV(HMI->first) << "****\n";
131 // if the Value * is not null, and LR is not yet written to the IGNodeList
132 if (!(L->getUserIGNode()) ) {
133 RegClass *const RC = // RegClass of first value in the LR
134 RegClassList[ L->getRegClass()->getID() ];
135 RC->addLRToIG(L); // add this LR to an IG
141 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
142 RegClassList[rc]->createInterferenceGraph();
144 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
148 //----------------------------------------------------------------------------
149 // This method will add all interferences at for a given instruction.
150 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
151 // class as that of live var. The live var passed to this function is the
152 // LVset AFTER the instruction
153 //----------------------------------------------------------------------------
155 void PhyRegAlloc::addInterference(const Value *Def,
156 const ValueSet *LVSet,
159 ValueSet::const_iterator LIt = LVSet->begin();
161 // get the live range of instruction
163 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
165 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
166 assert( IGNodeOfDef );
168 RegClass *const RCOfDef = LROfDef->getRegClass();
170 // for each live var in live variable set
172 for ( ; LIt != LVSet->end(); ++LIt) {
174 if (DEBUG_RA >= RA_DEBUG_Verbose)
175 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
177 // get the live range corresponding to live var
179 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
181 // LROfVar can be null if it is a const since a const
182 // doesn't have a dominating def - see Assumptions above
185 if (LROfDef != LROfVar) // do not set interf for same LR
186 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
187 RCOfDef->setInterference( LROfDef, LROfVar);
193 //----------------------------------------------------------------------------
194 // For a call instruction, this method sets the CallInterference flag in
195 // the LR of each variable live int the Live Variable Set live after the
196 // call instruction (except the return value of the call instruction - since
197 // the return value does not interfere with that call itself).
198 //----------------------------------------------------------------------------
200 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
201 const ValueSet *LVSetAft) {
203 if (DEBUG_RA >= RA_DEBUG_Interference)
204 cerr << "\n For call inst: " << *MInst;
206 // for each live var in live variable set after machine inst
208 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
209 LIt != LEnd; ++LIt) {
211 // get the live range corresponding to live var
213 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
215 // LR can be null if it is a const since a const
216 // doesn't have a dominating def - see Assumptions above
219 if (DEBUG_RA >= RA_DEBUG_Interference) {
220 cerr << "\n\tLR after Call: ";
223 LR->setCallInterference();
224 if (DEBUG_RA >= RA_DEBUG_Interference) {
225 cerr << "\n ++After adding call interference for LR: " ;
232 // Now find the LR of the return value of the call
233 // We do this because, we look at the LV set *after* the instruction
234 // to determine, which LRs must be saved across calls. The return value
235 // of the call is live in this set - but it does not interfere with call
236 // (i.e., we can allocate a volatile register to the return value)
238 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
240 if (const Value *RetVal = argDesc->getReturnValue()) {
241 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
242 assert( RetValLR && "No LR for RetValue of call");
243 RetValLR->clearCallInterference();
246 // If the CALL is an indirect call, find the LR of the function pointer.
247 // That has a call interference because it conflicts with outgoing args.
248 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
249 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
250 assert( AddrValLR && "No LR for indirect addr val of call");
251 AddrValLR->setCallInterference();
259 //----------------------------------------------------------------------------
260 // This method will walk thru code and create interferences in the IG of
261 // each RegClass. Also, this method calculates the spill cost of each
262 // Live Range (it is done in this method to save another pass over the code).
263 //----------------------------------------------------------------------------
264 void PhyRegAlloc::buildInterferenceGraphs()
267 if (DEBUG_RA >= RA_DEBUG_Interference)
268 cerr << "Creating interference graphs ...\n";
270 unsigned BBLoopDepthCost;
271 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
273 const MachineBasicBlock &MBB = *BBI;
274 const BasicBlock *BB = MBB.getBasicBlock();
276 // find the 10^(loop_depth) of this BB
278 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
280 // get the iterator for machine instructions
282 MachineBasicBlock::const_iterator MII = MBB.begin();
284 // iterate over all the machine instructions in BB
286 for ( ; MII != MBB.end(); ++MII) {
287 const MachineInstr *MInst = *MII;
289 // get the LV set after the instruction
291 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
292 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
295 // set the isCallInterference flag of each live range wich extends
296 // accross this call instruction. This information is used by graph
297 // coloring algo to avoid allocating volatile colors to live ranges
298 // that span across calls (since they have to be saved/restored)
300 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.isDefOnly() || OpI.isDefAndUse()) // create a new LR since 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 for (unsigned z=0; z < NumOfImpRefs; z++)
328 if (MInst->getImplicitOp(z).opIsDefOnly() ||
329 MInst->getImplicitOp(z).opIsDefAndUse())
330 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
332 } // for all machine instructions in BB
333 } // for all BBs in function
336 // add interferences for function arguments. Since there are no explict
337 // defs in the function for args, we have to add them manually
339 addInterferencesForArgs();
341 if (DEBUG_RA >= RA_DEBUG_Interference)
342 cerr << "Interference graphs calculated!\n";
347 //--------------------------------------------------------------------------
348 // Pseudo instructions will be exapnded to multiple instructions by the
349 // assembler. Consequently, all the opernds must get distinct registers.
350 // Therefore, we mark all operands of a pseudo instruction as they interfere
352 //--------------------------------------------------------------------------
353 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
355 bool setInterf = false;
357 // iterate over MI operands to find defs
359 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
360 ItE = MInst->end(); It1 != ItE; ++It1) {
361 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
362 assert((LROfOp1 || !It1.isUseOnly())&& "No LR for Def in PSEUDO insruction");
364 MachineInstr::const_val_op_iterator It2 = It1;
365 for (++It2; It2 != ItE; ++It2) {
366 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
369 RegClass *RCOfOp1 = LROfOp1->getRegClass();
370 RegClass *RCOfOp2 = LROfOp2->getRegClass();
372 if (RCOfOp1 == RCOfOp2 ){
373 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
377 } // for all other defs in machine instr
378 } // for all operands in an instruction
380 if (!setInterf && MInst->getNumOperands() > 2) {
381 cerr << "\nInterf not set for any operand in pseudo instr:\n";
383 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
389 //----------------------------------------------------------------------------
390 // This method will add interferences for incoming arguments to a function.
391 //----------------------------------------------------------------------------
393 void PhyRegAlloc::addInterferencesForArgs() {
394 // get the InSet of root BB
395 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
397 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
398 // add interferences between args and LVars at start
399 addInterference(AI, &InSet, false);
401 if (DEBUG_RA >= RA_DEBUG_Interference)
402 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
407 //----------------------------------------------------------------------------
408 // This method is called after register allocation is complete to set the
409 // allocated reisters in the machine code. This code will add register numbers
410 // to MachineOperands that contain a Value. Also it calls target specific
411 // methods to produce caller saving instructions. At the end, it adds all
412 // additional instructions produced by the register allocator to the
413 // instruction stream.
414 //----------------------------------------------------------------------------
416 //-----------------------------
417 // Utility functions used below
418 //-----------------------------
420 InsertBefore(MachineInstr* newMI,
421 MachineBasicBlock& MBB,
422 MachineBasicBlock::iterator& MII)
424 MII = MBB.insert(MII, newMI);
429 InsertAfter(MachineInstr* newMI,
430 MachineBasicBlock& MBB,
431 MachineBasicBlock::iterator& MII)
433 ++MII; // insert before the next instruction
434 MII = MBB.insert(MII, newMI);
438 DeleteInstruction(MachineBasicBlock& MBB,
439 MachineBasicBlock::iterator& MII)
441 MII = MBB.erase(MII);
445 SubstituteInPlace(MachineInstr* newMI,
446 MachineBasicBlock& MBB,
447 MachineBasicBlock::iterator MII)
453 PrependInstructions(vector<MachineInstr *> &IBef,
454 MachineBasicBlock& MBB,
455 MachineBasicBlock::iterator& MII,
456 const std::string& msg)
460 MachineInstr* OrigMI = *MII;
461 std::vector<MachineInstr *>::iterator AdIt;
462 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
465 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
466 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
468 InsertBefore(*AdIt, MBB, MII);
474 AppendInstructions(std::vector<MachineInstr *> &IAft,
475 MachineBasicBlock& MBB,
476 MachineBasicBlock::iterator& MII,
477 const std::string& msg)
481 MachineInstr* OrigMI = *MII;
482 std::vector<MachineInstr *>::iterator AdIt;
483 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
486 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
487 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
489 InsertAfter(*AdIt, MBB, MII);
494 static bool MarkAllocatedRegs(MachineInstr* MInst,
496 const TargetRegInfo& MRI)
498 bool instrNeedsSpills = false;
500 // First, set the registers for operands in the machine instruction
501 // if a register was successfully allocated. Do this first because we
502 // will need to know which registers are already used by this instr'n.
504 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
506 MachineOperand& Op = MInst->getOperand(OpNum);
507 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
508 Op.getType() == MachineOperand::MO_CCRegister)
510 const Value *const Val = Op.getVRegValue();
511 if (const LiveRange* LR = LRI.getLiveRangeForValue(Val)) {
512 // Remember if any operand needs spilling
513 instrNeedsSpills |= LR->isMarkedForSpill();
515 // An operand may have a color whether or not it needs spilling
517 MInst->SetRegForOperand(OpNum,
518 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
522 } // for each operand
524 return instrNeedsSpills;
527 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
528 MachineBasicBlock &MBB)
530 MachineInstr* MInst = *MII;
531 unsigned Opcode = MInst->getOpCode();
533 // Reset tmp stack positions so they can be reused for each machine instr.
534 MF.getInfo()->popAllTempValues();
536 // Mark the operands for which regs have been allocated.
537 bool instrNeedsSpills = MarkAllocatedRegs(*MII, LRI, MRI);
540 // Mark that the operands have been updated. Later,
541 // setRelRegsUsedByThisInst() is called to find registers used by each
542 // MachineInst, and it should not be used for an instruction until
543 // this is done. This flag just serves as a sanity check.
544 OperandsColoredMap[MInst] = true;
547 // Now insert caller-saving code before/after the call.
548 // Do this before inserting spill code since some registers must be
549 // used by save/restore and spill code should not use those registers.
551 if (TM.getInstrInfo().isCall(Opcode)) {
552 AddedInstrns &AI = AddedInstrMap[MInst];
553 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
554 MBB.getBasicBlock());
557 // Now insert spill code for remaining operands not allocated to
558 // registers. This must be done even for call return instructions
559 // since those are not handled by the special code above.
560 if (instrNeedsSpills)
561 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
563 MachineOperand& Op = MInst->getOperand(OpNum);
564 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
565 Op.getType() == MachineOperand::MO_CCRegister)
567 const Value* Val = Op.getVRegValue();
568 if (const LiveRange *LR = LRI.getLiveRangeForValue(Val))
569 if (LR->isMarkedForSpill())
570 insertCode4SpilledLR(LR, MII, MBB, OpNum);
572 } // for each operand
575 void PhyRegAlloc::updateMachineCode()
577 // Insert any instructions needed at method entry
578 MachineBasicBlock::iterator MII = MF.front().begin();
579 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF.front(), MII,
580 "At function entry: \n");
581 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
582 "InstrsAfter should be unnecessary since we are just inserting at "
583 "the function entry point here.");
585 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
588 MachineBasicBlock &MBB = *BBI;
590 // Iterate over all machine instructions in BB and mark operands with
591 // their assigned registers or insert spill code, as appropriate.
592 // Also, fix operands of call/return instructions.
593 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
594 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
595 updateInstruction(MII, MBB);
597 // Now, move code out of delay slots of branches and returns if needed.
598 // (Also, move "after" code from calls to the last delay slot instruction.)
599 // Moving code out of delay slots is needed in 2 situations:
600 // (1) If this is a branch and it needs instructions inserted after it,
601 // move any existing instructions out of the delay slot so that the
602 // instructions can go into the delay slot. This only supports the
603 // case that #instrsAfter <= #delay slots.
605 // (2) If any instruction in the delay slot needs
606 // instructions inserted, move it out of the delay slot and before the
607 // branch because putting code before or after it would be VERY BAD!
609 // If the annul bit of the branch is set, neither of these is legal!
610 // If so, we need to handle spill differently but annulling is not yet used.
612 for (MachineBasicBlock::iterator MII = MBB.begin();
613 MII != MBB.end(); ++MII)
614 if (unsigned delaySlots =
615 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
617 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
619 // Check the 2 conditions above:
620 // (1) Does a branch need instructions added after it?
621 // (2) O/w does delay slot instr. need instrns before or after?
622 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
623 TM.getInstrInfo().isReturn(MInst->getOpCode()));
624 bool cond1 = (isBranch &&
625 AddedInstrMap.count(MInst) &&
626 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
627 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
628 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
629 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
633 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
634 "FIXME: Moving an annulled delay slot instruction!");
635 assert(delaySlots==1 &&
636 "InsertBefore does not yet handle >1 delay slots!");
637 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
639 // In case (1), delete it and don't replace with anything!
640 // Otherwise (i.e., case (2) only) replace it with a NOP.
642 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
643 --MII; // reset MII for ++MII of loop
646 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
647 MBB, MII+1); // replace with NOP
650 cerr << "\nRegAlloc: Moved instr. with added code: "
652 << " out of delay slots of instr: " << *MInst;
656 // For non-branch instr with delay slots (probably a call), move
657 // InstrAfter to the instr. in the last delay slot.
658 move2DelayedInstr(*MII, *(MII+delaySlots));
661 // Finally iterate over all instructions in BB and insert before/after
663 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
664 MachineInstr *MInst = *MII;
666 // do not process Phis
667 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
670 // if there are any added instructions...
671 if (AddedInstrMap.count(MInst)) {
672 AddedInstrns &CallAI = AddedInstrMap[MInst];
675 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
676 TM.getInstrInfo().isReturn(MInst->getOpCode()));
678 AddedInstrMap[MInst].InstrnsAfter.size() <=
679 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
680 "Cannot put more than #delaySlots instrns after "
681 "branch or return! Need to handle temps differently.");
685 // Temporary sanity checking code to detect whether the same machine
686 // instruction is ever inserted twice before/after a call.
687 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
689 std::set<const MachineInstr*> instrsSeen;
690 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
691 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
692 "Duplicate machine instruction in InstrnsBefore!");
693 instrsSeen.insert(CallAI.InstrnsBefore[i]);
695 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
696 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
697 "Duplicate machine instruction in InstrnsBefore/After!");
698 instrsSeen.insert(CallAI.InstrnsAfter[i]);
702 // Now add the instructions before/after this MI.
703 // We do this here to ensure that spill for an instruction is inserted
704 // as close as possible to an instruction (see above insertCode4Spill)
706 if (! CallAI.InstrnsBefore.empty())
707 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
709 if (! CallAI.InstrnsAfter.empty())
710 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
712 } // if there are any added instructions
714 } // for each machine instruction
721 //----------------------------------------------------------------------------
722 // This method inserts spill code for AN operand whose LR was spilled.
723 // This method may be called several times for a single machine instruction
724 // if it contains many spilled operands. Each time it is called, it finds
725 // a register which is not live at that instruction and also which is not
726 // used by other spilled operands of the same instruction. Then it uses
727 // this register temporarily to accomodate the spilled value.
728 //----------------------------------------------------------------------------
730 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
731 MachineBasicBlock::iterator& MII,
732 MachineBasicBlock &MBB,
733 const unsigned OpNum) {
735 MachineInstr *MInst = *MII;
736 const BasicBlock *BB = MBB.getBasicBlock();
738 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
739 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
740 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
741 "Return value of a ret must be handled elsewhere");
743 MachineOperand& Op = MInst->getOperand(OpNum);
744 bool isDef = Op.opIsDefOnly();
745 bool isDefAndUse = Op.opIsDefAndUse();
746 unsigned RegType = MRI.getRegTypeForLR(LR);
747 int SpillOff = LR->getSpillOffFromFP();
748 RegClass *RC = LR->getRegClass();
750 // Get the live-variable set to find registers free before this instr.
751 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
754 // If this instr. is in the delay slot of a branch or return, we need to
755 // include all live variables before that branch or return -- we don't want to
756 // trample those! Verify that the set is included in the LV set before MInst.
758 if (MII != MBB.begin()) {
759 MachineInstr *PredMI = *(MII-1);
760 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
761 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
762 .empty() && "Live-var set before branch should be included in "
763 "live-var set of each delay slot instruction!");
767 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
769 vector<MachineInstr*> MIBef, MIAft;
770 vector<MachineInstr*> AdIMid;
772 // Choose a register to hold the spilled value, if one was not preallocated.
773 // This may insert code before and after MInst to free up the value. If so,
774 // this code should be first/last in the spill sequence before/after MInst.
775 int TmpRegU=(LR->hasColor()
776 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
777 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
779 // Set the operand first so that it this register does not get used
780 // as a scratch register for later calls to getUsableUniRegAtMI below
781 MInst->SetRegForOperand(OpNum, TmpRegU);
783 // get the added instructions for this instruction
784 AddedInstrns &AI = AddedInstrMap[MInst];
786 // We may need a scratch register to copy the spilled value to/from memory.
787 // This may itself have to insert code to free up a scratch register.
788 // Any such code should go before (after) the spill code for a load (store).
789 // The scratch reg is not marked as used because it is only used
790 // for the copy and not used across MInst.
791 int scratchRegType = -1;
793 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
795 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
796 MInst, MIBef, MIAft);
797 assert(scratchReg != MRI.getInvalidRegNum());
800 if (!isDef || isDefAndUse) {
801 // for a USE, we have to load the value of LR from stack to a TmpReg
802 // and use the TmpReg as one operand of instruction
804 // actual loading instruction(s)
805 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
806 RegType, scratchReg);
808 // the actual load should be after the instructions to free up TmpRegU
809 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
813 if (isDef || isDefAndUse) { // if this is a Def
814 // for a DEF, we have to store the value produced by this instruction
815 // on the stack position allocated for this LR
817 // actual storing instruction(s)
818 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
819 RegType, scratchReg);
821 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
824 // Finally, insert the entire spill code sequences before/after MInst
825 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
826 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
829 cerr << "\nFor Inst:\n " << *MInst;
830 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
831 cerr << "; added Instructions:";
832 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
833 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
839 //----------------------------------------------------------------------------
840 // This method inserts caller saving/restoring instructons before/after
841 // a call machine instruction. The caller saving/restoring instructions are
843 // ** caller saving instructions
844 // other instructions inserted for the call by ColorCallArg
846 // other instructions inserted for the call ColorCallArg
847 // ** caller restoring instructions
848 //----------------------------------------------------------------------------
851 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
852 std::vector<MachineInstr*> &instrnsAfter,
853 MachineInstr *CallMI,
854 const BasicBlock *BB)
856 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
858 // has set to record which registers were saved/restored
860 hash_set<unsigned> PushedRegSet;
862 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
864 // if the call is to a instrumentation function, do not insert save and
865 // restore instructions the instrumentation function takes care of save
866 // restore for volatile regs.
868 // FIXME: this should be made general, not specific to the reoptimizer!
870 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
871 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
873 // Now check if the call has a return value (using argDesc) and if so,
874 // find the LR of the TmpInstruction representing the return value register.
875 // (using the last or second-last *implicit operand* of the call MI).
876 // Insert it to to the PushedRegSet since we must not save that register
877 // and restore it after the call.
878 // We do this because, we look at the LV set *after* the instruction
879 // to determine, which LRs must be saved across calls. The return value
880 // of the call is live in this set - but we must not save/restore it.
882 if (const Value *origRetVal = argDesc->getReturnValue()) {
883 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
884 (argDesc->getIndirectFuncPtr()? 1 : 2));
885 const TmpInstruction* tmpRetVal =
886 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
887 assert(tmpRetVal->getOperand(0) == origRetVal &&
888 tmpRetVal->getType() == origRetVal->getType() &&
889 "Wrong implicit ref?");
890 LiveRange *RetValLR = LRI.getLiveRangeForValue(tmpRetVal);
891 assert(RetValLR && "No LR for RetValue of call");
893 if (! RetValLR->isMarkedForSpill())
894 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
895 RetValLR->getColor()));
898 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
899 ValueSet::const_iterator LIt = LVSetAft.begin();
901 // for each live var in live variable set after machine inst
902 for( ; LIt != LVSetAft.end(); ++LIt) {
904 // get the live range corresponding to live var
905 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt);
907 // LR can be null if it is a const since a const
908 // doesn't have a dominating def - see Assumptions above
911 if(! LR->isMarkedForSpill()) {
913 assert(LR->hasColor() && "LR is neither spilled nor colored?");
914 unsigned RCID = LR->getRegClassID();
915 unsigned Color = LR->getColor();
917 if (MRI.isRegVolatile(RCID, Color) ) {
919 //if the function is special LLVM function,
920 //And the register is not modified by call, don't save and restore
921 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
924 // if the value is in both LV sets (i.e., live before and after
925 // the call machine instruction)
927 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
929 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
931 // if we haven't already pushed that register
933 unsigned RegType = MRI.getRegTypeForLR(LR);
935 // Now get two instructions - to push on stack and pop from stack
936 // and add them to InstrnsBefore and InstrnsAfter of the
940 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
942 //---- Insert code for pushing the reg on stack ----------
944 std::vector<MachineInstr*> AdIBef, AdIAft;
946 // We may need a scratch register to copy the saved value
947 // to/from memory. This may itself have to insert code to
948 // free up a scratch register. Any such code should go before
949 // the save code. The scratch register, if any, is by default
950 // temporary and not "used" by the instruction unless the
951 // copy code itself decides to keep the value in the scratch reg.
952 int scratchRegType = -1;
954 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
955 { // Find a register not live in the LVSet before CallMI
956 const ValueSet &LVSetBef =
957 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
958 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
959 CallMI, AdIBef, AdIAft);
960 assert(scratchReg != MRI.getInvalidRegNum());
963 if (AdIBef.size() > 0)
964 instrnsBefore.insert(instrnsBefore.end(),
965 AdIBef.begin(), AdIBef.end());
967 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
968 StackOff, RegType, scratchReg);
970 if (AdIAft.size() > 0)
971 instrnsBefore.insert(instrnsBefore.end(),
972 AdIAft.begin(), AdIAft.end());
974 //---- Insert code for popping the reg from the stack ----------
979 // We may need a scratch register to copy the saved value
980 // from memory. This may itself have to insert code to
981 // free up a scratch register. Any such code should go
982 // after the save code. As above, scratch is not marked "used".
986 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
987 { // Find a register not live in the LVSet after CallMI
988 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
989 CallMI, AdIBef, AdIAft);
990 assert(scratchReg != MRI.getInvalidRegNum());
993 if (AdIBef.size() > 0)
994 instrnsAfter.insert(instrnsAfter.end(),
995 AdIBef.begin(), AdIBef.end());
997 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
998 Reg, RegType, scratchReg);
1000 if (AdIAft.size() > 0)
1001 instrnsAfter.insert(instrnsAfter.end(),
1002 AdIAft.begin(), AdIAft.end());
1004 PushedRegSet.insert(Reg);
1007 std::cerr << "\nFor call inst:" << *CallMI;
1008 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1009 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1010 std::mem_fun(&MachineInstr::dump));
1011 std::cerr << " -and After:\n\t ";
1012 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1013 std::mem_fun(&MachineInstr::dump));
1015 } // if not already pushed
1017 } // if LR has a volatile color
1019 } // if LR has color
1021 } // if there is a LR for Var
1023 } // for each value in the LV set after instruction
1027 //----------------------------------------------------------------------------
1028 // We can use the following method to get a temporary register to be used
1029 // BEFORE any given machine instruction. If there is a register available,
1030 // this method will simply return that register and set MIBef = MIAft = NULL.
1031 // Otherwise, it will return a register and MIAft and MIBef will contain
1032 // two instructions used to free up this returned register.
1033 // Returned register number is the UNIFIED register number
1034 //----------------------------------------------------------------------------
1036 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
1037 const ValueSet *LVSetBef,
1038 MachineInstr *MInst,
1039 std::vector<MachineInstr*>& MIBef,
1040 std::vector<MachineInstr*>& MIAft) {
1042 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
1044 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
1047 // we couldn't find an unused register. Generate code to free up a reg by
1048 // saving it on stack and restoring after the instruction
1050 int TmpOff = MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
1052 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
1054 // Check if we need a scratch register to copy this register to memory.
1055 int scratchRegType = -1;
1056 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
1058 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
1059 MInst, MIBef, MIAft);
1060 assert(scratchReg != MRI.getInvalidRegNum());
1062 // We may as well hold the value in the scratch register instead
1063 // of copying it to memory and back. But we have to mark the
1064 // register as used by this instruction, so it does not get used
1065 // as a scratch reg. by another operand or anyone else.
1066 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
1067 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
1068 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
1071 { // the register can be copied directly to/from memory so do it.
1072 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
1073 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
1081 //----------------------------------------------------------------------------
1082 // This method is called to get a new unused register that can be used
1083 // to accomodate a temporary value. This method may be called several times
1084 // for a single machine instruction. Each time it is called, it finds a
1085 // register which is not live at that instruction and also which is not used
1086 // by other spilled operands of the same instruction. Return register number
1087 // is relative to the register class, NOT the unified number.
1088 //----------------------------------------------------------------------------
1090 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
1092 const MachineInstr *MInst,
1093 const ValueSet* LVSetBef) {
1095 RC->clearColorsUsed(); // Reset array
1097 if (LVSetBef == NULL) {
1098 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
1099 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1102 ValueSet::const_iterator LIt = LVSetBef->begin();
1104 // for each live var in live variable set after machine inst
1105 for ( ; LIt != LVSetBef->end(); ++LIt) {
1107 // get the live range corresponding to live var, and its RegClass
1108 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
1110 // LR can be null if it is a const since a const
1111 // doesn't have a dominating def - see Assumptions above
1112 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1113 RC->markColorsUsed(LRofLV->getColor(),
1114 MRI.getRegTypeForLR(LRofLV), RegType);
1117 // It is possible that one operand of this MInst was already spilled
1118 // and it received some register temporarily. If that's the case,
1119 // it is recorded in machine operand. We must skip such registers.
1121 setRelRegsUsedByThisInst(RC, RegType, MInst);
1123 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1125 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1131 //----------------------------------------------------------------------------
1132 // Get any other register in a register class, other than what is used
1133 // by operands of a machine instruction. Returns the unified reg number.
1134 //----------------------------------------------------------------------------
1135 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
1137 const MachineInstr *MInst) {
1138 RC->clearColorsUsed();
1140 setRelRegsUsedByThisInst(RC, RegType, MInst);
1142 // find the first unused color
1143 int unusedReg = RC->getUnusedColor(RegType);
1144 assert(unusedReg >= 0 &&
1145 "FATAL: No free register could be found in reg class!!");
1147 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1151 //----------------------------------------------------------------------------
1152 // This method modifies the IsColorUsedArr of the register class passed to it.
1153 // It sets the bits corresponding to the registers used by this machine
1154 // instructions. Both explicit and implicit operands are set.
1155 //----------------------------------------------------------------------------
1157 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1158 const TargetRegInfo &TRI) {
1159 unsigned classId = 0;
1160 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1161 if (RC->getID() == classId)
1162 RC->markColorsUsed(classRegNum, RegType, RegType);
1165 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1166 const MachineInstr *MI)
1168 assert(OperandsColoredMap[MI] == true &&
1169 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1170 "are marked for an instruction.");
1172 // Add the registers already marked as used by the instruction.
1173 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1174 if (MI->getOperand(i).hasAllocatedReg())
1175 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1177 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1178 if (MI->getImplicitOp(i).hasAllocatedReg())
1179 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1182 // Add all of the scratch registers that are used to save values across the
1183 // instruction (e.g., for saving state register values).
1184 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1185 IR = ScratchRegsUsed.equal_range(MI);
1186 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1187 markRegisterUsed(I->second, RC, RegType, MRI);
1189 // If there are implicit references, mark their allocated regs as well
1191 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1192 if (const LiveRange*
1193 LRofImpRef = LRI.getLiveRangeForValue(MI->getImplicitRef(z)))
1194 if (LRofImpRef->hasColor())
1195 // this implicit reference is in a LR that received a color
1196 RC->markColorsUsed(LRofImpRef->getColor(),
1197 MRI.getRegTypeForLR(LRofImpRef), RegType);
1201 //----------------------------------------------------------------------------
1202 // If there are delay slots for an instruction, the instructions
1203 // added after it must really go after the delayed instruction(s).
1204 // So, we move the InstrAfter of that instruction to the
1205 // corresponding delayed instruction using the following method.
1206 //----------------------------------------------------------------------------
1208 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1209 const MachineInstr *DelayedMI)
1211 // "added after" instructions of the original instr
1212 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1214 if (DEBUG_RA && OrigAft.size() > 0) {
1215 cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1216 cerr << " to last delay slot instrn: " << *DelayedMI;
1219 // "added after" instructions of the delayed instr
1220 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1222 // go thru all the "added after instructions" of the original instruction
1223 // and append them to the "added after instructions" of the delayed
1225 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1227 // empty the "added after instructions" of the original instruction
1231 //----------------------------------------------------------------------------
1232 // This method prints the code with registers after register allocation is
1234 //----------------------------------------------------------------------------
1235 void PhyRegAlloc::printMachineCode()
1238 cerr << "\n;************** Function " << Fn->getName()
1239 << " *****************\n";
1241 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
1242 BBI != BBE; ++BBI) {
1243 cerr << "\n"; printLabel(BBI->getBasicBlock()); cerr << ": ";
1245 // get the iterator for machine instructions
1246 MachineBasicBlock& MBB = *BBI;
1247 MachineBasicBlock::iterator MII = MBB.begin();
1249 // iterate over all the machine instructions in BB
1250 for ( ; MII != MBB.end(); ++MII) {
1251 MachineInstr *MInst = *MII;
1254 cerr << TM.getInstrInfo().getName(MInst->getOpCode());
1256 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1257 MachineOperand& Op = MInst->getOperand(OpNum);
1259 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
1260 Op.getType() == MachineOperand::MO_CCRegister /*||
1261 Op.getType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1263 const Value *const Val = Op.getVRegValue () ;
1264 // ****this code is temporary till NULL Values are fixed
1266 cerr << "\t<*NULL*>";
1270 // if a label or a constant
1271 if (isa<BasicBlock>(Val)) {
1272 cerr << "\t"; printLabel( Op.getVRegValue () );
1274 // else it must be a register value
1275 const int RegNum = Op.getAllocatedRegNum();
1277 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1278 if (Val->hasName() )
1279 cerr << "(" << Val->getName() << ")";
1281 cerr << "(" << Val << ")";
1283 if (Op.opIsDefOnly() || Op.opIsDefAndUse())
1286 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1288 if (LROfVal->hasSpillOffset() )
1293 else if (Op.getType() == MachineOperand::MO_MachineRegister) {
1294 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1298 cerr << "\t" << Op; // use dump field
1303 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1304 if (NumOfImpRefs > 0) {
1305 cerr << "\tImplicit:";
1307 for (unsigned z=0; z < NumOfImpRefs; z++)
1308 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1311 } // for all machine instructions
1321 //----------------------------------------------------------------------------
1323 //----------------------------------------------------------------------------
1324 void PhyRegAlloc::colorIncomingArgs()
1326 MRI.colorMethodArgs(Fn, LRI, AddedInstrAtEntry.InstrnsBefore,
1327 AddedInstrAtEntry.InstrnsAfter);
1331 //----------------------------------------------------------------------------
1332 // Used to generate a label for a basic block
1333 //----------------------------------------------------------------------------
1334 void PhyRegAlloc::printLabel(const Value *Val) {
1336 cerr << Val->getName();
1338 cerr << "Label" << Val;
1342 //----------------------------------------------------------------------------
1343 // This method calls setSugColorUsable method of each live range. This
1344 // will determine whether the suggested color of LR is really usable.
1345 // A suggested color is not usable when the suggested color is volatile
1346 // AND when there are call interferences
1347 //----------------------------------------------------------------------------
1349 void PhyRegAlloc::markUnusableSugColors()
1351 // hash map iterator
1352 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1353 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1355 for (; HMI != HMIEnd ; ++HMI ) {
1357 LiveRange *L = HMI->second; // get the LiveRange
1359 if (L->hasSuggestedColor()) {
1360 int RCID = L->getRegClass()->getID();
1361 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1362 L->isCallInterference() )
1363 L->setSuggestedColorUsable( false );
1365 L->setSuggestedColorUsable( true );
1367 } // if L->hasSuggestedColor()
1369 } // for all LR's in hash map
1374 //----------------------------------------------------------------------------
1375 // The following method will set the stack offsets of the live ranges that
1376 // are decided to be spillled. This must be called just after coloring the
1377 // LRs using the graph coloring algo. For each live range that is spilled,
1378 // this method allocate a new spill position on the stack.
1379 //----------------------------------------------------------------------------
1381 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1382 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1384 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1385 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1387 for ( ; HMI != HMIEnd ; ++HMI) {
1388 if (HMI->first && HMI->second) {
1389 LiveRange *L = HMI->second; // get the LiveRange
1390 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1391 int stackOffset = MF.getInfo()->allocateSpilledValue(Type::LongTy);
1392 L->setSpillOffFromFP(stackOffset);
1394 cerr << " LR# " << L->getUserIGNode()->getIndex()
1395 << ": stack-offset = " << stackOffset << "\n";
1398 } // for all LR's in hash map
1402 //----------------------------------------------------------------------------
1403 // The entry pont to Register Allocation
1404 //----------------------------------------------------------------------------
1406 void PhyRegAlloc::allocateRegisters()
1409 // make sure that we put all register classes into the RegClassList
1410 // before we call constructLiveRanges (now done in the constructor of
1411 // PhyRegAlloc class).
1413 LRI.constructLiveRanges(); // create LR info
1415 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1416 LRI.printLiveRanges();
1418 createIGNodeListsAndIGs(); // create IGNode list and IGs
1420 buildInterferenceGraphs(); // build IGs in all reg classes
1423 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1424 // print all LRs in all reg classes
1425 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1426 RegClassList[rc]->printIGNodeList();
1428 // print IGs in all register classes
1429 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1430 RegClassList[rc]->printIG();
1433 LRI.coalesceLRs(); // coalesce all live ranges
1435 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1436 // print all LRs in all reg classes
1437 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1438 RegClassList[rc]->printIGNodeList();
1440 // print IGs in all register classes
1441 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1442 RegClassList[rc]->printIG();
1446 // mark un-usable suggested color before graph coloring algorithm.
1447 // When this is done, the graph coloring algo will not reserve
1448 // suggested color unnecessarily - they can be used by another LR
1450 markUnusableSugColors();
1452 // color all register classes using the graph coloring algo
1453 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1454 RegClassList[rc]->colorAllRegs();
1456 // Atter graph coloring, if some LRs did not receive a color (i.e, spilled)
1457 // a poistion for such spilled LRs
1459 allocateStackSpace4SpilledLRs();
1461 // Reset the temp. area on the stack before use by the first instruction.
1462 // This will also happen after updating each instruction.
1463 MF.getInfo()->popAllTempValues();
1465 // color incoming args - if the correct color was not received
1466 // insert code to copy to the correct register
1468 colorIncomingArgs();
1470 // Now update the machine code with register names and add any
1471 // additional code inserted by the register allocator to the instruction
1474 updateMachineCode();
1477 cerr << "\n**** Machine Code After Register Allocation:\n\n";