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 "RegisterClassInfo.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/IndexedMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
40 STATISTIC(NumStores, "Number of stores added");
41 STATISTIC(NumLoads , "Number of loads added");
42 STATISTIC(NumCopies, "Number of copies coalesced");
44 static RegisterRegAlloc
45 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
48 class RAFast : public MachineFunctionPass {
51 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
52 isBulkSpilling(false) {
53 initializePHIEliminationPass(*PassRegistry::getPassRegistry());
54 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
57 const TargetMachine *TM;
59 MachineRegisterInfo *MRI;
60 const TargetRegisterInfo *TRI;
61 const TargetInstrInfo *TII;
62 RegisterClassInfo RegClassInfo;
64 // Basic block currently being allocated.
65 MachineBasicBlock *MBB;
67 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
68 // values are spilled.
69 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
71 // Everything we know about a live virtual register.
73 MachineInstr *LastUse; // Last instr to use reg.
74 unsigned PhysReg; // Currently held here.
75 unsigned short LastOpNum; // OpNum on LastUse.
76 bool Dirty; // Register needs spill.
78 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
82 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
83 typedef LiveRegMap::value_type LiveRegEntry;
85 // LiveVirtRegs - This map contains entries for each virtual register
86 // that is currently available in a physical register.
87 LiveRegMap LiveVirtRegs;
89 DenseMap<unsigned, MachineInstr *> LiveDbgValueMap;
91 // RegState - Track the state of a physical register.
93 // A disabled register is not available for allocation, but an alias may
94 // be in use. A register can only be moved out of the disabled state if
95 // all aliases are disabled.
98 // A free register is not currently in use and can be allocated
99 // immediately without checking aliases.
102 // A reserved register has been assigned explicitly (e.g., setting up a
103 // call parameter), and it remains reserved until it is used.
106 // A register state may also be a virtual register number, indication that
107 // the physical register is currently allocated to a virtual register. In
108 // that case, LiveVirtRegs contains the inverse mapping.
111 // PhysRegState - One of the RegState enums, or a virtreg.
112 std::vector<unsigned> PhysRegState;
114 // UsedInInstr - BitVector of physregs that are used in the current
115 // instruction, and so cannot be allocated.
116 BitVector UsedInInstr;
118 // Allocatable - vector of allocatable physical registers.
119 BitVector Allocatable;
121 // SkippedInstrs - Descriptors of instructions whose clobber list was
122 // ignored because all registers were spilled. It is still necessary to
123 // mark all the clobbered registers as used by the function.
124 SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
126 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
127 // completely after spilling all live registers. LiveRegMap entries should
134 spillImpossible = ~0u
137 virtual const char *getPassName() const {
138 return "Fast Register Allocator";
141 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
142 AU.setPreservesCFG();
143 AU.addRequiredID(PHIEliminationID);
144 AU.addRequiredID(TwoAddressInstructionPassID);
145 MachineFunctionPass::getAnalysisUsage(AU);
149 bool runOnMachineFunction(MachineFunction &Fn);
150 void AllocateBasicBlock();
151 void handleThroughOperands(MachineInstr *MI,
152 SmallVectorImpl<unsigned> &VirtDead);
153 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
154 bool isLastUseOfLocalReg(MachineOperand&);
156 void addKillFlag(const LiveReg&);
157 void killVirtReg(LiveRegMap::iterator);
158 void killVirtReg(unsigned VirtReg);
159 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
160 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
162 void usePhysReg(MachineOperand&);
163 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
164 unsigned calcSpillCost(unsigned PhysReg) const;
165 void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
166 void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
167 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
168 unsigned VirtReg, unsigned Hint);
169 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
170 unsigned VirtReg, unsigned Hint);
171 void spillAll(MachineInstr *MI);
172 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
177 /// getStackSpaceFor - This allocates space for the specified virtual register
178 /// to be held on the stack.
179 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
180 // Find the location Reg would belong...
181 int SS = StackSlotForVirtReg[VirtReg];
183 return SS; // Already has space allocated?
185 // Allocate a new stack object for this spill location...
186 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
190 StackSlotForVirtReg[VirtReg] = FrameIdx;
194 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
195 /// its virtual register, and it is guaranteed to be a block-local register.
197 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
198 // Check for non-debug uses or defs following MO.
199 // This is the most likely way to fail - fast path it.
200 MachineOperand *Next = &MO;
201 while ((Next = Next->getNextOperandForReg()))
202 if (!Next->isDebug())
205 // If the register has ever been spilled or reloaded, we conservatively assume
206 // it is a global register used in multiple blocks.
207 if (StackSlotForVirtReg[MO.getReg()] != -1)
210 // Check that the use/def chain has exactly one operand - MO.
211 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
214 /// addKillFlag - Set kill flags on last use of a virtual register.
215 void RAFast::addKillFlag(const LiveReg &LR) {
216 if (!LR.LastUse) return;
217 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
218 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
219 if (MO.getReg() == LR.PhysReg)
222 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
226 /// killVirtReg - Mark virtreg as no longer available.
227 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
228 addKillFlag(LRI->second);
229 const LiveReg &LR = LRI->second;
230 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
231 PhysRegState[LR.PhysReg] = regFree;
232 // Erase from LiveVirtRegs unless we're spilling in bulk.
234 LiveVirtRegs.erase(LRI);
237 /// killVirtReg - Mark virtreg as no longer available.
238 void RAFast::killVirtReg(unsigned VirtReg) {
239 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
240 "killVirtReg needs a virtual register");
241 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
242 if (LRI != LiveVirtRegs.end())
246 /// spillVirtReg - This method spills the value specified by VirtReg into the
247 /// corresponding stack slot if needed.
248 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
249 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
250 "Spilling a physical register is illegal!");
251 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
252 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
253 spillVirtReg(MI, LRI);
256 /// spillVirtReg - Do the actual work of spilling.
257 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
258 LiveRegMap::iterator LRI) {
259 LiveReg &LR = LRI->second;
260 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
263 // If this physreg is used by the instruction, we want to kill it on the
264 // instruction, not on the spill.
265 bool SpillKill = LR.LastUse != MI;
267 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->first, TRI)
268 << " in " << PrintReg(LR.PhysReg, TRI));
269 const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
270 int FI = getStackSpaceFor(LRI->first, RC);
271 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
272 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
273 ++NumStores; // Update statistics
275 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
276 // identify spilled location as the place to find corresponding variable's
278 if (MachineInstr *DBG = LiveDbgValueMap.lookup(LRI->first)) {
279 const MDNode *MDPtr =
280 DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
282 if (DBG->getOperand(1).isImm())
283 Offset = DBG->getOperand(1).getImm();
285 if (MI == MBB->end()) {
286 // If MI is at basic block end then use last instruction's location.
287 MachineBasicBlock::iterator EI = MI;
288 DL = (--EI)->getDebugLoc();
291 DL = MI->getDebugLoc();
292 if (MachineInstr *NewDV =
293 TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
294 MachineBasicBlock *MBB = DBG->getParent();
295 MBB->insert(MI, NewDV);
296 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
297 LiveDbgValueMap[LRI->first] = NewDV;
301 LR.LastUse = 0; // Don't kill register again
306 /// spillAll - Spill all dirty virtregs without killing them.
307 void RAFast::spillAll(MachineInstr *MI) {
308 if (LiveVirtRegs.empty()) return;
309 isBulkSpilling = true;
310 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
311 // of spilling here is deterministic, if arbitrary.
312 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
315 LiveVirtRegs.clear();
316 isBulkSpilling = false;
319 /// usePhysReg - Handle the direct use of a physical register.
320 /// Check that the register is not used by a virtreg.
321 /// Kill the physreg, marking it free.
322 /// This may add implicit kills to MO->getParent() and invalidate MO.
323 void RAFast::usePhysReg(MachineOperand &MO) {
324 unsigned PhysReg = MO.getReg();
325 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
326 "Bad usePhysReg operand");
328 switch (PhysRegState[PhysReg]) {
332 PhysRegState[PhysReg] = regFree;
335 UsedInInstr.set(PhysReg);
339 // The physreg was allocated to a virtual register. That means the value we
340 // wanted has been clobbered.
341 llvm_unreachable("Instruction uses an allocated register");
344 // Maybe a superregister is reserved?
345 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
346 unsigned Alias = *AS; ++AS) {
347 switch (PhysRegState[Alias]) {
351 assert(TRI->isSuperRegister(PhysReg, Alias) &&
352 "Instruction is not using a subregister of a reserved register");
353 // Leave the superregister in the working set.
354 PhysRegState[Alias] = regFree;
355 UsedInInstr.set(Alias);
356 MO.getParent()->addRegisterKilled(Alias, TRI, true);
359 if (TRI->isSuperRegister(PhysReg, Alias)) {
360 // Leave the superregister in the working set.
361 UsedInInstr.set(Alias);
362 MO.getParent()->addRegisterKilled(Alias, TRI, true);
365 // Some other alias was in the working set - clear it.
366 PhysRegState[Alias] = regDisabled;
369 llvm_unreachable("Instruction uses an alias of an allocated register");
373 // All aliases are disabled, bring register into working set.
374 PhysRegState[PhysReg] = regFree;
375 UsedInInstr.set(PhysReg);
379 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
380 /// virtregs. This is very similar to defineVirtReg except the physreg is
381 /// reserved instead of allocated.
382 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
384 UsedInInstr.set(PhysReg);
385 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
389 spillVirtReg(MI, VirtReg);
393 PhysRegState[PhysReg] = NewState;
397 // This is a disabled register, disable all aliases.
398 PhysRegState[PhysReg] = NewState;
399 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
400 unsigned Alias = *AS; ++AS) {
401 switch (unsigned VirtReg = PhysRegState[Alias]) {
405 spillVirtReg(MI, VirtReg);
409 PhysRegState[Alias] = regDisabled;
410 if (TRI->isSuperRegister(PhysReg, Alias))
418 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
419 // aliases so it is free for allocation.
420 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
421 // can be allocated directly.
422 // Returns spillImpossible when PhysReg or an alias can't be spilled.
423 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
424 if (UsedInInstr.test(PhysReg)) {
425 DEBUG(dbgs() << "PhysReg: " << PhysReg << " is already used in instr.\n");
426 return spillImpossible;
428 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
434 DEBUG(dbgs() << "VirtReg: " << VirtReg << " corresponding to PhysReg: "
435 << PhysReg << " is reserved already.\n");
436 return spillImpossible;
438 return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
441 // This is a disabled register, add up cost of aliases.
442 DEBUG(dbgs() << "\tRegister: " << PhysReg << " is disabled.\n");
444 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
445 unsigned Alias = *AS; ++AS) {
446 if (UsedInInstr.test(Alias))
447 return spillImpossible;
448 switch (unsigned VirtReg = PhysRegState[Alias]) {
455 return spillImpossible;
457 Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
465 /// assignVirtToPhysReg - This method updates local state so that we know
466 /// that PhysReg is the proper container for VirtReg now. The physical
467 /// register must not be used for anything else when this is called.
469 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
470 DEBUG(dbgs() << "Assigning " << PrintReg(LRE.first, TRI) << " to "
471 << PrintReg(PhysReg, TRI) << "\n");
472 PhysRegState[PhysReg] = LRE.first;
473 assert(!LRE.second.PhysReg && "Already assigned a physreg");
474 LRE.second.PhysReg = PhysReg;
477 /// allocVirtReg - Allocate a physical register for VirtReg.
478 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
479 const unsigned VirtReg = LRE.first;
481 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
482 "Can only allocate virtual registers");
484 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
486 // Ignore invalid hints.
487 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
488 !RC->contains(Hint) || !Allocatable.test(Hint)))
491 // Take hint when possible.
493 switch(calcSpillCost(Hint)) {
495 definePhysReg(MI, Hint, regFree);
498 return assignVirtToPhysReg(LRE, Hint);
499 case spillImpossible:
504 ArrayRef<unsigned> AO = RegClassInfo.getOrder(RC);
506 // First try to find a completely free register.
507 for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
508 unsigned PhysReg = *I;
509 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg))
510 return assignVirtToPhysReg(LRE, PhysReg);
513 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
514 << RC->getName() << "\n");
516 unsigned BestReg = 0, BestCost = spillImpossible;
517 for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
518 unsigned Cost = calcSpillCost(*I);
519 DEBUG(dbgs() << "\tRegister: " << *I << "\n");
520 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
521 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
522 // Cost is 0 when all aliases are already disabled.
524 return assignVirtToPhysReg(LRE, *I);
526 BestReg = *I, BestCost = Cost;
530 definePhysReg(MI, BestReg, regFree);
531 return assignVirtToPhysReg(LRE, BestReg);
534 // Nothing we can do.
536 raw_string_ostream Msg(msg);
537 Msg << "Ran out of registers during register allocation!";
538 if (MI->isInlineAsm()) {
539 Msg << "\nPlease check your inline asm statement for "
540 << "invalid constraints:\n";
543 report_fatal_error(Msg.str());
546 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
547 RAFast::LiveRegMap::iterator
548 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
549 unsigned VirtReg, unsigned Hint) {
550 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
551 "Not a virtual register");
552 LiveRegMap::iterator LRI;
554 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
555 LiveReg &LR = LRI->second;
557 // If there is no hint, peek at the only use of this register.
558 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
559 MRI->hasOneNonDBGUse(VirtReg)) {
560 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
561 // It's a copy, use the destination register as a hint.
562 if (UseMI.isCopyLike())
563 Hint = UseMI.getOperand(0).getReg();
565 allocVirtReg(MI, *LRI, Hint);
566 } else if (LR.LastUse) {
567 // Redefining a live register - kill at the last use, unless it is this
568 // instruction defining VirtReg multiple times.
569 if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
572 assert(LR.PhysReg && "Register not assigned");
574 LR.LastOpNum = OpNum;
576 UsedInInstr.set(LR.PhysReg);
580 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
581 RAFast::LiveRegMap::iterator
582 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
583 unsigned VirtReg, unsigned Hint) {
584 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
585 "Not a virtual register");
586 LiveRegMap::iterator LRI;
588 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
589 LiveReg &LR = LRI->second;
590 MachineOperand &MO = MI->getOperand(OpNum);
592 allocVirtReg(MI, *LRI, Hint);
593 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
594 int FrameIndex = getStackSpaceFor(VirtReg, RC);
595 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
596 << PrintReg(LR.PhysReg, TRI) << "\n");
597 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
599 } else if (LR.Dirty) {
600 if (isLastUseOfLocalReg(MO)) {
601 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
606 } else if (MO.isKill()) {
607 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
609 } else if (MO.isDead()) {
610 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
613 } else if (MO.isKill()) {
614 // We must remove kill flags from uses of reloaded registers because the
615 // register would be killed immediately, and there might be a second use:
616 // %foo = OR %x<kill>, %x
617 // This would cause a second reload of %x into a different register.
618 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
620 } else if (MO.isDead()) {
621 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
624 assert(LR.PhysReg && "Register not assigned");
626 LR.LastOpNum = OpNum;
627 UsedInInstr.set(LR.PhysReg);
631 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
632 // subregs. This may invalidate any operand pointers.
633 // Return true if the operand kills its register.
634 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
635 MachineOperand &MO = MI->getOperand(OpNum);
636 if (!MO.getSubReg()) {
638 return MO.isKill() || MO.isDead();
641 // Handle subregister index.
642 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
645 // A kill flag implies killing the full register. Add corresponding super
648 MI->addRegisterKilled(PhysReg, TRI, true);
654 // Handle special instruction operand like early clobbers and tied ops when
655 // there are additional physreg defines.
656 void RAFast::handleThroughOperands(MachineInstr *MI,
657 SmallVectorImpl<unsigned> &VirtDead) {
658 DEBUG(dbgs() << "Scanning for through registers:");
659 SmallSet<unsigned, 8> ThroughRegs;
660 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
661 MachineOperand &MO = MI->getOperand(i);
662 if (!MO.isReg()) continue;
663 unsigned Reg = MO.getReg();
664 if (!TargetRegisterInfo::isVirtualRegister(Reg))
666 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
667 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
668 if (ThroughRegs.insert(Reg))
669 DEBUG(dbgs() << ' ' << PrintReg(Reg));
673 // If any physreg defines collide with preallocated through registers,
674 // we must spill and reallocate.
675 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
676 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
677 MachineOperand &MO = MI->getOperand(i);
678 if (!MO.isReg() || !MO.isDef()) continue;
679 unsigned Reg = MO.getReg();
680 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
681 UsedInInstr.set(Reg);
682 if (ThroughRegs.count(PhysRegState[Reg]))
683 definePhysReg(MI, Reg, regFree);
684 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
685 UsedInInstr.set(*AS);
686 if (ThroughRegs.count(PhysRegState[*AS]))
687 definePhysReg(MI, *AS, regFree);
691 SmallVector<unsigned, 8> PartialDefs;
692 DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
693 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
694 MachineOperand &MO = MI->getOperand(i);
695 if (!MO.isReg()) continue;
696 unsigned Reg = MO.getReg();
697 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
700 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
701 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
703 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
704 unsigned PhysReg = LRI->second.PhysReg;
705 setPhysReg(MI, i, PhysReg);
706 // Note: we don't update the def operand yet. That would cause the normal
707 // def-scan to attempt spilling.
708 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
709 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
710 // Reload the register, but don't assign to the operand just yet.
711 // That would confuse the later phys-def processing pass.
712 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
713 PartialDefs.push_back(LRI->second.PhysReg);
714 } else if (MO.isEarlyClobber()) {
715 // Note: defineVirtReg may invalidate MO.
716 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
717 unsigned PhysReg = LRI->second.PhysReg;
718 if (setPhysReg(MI, i, PhysReg))
719 VirtDead.push_back(Reg);
723 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
725 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
726 MachineOperand &MO = MI->getOperand(i);
727 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
728 unsigned Reg = MO.getReg();
729 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
730 DEBUG(dbgs() << "\tSetting reg " << Reg << " as used in instr\n");
731 UsedInInstr.set(Reg);
734 // Also mark PartialDefs as used to avoid reallocation.
735 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
736 UsedInInstr.set(PartialDefs[i]);
739 void RAFast::AllocateBasicBlock() {
740 DEBUG(dbgs() << "\nAllocating " << *MBB);
742 // FIXME: This should probably be added by instruction selection instead?
743 // If the last instruction in the block is a return, make sure to mark it as
744 // using all of the live-out values in the function. Things marked both call
745 // and return are tail calls; do not do this for them. The tail callee need
746 // not take the same registers as input that it produces as output, and there
747 // are dependencies for its input registers elsewhere.
748 if (!MBB->empty() && MBB->back().getDesc().isReturn() &&
749 !MBB->back().getDesc().isCall()) {
750 MachineInstr *Ret = &MBB->back();
752 for (MachineRegisterInfo::liveout_iterator
753 I = MF->getRegInfo().liveout_begin(),
754 E = MF->getRegInfo().liveout_end(); I != E; ++I) {
755 assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
756 "Cannot have a live-out virtual register.");
758 // Add live-out registers as implicit uses.
759 Ret->addRegisterKilled(*I, TRI, true);
763 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
764 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
766 MachineBasicBlock::iterator MII = MBB->begin();
768 // Add live-in registers as live.
769 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
770 E = MBB->livein_end(); I != E; ++I)
771 if (Allocatable.test(*I))
772 definePhysReg(MII, *I, regReserved);
774 SmallVector<unsigned, 8> VirtDead;
775 SmallVector<MachineInstr*, 32> Coalesced;
777 // Otherwise, sequentially allocate each instruction in the MBB.
778 while (MII != MBB->end()) {
779 MachineInstr *MI = MII++;
780 const TargetInstrDesc &TID = MI->getDesc();
782 dbgs() << "\n>> " << *MI << "Regs:";
783 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
784 if (PhysRegState[Reg] == regDisabled) continue;
785 dbgs() << " " << TRI->getName(Reg);
786 switch(PhysRegState[Reg]) {
793 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
794 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
796 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
802 // Check that LiveVirtRegs is the inverse.
803 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
804 e = LiveVirtRegs.end(); i != e; ++i) {
805 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
807 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
809 assert(PhysRegState[i->second.PhysReg] == i->first &&
814 // Debug values are not allowed to change codegen in any way.
815 if (MI->isDebugValue()) {
816 bool ScanDbgValue = true;
817 while (ScanDbgValue) {
818 ScanDbgValue = false;
819 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
820 MachineOperand &MO = MI->getOperand(i);
821 if (!MO.isReg()) continue;
822 unsigned Reg = MO.getReg();
823 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
824 LiveDbgValueMap[Reg] = MI;
825 LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
826 if (LRI != LiveVirtRegs.end())
827 setPhysReg(MI, i, LRI->second.PhysReg);
829 int SS = StackSlotForVirtReg[Reg];
831 // We can't allocate a physreg for a DebugValue, sorry!
832 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
836 // Modify DBG_VALUE now that the value is in a spill slot.
837 int64_t Offset = MI->getOperand(1).getImm();
838 const MDNode *MDPtr =
839 MI->getOperand(MI->getNumOperands()-1).getMetadata();
840 DebugLoc DL = MI->getDebugLoc();
841 if (MachineInstr *NewDV =
842 TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
843 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
845 MachineBasicBlock *MBB = MI->getParent();
846 MBB->insert(MBB->erase(MI), NewDV);
847 // Scan NewDV operands from the beginning.
852 // We can't allocate a physreg for a DebugValue; sorry!
853 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
864 // If this is a copy, we may be able to coalesce.
865 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
867 CopyDst = MI->getOperand(0).getReg();
868 CopySrc = MI->getOperand(1).getReg();
869 CopyDstSub = MI->getOperand(0).getSubReg();
870 CopySrcSub = MI->getOperand(1).getSubReg();
873 // Track registers used by instruction.
877 // Mark physreg uses and early clobbers as used.
878 // Find the end of the virtreg operands
879 unsigned VirtOpEnd = 0;
880 bool hasTiedOps = false;
881 bool hasEarlyClobbers = false;
882 bool hasPartialRedefs = false;
883 bool hasPhysDefs = false;
884 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
885 MachineOperand &MO = MI->getOperand(i);
886 if (!MO.isReg()) continue;
887 unsigned Reg = MO.getReg();
889 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
892 hasTiedOps = hasTiedOps ||
893 TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
895 if (MO.isEarlyClobber())
896 hasEarlyClobbers = true;
897 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
898 hasPartialRedefs = true;
902 if (!Allocatable.test(Reg)) continue;
905 } else if (MO.isEarlyClobber()) {
906 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
907 regFree : regReserved);
908 hasEarlyClobbers = true;
913 // The instruction may have virtual register operands that must be allocated
914 // the same register at use-time and def-time: early clobbers and tied
915 // operands. If there are also physical defs, these registers must avoid
916 // both physical defs and uses, making them more constrained than normal
918 // Similarly, if there are multiple defs and tied operands, we must make
919 // sure the same register is allocated to uses and defs.
920 // We didn't detect inline asm tied operands above, so just make this extra
921 // pass for all inline asm.
922 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
923 (hasTiedOps && (hasPhysDefs || TID.getNumDefs() > 1))) {
924 handleThroughOperands(MI, VirtDead);
925 // Don't attempt coalescing when we have funny stuff going on.
927 // Pretend we have early clobbers so the use operands get marked below.
928 // This is not necessary for the common case of a single tied use.
929 hasEarlyClobbers = true;
933 // Allocate virtreg uses.
934 for (unsigned i = 0; i != VirtOpEnd; ++i) {
935 MachineOperand &MO = MI->getOperand(i);
936 if (!MO.isReg()) continue;
937 unsigned Reg = MO.getReg();
938 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
940 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
941 unsigned PhysReg = LRI->second.PhysReg;
942 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
943 if (setPhysReg(MI, i, PhysReg))
948 MRI->addPhysRegsUsed(UsedInInstr);
950 // Track registers defined by instruction - early clobbers and tied uses at
953 if (hasEarlyClobbers) {
954 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
955 MachineOperand &MO = MI->getOperand(i);
956 if (!MO.isReg()) continue;
957 unsigned Reg = MO.getReg();
958 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
959 // Look for physreg defs and tied uses.
960 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
961 UsedInInstr.set(Reg);
962 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
963 UsedInInstr.set(*AS);
967 unsigned DefOpEnd = MI->getNumOperands();
969 // Spill all virtregs before a call. This serves two purposes: 1. If an
970 // exception is thrown, the landing pad is going to expect to find
971 // registers in their spill slots, and 2. we don't have to wade through
972 // all the <imp-def> operands on the call instruction.
973 DefOpEnd = VirtOpEnd;
974 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
977 // The imp-defs are skipped below, but we still need to mark those
978 // registers as used by the function.
979 SkippedInstrs.insert(&TID);
983 // Allocate defs and collect dead defs.
984 for (unsigned i = 0; i != DefOpEnd; ++i) {
985 MachineOperand &MO = MI->getOperand(i);
986 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
988 unsigned Reg = MO.getReg();
990 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
991 if (!Allocatable.test(Reg)) continue;
992 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
993 regFree : regReserved);
996 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
997 unsigned PhysReg = LRI->second.PhysReg;
998 if (setPhysReg(MI, i, PhysReg)) {
999 VirtDead.push_back(Reg);
1000 CopyDst = 0; // cancel coalescing;
1002 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1005 // Kill dead defs after the scan to ensure that multiple defs of the same
1006 // register are allocated identically. We didn't need to do this for uses
1007 // because we are crerating our own kill flags, and they are always at the
1009 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1010 killVirtReg(VirtDead[i]);
1013 MRI->addPhysRegsUsed(UsedInInstr);
1015 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1016 DEBUG(dbgs() << "-- coalescing: " << *MI);
1017 Coalesced.push_back(MI);
1019 DEBUG(dbgs() << "<< " << *MI);
1023 // Spill all physical registers holding virtual registers now.
1024 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1025 spillAll(MBB->getFirstTerminator());
1027 // Erase all the coalesced copies. We are delaying it until now because
1028 // LiveVirtRegs might refer to the instrs.
1029 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1030 MBB->erase(Coalesced[i]);
1031 NumCopies += Coalesced.size();
1036 /// runOnMachineFunction - Register allocate the whole function
1038 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1039 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1040 << "********** Function: "
1041 << ((Value*)Fn.getFunction())->getName() << '\n');
1043 MRI = &MF->getRegInfo();
1044 TM = &Fn.getTarget();
1045 TRI = TM->getRegisterInfo();
1046 TII = TM->getInstrInfo();
1047 RegClassInfo.runOnMachineFunction(Fn);
1049 UsedInInstr.resize(TRI->getNumRegs());
1050 Allocatable = TRI->getAllocatableSet(*MF);
1052 // initialize the virtual->physical register map to have a 'null'
1053 // mapping for all virtual registers
1054 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1056 // Loop over all of the basic blocks, eliminating virtual register references
1057 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1058 MBBi != MBBe; ++MBBi) {
1060 AllocateBasicBlock();
1063 // Make sure the set of used physregs is closed under subreg operations.
1064 MRI->closePhysRegsUsed(*TRI);
1066 // Add the clobber lists for all the instructions we skipped earlier.
1067 for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
1068 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1069 if (const unsigned *Defs = (*I)->getImplicitDefs())
1071 MRI->setPhysRegUsed(*Defs++);
1073 SkippedInstrs.clear();
1074 StackSlotForVirtReg.clear();
1075 LiveDbgValueMap.clear();
1079 FunctionPass *llvm::createFastRegisterAllocator() {
1080 return new RAFast();