1 //===-- RegAllocFast.cpp - A fast register allocator for debug code -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This register allocator allocates registers to a basic block at a time,
11 // attempting to keep values in registers and reusing registers as appropriate.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/IndexedMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/STLExtras.h"
38 static cl::opt<bool> VerifyFastRegalloc("verify-fast-regalloc", cl::Hidden,
39 cl::desc("Verify machine code before fast regalloc"));
41 STATISTIC(NumStores, "Number of stores added");
42 STATISTIC(NumLoads , "Number of loads added");
43 STATISTIC(NumCopies, "Number of copies coalesced");
45 static RegisterRegAlloc
46 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
49 class RAFast : public MachineFunctionPass {
52 RAFast() : MachineFunctionPass(&ID), StackSlotForVirtReg(-1),
53 atEndOfBlock(false) {}
55 const TargetMachine *TM;
57 MachineRegisterInfo *MRI;
58 const TargetRegisterInfo *TRI;
59 const TargetInstrInfo *TII;
61 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
62 // values are spilled.
63 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
65 // Everything we know about a live virtual register.
67 MachineInstr *LastUse; // Last instr to use reg.
68 unsigned PhysReg; // Currently held here.
69 unsigned short LastOpNum; // OpNum on LastUse.
70 bool Dirty; // Register needs spill.
72 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
74 assert(p && "Don't create LiveRegs without a PhysReg");
78 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
80 // LiveVirtRegs - This map contains entries for each virtual register
81 // that is currently available in a physical register.
82 LiveRegMap LiveVirtRegs;
84 // RegState - Track the state of a physical register.
86 // A disabled register is not available for allocation, but an alias may
87 // be in use. A register can only be moved out of the disabled state if
88 // all aliases are disabled.
91 // A free register is not currently in use and can be allocated
92 // immediately without checking aliases.
95 // A reserved register has been assigned expolicitly (e.g., setting up a
96 // call parameter), and it remains reserved until it is used.
99 // A register state may also be a virtual register number, indication that
100 // the physical register is currently allocated to a virtual register. In
101 // that case, LiveVirtRegs contains the inverse mapping.
104 // PhysRegState - One of the RegState enums, or a virtreg.
105 std::vector<unsigned> PhysRegState;
107 // UsedInInstr - BitVector of physregs that are used in the current
108 // instruction, and so cannot be allocated.
109 BitVector UsedInInstr;
111 // Allocatable - vector of allocatable physical registers.
112 BitVector Allocatable;
114 // atEndOfBlock - This flag is set after allocating all instructions in a
115 // block, before emitting final spills. When it is set, LiveRegMap is no
116 // longer updated properly sonce it will be cleared anyway.
120 virtual const char *getPassName() const {
121 return "Fast Register Allocator";
124 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
125 AU.setPreservesCFG();
126 AU.addRequiredID(PHIEliminationID);
127 AU.addRequiredID(TwoAddressInstructionPassID);
128 MachineFunctionPass::getAnalysisUsage(AU);
132 bool runOnMachineFunction(MachineFunction &Fn);
133 void AllocateBasicBlock(MachineBasicBlock &MBB);
134 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
135 bool isLastUseOfLocalReg(MachineOperand&);
137 void addKillFlag(LiveRegMap::iterator i);
138 void killVirtReg(LiveRegMap::iterator i);
139 void killVirtReg(unsigned VirtReg);
140 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
141 LiveRegMap::iterator i, bool isKill);
142 void spillVirtReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
143 unsigned VirtReg, bool isKill);
145 void usePhysReg(MachineOperand&);
146 void definePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
147 unsigned PhysReg, RegState NewState);
148 LiveRegMap::iterator assignVirtToPhysReg(unsigned VirtReg,
150 LiveRegMap::iterator allocVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
151 unsigned VirtReg, unsigned Hint);
152 unsigned defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
153 unsigned OpNum, unsigned VirtReg, unsigned Hint);
154 unsigned reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
155 unsigned OpNum, unsigned VirtReg, unsigned Hint);
156 void spillAll(MachineBasicBlock &MBB, MachineInstr *MI);
157 void setPhysReg(MachineOperand &MO, unsigned PhysReg);
162 /// getStackSpaceFor - This allocates space for the specified virtual register
163 /// to be held on the stack.
164 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
165 // Find the location Reg would belong...
166 int SS = StackSlotForVirtReg[VirtReg];
168 return SS; // Already has space allocated?
170 // Allocate a new stack object for this spill location...
171 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
175 StackSlotForVirtReg[VirtReg] = FrameIdx;
179 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
180 /// its virtual register, and it is guaranteed to be a block-local register.
182 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
183 // Check for non-debug uses or defs following MO.
184 // This is the most likely way to fail - fast path it.
185 MachineOperand *i = &MO;
186 while ((i = i->getNextOperandForReg()))
190 // If the register has ever been spilled or reloaded, we conservatively assume
191 // it is a global register used in multiple blocks.
192 if (StackSlotForVirtReg[MO.getReg()] != -1)
195 // Check that the use/def chain has exactly one operand - MO.
196 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
199 /// addKillFlag - Set kill flags on last use of a virtual register.
200 void RAFast::addKillFlag(LiveRegMap::iterator lri) {
201 assert(lri != LiveVirtRegs.end() && "Killing unmapped virtual register");
202 const LiveReg &LR = lri->second;
204 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
207 else if (!LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum))
212 /// killVirtReg - Mark virtreg as no longer available.
213 void RAFast::killVirtReg(LiveRegMap::iterator lri) {
215 const LiveReg &LR = lri->second;
216 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
217 PhysRegState[LR.PhysReg] = regFree;
218 // Erase from LiveVirtRegs unless we're at the end of the block when
219 // everything will be bulk erased.
221 LiveVirtRegs.erase(lri);
224 /// killVirtReg - Mark virtreg as no longer available.
225 void RAFast::killVirtReg(unsigned VirtReg) {
226 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
227 "killVirtReg needs a virtual register");
228 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
229 if (lri != LiveVirtRegs.end())
233 /// spillVirtReg - This method spills the value specified by VirtReg into the
234 /// corresponding stack slot if needed. If isKill is set, the register is also
236 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
237 MachineBasicBlock::iterator MI,
238 unsigned VirtReg, bool isKill) {
239 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
240 "Spilling a physical register is illegal!");
241 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
242 assert(lri != LiveVirtRegs.end() && "Spilling unmapped virtual register");
243 spillVirtReg(MBB, MI, lri, isKill);
246 /// spillVirtReg - Do the actual work of spilling.
247 void RAFast::spillVirtReg(MachineBasicBlock &MBB,
248 MachineBasicBlock::iterator MI,
249 LiveRegMap::iterator lri, bool isKill) {
250 LiveReg &LR = lri->second;
251 assert(PhysRegState[LR.PhysReg] == lri->first && "Broken RegState mapping");
253 // If this physreg is used by the instruction, we want to kill it on the
254 // instruction, not on the spill.
255 bool spillKill = isKill && LR.LastUse != MI;
259 DEBUG(dbgs() << "Spilling %reg" << lri->first
260 << " in " << TRI->getName(LR.PhysReg));
261 const TargetRegisterClass *RC = MRI->getRegClass(lri->first);
262 int FrameIndex = getStackSpaceFor(lri->first, RC);
263 DEBUG(dbgs() << " to stack slot #" << FrameIndex << "\n");
264 TII->storeRegToStackSlot(MBB, MI, LR.PhysReg, spillKill,
265 FrameIndex, RC, TRI);
266 ++NumStores; // Update statistics
269 LR.LastUse = 0; // Don't kill register again
271 MachineInstr *Spill = llvm::prior(MI);
273 LR.LastOpNum = Spill->findRegisterUseOperandIdx(LR.PhysReg);
281 /// spillAll - Spill all dirty virtregs without killing them.
282 void RAFast::spillAll(MachineBasicBlock &MBB, MachineInstr *MI) {
283 SmallVector<unsigned, 16> Dirty;
284 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
285 e = LiveVirtRegs.end(); i != e; ++i)
287 Dirty.push_back(i->first);
288 for (unsigned i = 0, e = Dirty.size(); i != e; ++i)
289 spillVirtReg(MBB, MI, Dirty[i], false);
292 /// usePhysReg - Handle the direct use of a physical register.
293 /// Check that the register is not used by a virtreg.
294 /// Kill the physreg, marking it free.
295 /// This may add implicit kills to MO->getParent() and invalidate MO.
296 void RAFast::usePhysReg(MachineOperand &MO) {
297 unsigned PhysReg = MO.getReg();
298 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
299 "Bad usePhysReg operand");
301 switch (PhysRegState[PhysReg]) {
305 PhysRegState[PhysReg] = regFree;
308 UsedInInstr.set(PhysReg);
312 // The physreg was allocated to a virtual register. That means to value we
313 // wanted has been clobbered.
314 llvm_unreachable("Instruction uses an allocated register");
317 // Maybe a superregister is reserved?
318 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
319 unsigned Alias = *AS; ++AS) {
320 switch (PhysRegState[Alias]) {
324 assert(TRI->isSuperRegister(PhysReg, Alias) &&
325 "Instruction is not using a subregister of a reserved register");
326 // Leave the superregister in the working set.
327 PhysRegState[Alias] = regFree;
328 UsedInInstr.set(Alias);
329 MO.getParent()->addRegisterKilled(Alias, TRI, true);
332 if (TRI->isSuperRegister(PhysReg, Alias)) {
333 // Leave the superregister in the working set.
334 UsedInInstr.set(Alias);
335 MO.getParent()->addRegisterKilled(Alias, TRI, true);
338 // Some other alias was in the working set - clear it.
339 PhysRegState[Alias] = regDisabled;
342 llvm_unreachable("Instruction uses an alias of an allocated register");
346 // All aliases are disabled, bring register into working set.
347 PhysRegState[PhysReg] = regFree;
348 UsedInInstr.set(PhysReg);
352 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
353 /// virtregs. This is very similar to defineVirtReg except the physreg is
354 /// reserved instead of allocated.
355 void RAFast::definePhysReg(MachineBasicBlock &MBB, MachineInstr *MI,
356 unsigned PhysReg, RegState NewState) {
357 UsedInInstr.set(PhysReg);
358 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
362 spillVirtReg(MBB, MI, VirtReg, true);
366 PhysRegState[PhysReg] = NewState;
370 // This is a disabled register, disable all aliases.
371 PhysRegState[PhysReg] = NewState;
372 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
373 unsigned Alias = *AS; ++AS) {
374 UsedInInstr.set(Alias);
375 switch (unsigned VirtReg = PhysRegState[Alias]) {
379 spillVirtReg(MBB, MI, VirtReg, true);
383 PhysRegState[Alias] = regDisabled;
384 if (TRI->isSuperRegister(PhysReg, Alias))
392 /// assignVirtToPhysReg - This method updates local state so that we know
393 /// that PhysReg is the proper container for VirtReg now. The physical
394 /// register must not be used for anything else when this is called.
396 RAFast::LiveRegMap::iterator
397 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
398 DEBUG(dbgs() << "Assigning %reg" << VirtReg << " to "
399 << TRI->getName(PhysReg) << "\n");
400 PhysRegState[PhysReg] = VirtReg;
401 return LiveVirtRegs.insert(std::make_pair(VirtReg, PhysReg)).first;
404 /// allocVirtReg - Allocate a physical register for VirtReg.
405 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineBasicBlock &MBB,
409 const unsigned spillCost = 100;
410 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
411 "Can only allocate virtual registers");
413 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
414 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
415 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
417 // Ignore invalid hints.
418 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
419 !RC->contains(Hint) || UsedInInstr.test(Hint) ||
420 !Allocatable.test(Hint)))
423 // If there is no hint, peek at the first use of this register.
424 if (!Hint && !MRI->use_nodbg_empty(VirtReg)) {
425 MachineInstr &MI = *MRI->use_nodbg_begin(VirtReg);
426 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
427 // Copy to physreg -> use physreg as hint.
428 if (TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
429 SrcReg == VirtReg && TargetRegisterInfo::isPhysicalRegister(DstReg) &&
430 RC->contains(DstReg) && !UsedInInstr.test(DstReg) &&
431 Allocatable.test(DstReg)) {
433 DEBUG(dbgs() << "%reg" << VirtReg << " gets hint from " << MI);
437 // Take hint when possible.
439 assert(RC->contains(Hint) && !UsedInInstr.test(Hint) &&
440 Allocatable.test(Hint) && "Invalid hint should have been cleared");
441 switch(PhysRegState[Hint]) {
446 spillVirtReg(MBB, MI, PhysRegState[Hint], true);
449 return assignVirtToPhysReg(VirtReg, Hint);
453 // First try to find a completely free register.
454 unsigned BestCost = 0, BestReg = 0;
455 bool hasDisabled = false;
456 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
457 unsigned PhysReg = *I;
458 switch(PhysRegState[PhysReg]) {
464 if (!UsedInInstr.test(PhysReg))
465 return assignVirtToPhysReg(VirtReg, PhysReg);
468 // Grab the first spillable register we meet.
469 if (!BestReg && !UsedInInstr.test(PhysReg))
470 BestReg = PhysReg, BestCost = spillCost;
475 DEBUG(dbgs() << "Allocating %reg" << VirtReg << " from " << RC->getName()
476 << " candidate=" << TRI->getName(BestReg) << "\n");
478 // Try to extend the working set for RC if there were any disabled registers.
479 if (hasDisabled && (!BestReg || BestCost >= spillCost)) {
480 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
481 unsigned PhysReg = *I;
482 if (PhysRegState[PhysReg] != regDisabled || UsedInInstr.test(PhysReg))
485 // Calculate the cost of bringing PhysReg into the working set.
487 bool Impossible = false;
488 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
489 unsigned Alias = *AS; ++AS) {
490 if (UsedInInstr.test(Alias)) {
494 switch (PhysRegState[Alias]) {
508 if (Impossible) continue;
509 DEBUG(dbgs() << "- candidate " << TRI->getName(PhysReg)
510 << " cost=" << Cost << "\n");
511 if (!BestReg || Cost < BestCost) {
514 if (Cost < spillCost) break;
520 // BestCost is 0 when all aliases are already disabled.
522 if (PhysRegState[BestReg] != regDisabled)
523 spillVirtReg(MBB, MI, PhysRegState[BestReg], true);
525 // Make sure all aliases are disabled.
526 for (const unsigned *AS = TRI->getAliasSet(BestReg);
527 unsigned Alias = *AS; ++AS) {
528 switch (PhysRegState[Alias]) {
532 PhysRegState[Alias] = regDisabled;
535 spillVirtReg(MBB, MI, PhysRegState[Alias], true);
536 PhysRegState[Alias] = regDisabled;
542 return assignVirtToPhysReg(VirtReg, BestReg);
545 // Nothing we can do.
547 raw_string_ostream Msg(msg);
548 Msg << "Ran out of registers during register allocation!";
549 if (MI->isInlineAsm()) {
550 Msg << "\nPlease check your inline asm statement for "
551 << "invalid constraints:\n";
554 report_fatal_error(Msg.str());
555 return LiveVirtRegs.end();
558 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
559 unsigned RAFast::defineVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
560 unsigned OpNum, unsigned VirtReg, unsigned Hint) {
561 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
562 "Not a virtual register");
563 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
564 if (lri == LiveVirtRegs.end())
565 lri = allocVirtReg(MBB, MI, VirtReg, Hint);
567 addKillFlag(lri); // Kill before redefine.
568 LiveReg &LR = lri->second;
570 LR.LastOpNum = OpNum;
572 UsedInInstr.set(LR.PhysReg);
576 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
577 unsigned RAFast::reloadVirtReg(MachineBasicBlock &MBB, MachineInstr *MI,
578 unsigned OpNum, unsigned VirtReg, unsigned Hint) {
579 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
580 "Not a virtual register");
581 LiveRegMap::iterator lri = LiveVirtRegs.find(VirtReg);
582 if (lri == LiveVirtRegs.end()) {
583 lri = allocVirtReg(MBB, MI, VirtReg, Hint);
584 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
585 int FrameIndex = getStackSpaceFor(VirtReg, RC);
586 DEBUG(dbgs() << "Reloading %reg" << VirtReg << " into "
587 << TRI->getName(lri->second.PhysReg) << "\n");
588 TII->loadRegFromStackSlot(MBB, MI, lri->second.PhysReg, FrameIndex, RC,
591 } else if (lri->second.Dirty) {
592 MachineOperand &MO = MI->getOperand(OpNum);
593 if (isLastUseOfLocalReg(MO)) {
594 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
596 } else if (MO.isKill()) {
597 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
601 LiveReg &LR = lri->second;
603 LR.LastOpNum = OpNum;
604 UsedInInstr.set(LR.PhysReg);
608 // setPhysReg - Change MO the refer the PhysReg, considering subregs.
609 void RAFast::setPhysReg(MachineOperand &MO, unsigned PhysReg) {
610 if (unsigned Idx = MO.getSubReg()) {
611 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, Idx) : 0);
617 void RAFast::AllocateBasicBlock(MachineBasicBlock &MBB) {
618 DEBUG(dbgs() << "\nAllocating " << MBB);
620 atEndOfBlock = false;
621 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
622 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
624 MachineBasicBlock::iterator MII = MBB.begin();
626 // Add live-in registers as live.
627 for (MachineBasicBlock::livein_iterator I = MBB.livein_begin(),
628 E = MBB.livein_end(); I != E; ++I)
629 definePhysReg(MBB, MII, *I, regReserved);
631 SmallVector<unsigned, 8> VirtKills, PhysDefs;
632 SmallVector<MachineInstr*, 32> Coalesced;
634 // Otherwise, sequentially allocate each instruction in the MBB.
635 while (MII != MBB.end()) {
636 MachineInstr *MI = MII++;
637 const TargetInstrDesc &TID = MI->getDesc();
639 dbgs() << "\n>> " << *MI << "Regs:";
640 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
641 if (PhysRegState[Reg] == regDisabled) continue;
642 dbgs() << " " << TRI->getName(Reg);
643 switch(PhysRegState[Reg]) {
650 dbgs() << "=%reg" << PhysRegState[Reg];
651 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
653 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
659 // Check that LiveVirtRegs is the inverse.
660 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
661 e = LiveVirtRegs.end(); i != e; ++i) {
662 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
664 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
666 assert(PhysRegState[i->second.PhysReg] == i->first &&
671 // Debug values are not allowed to change codegen in any way.
672 if (MI->isDebugValue()) {
673 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
674 MachineOperand &MO = MI->getOperand(i);
675 if (!MO.isReg()) continue;
676 unsigned Reg = MO.getReg();
677 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
678 LiveRegMap::iterator lri = LiveVirtRegs.find(Reg);
679 if (lri != LiveVirtRegs.end())
680 setPhysReg(MO, lri->second.PhysReg);
682 MO.setReg(0); // We can't allocate a physreg for a DebugValue, sorry!
688 // If this is a copy, we may be able to coalesce.
689 unsigned CopySrc, CopyDst, CopySrcSub, CopyDstSub;
690 if (!TII->isMoveInstr(*MI, CopySrc, CopyDst, CopySrcSub, CopyDstSub))
691 CopySrc = CopyDst = 0;
693 // Track registers used by instruction.
698 // Mark physreg uses and early clobbers as used.
699 // Find the end of the virtreg operands
700 unsigned VirtOpEnd = 0;
701 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
702 MachineOperand &MO = MI->getOperand(i);
703 if (!MO.isReg()) continue;
704 unsigned Reg = MO.getReg();
706 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
710 if (!Allocatable.test(Reg)) continue;
713 } else if (MO.isEarlyClobber()) {
714 definePhysReg(MBB, MI, Reg, MO.isDead() ? regFree : regReserved);
715 PhysDefs.push_back(Reg);
720 // Allocate virtreg uses and early clobbers.
722 for (unsigned i = 0; i != VirtOpEnd; ++i) {
723 MachineOperand &MO = MI->getOperand(i);
724 if (!MO.isReg()) continue;
725 unsigned Reg = MO.getReg();
726 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
728 unsigned PhysReg = reloadVirtReg(MBB, MI, i, Reg, CopyDst);
729 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
730 setPhysReg(MO, PhysReg);
732 VirtKills.push_back(Reg);
733 } else if (MO.isEarlyClobber()) {
734 unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, 0);
735 setPhysReg(MO, PhysReg);
736 PhysDefs.push_back(PhysReg);
740 // Process virtreg kills
741 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
742 killVirtReg(VirtKills[i]);
745 MRI->addPhysRegsUsed(UsedInInstr);
747 // Track registers defined by instruction - early clobbers at this point.
749 for (unsigned i = 0, e = PhysDefs.size(); i != e; ++i) {
750 unsigned PhysReg = PhysDefs[i];
751 UsedInInstr.set(PhysReg);
752 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
753 unsigned Alias = *AS; ++AS)
754 UsedInInstr.set(Alias);
758 // Allocate defs and collect dead defs.
759 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
760 MachineOperand &MO = MI->getOperand(i);
761 if (!MO.isReg() || !MO.isDef() || !MO.getReg()) continue;
762 unsigned Reg = MO.getReg();
764 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
765 if (!Allocatable.test(Reg)) continue;
766 definePhysReg(MBB, MI, Reg, (MO.isImplicit() || MO.isDead()) ?
767 regFree : regReserved);
770 unsigned PhysReg = defineVirtReg(MBB, MI, i, Reg, CopySrc);
772 VirtKills.push_back(Reg);
773 CopyDst = 0; // cancel coalescing;
775 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
776 setPhysReg(MO, PhysReg);
779 // Spill all dirty virtregs before a call, in case of an exception.
781 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
785 // Process virtreg deads.
786 for (unsigned i = 0, e = VirtKills.size(); i != e; ++i)
787 killVirtReg(VirtKills[i]);
790 MRI->addPhysRegsUsed(UsedInInstr);
792 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
793 DEBUG(dbgs() << "-- coalescing: " << *MI);
794 Coalesced.push_back(MI);
796 DEBUG(dbgs() << "<< " << *MI);
800 // Spill all physical registers holding virtual registers now.
802 MachineBasicBlock::iterator MI = MBB.getFirstTerminator();
803 if (MI != MBB.end() && MI->getDesc().isReturn()) {
804 // This is a return block, kill all virtual registers.
805 DEBUG(dbgs() << "Killing live registers at end of return block.\n");
806 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
810 // This is a normal block, spill any dirty virtregs.
811 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
812 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
814 spillVirtReg(MBB, MI, i, true);
816 LiveVirtRegs.clear();
818 // Erase all the coalesced copies. We are delaying it until now because
819 // LiveVirtsRegs might refer to the instrs.
820 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
821 MBB.erase(Coalesced[i]);
822 NumCopies += Coalesced.size();
827 /// runOnMachineFunction - Register allocate the whole function
829 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
830 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
831 << "********** Function: "
832 << ((Value*)Fn.getFunction())->getName() << '\n');
833 if (VerifyFastRegalloc)
834 Fn.verify(this, true);
836 MRI = &MF->getRegInfo();
837 TM = &Fn.getTarget();
838 TRI = TM->getRegisterInfo();
839 TII = TM->getInstrInfo();
841 UsedInInstr.resize(TRI->getNumRegs());
842 Allocatable = TRI->getAllocatableSet(*MF);
844 // initialize the virtual->physical register map to have a 'null'
845 // mapping for all virtual registers
846 unsigned LastVirtReg = MRI->getLastVirtReg();
847 StackSlotForVirtReg.grow(LastVirtReg);
849 // Loop over all of the basic blocks, eliminating virtual register references
850 for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();
852 AllocateBasicBlock(*MBB);
854 // Make sure the set of used physregs is closed under subreg operations.
855 MRI->closePhysRegsUsed(*TRI);
857 StackSlotForVirtReg.clear();
861 FunctionPass *llvm::createFastRegisterAllocator() {