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/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/CodeGen/RegAllocRegistry.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/IndexedMap.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumCopies, "Number of copies coalesced");
43 static RegisterRegAlloc
44 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
47 class RAFast : public MachineFunctionPass {
50 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
51 isBulkSpilling(false) {
52 initializePHIEliminationPass(*PassRegistry::getPassRegistry());
53 initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
56 const TargetMachine *TM;
58 MachineRegisterInfo *MRI;
59 const TargetRegisterInfo *TRI;
60 const TargetInstrInfo *TII;
62 // Basic block currently being allocated.
63 MachineBasicBlock *MBB;
65 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
66 // values are spilled.
67 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
69 // Everything we know about a live virtual register.
71 MachineInstr *LastUse; // Last instr to use reg.
72 unsigned PhysReg; // Currently held here.
73 unsigned short LastOpNum; // OpNum on LastUse.
74 bool Dirty; // Register needs spill.
76 LiveReg(unsigned p=0) : LastUse(0), PhysReg(p), LastOpNum(0),
80 typedef DenseMap<unsigned, LiveReg> LiveRegMap;
81 typedef LiveRegMap::value_type LiveRegEntry;
83 // LiveVirtRegs - This map contains entries for each virtual register
84 // that is currently available in a physical register.
85 LiveRegMap LiveVirtRegs;
87 DenseMap<unsigned, MachineInstr *> LiveDbgValueMap;
89 // RegState - Track the state of a physical register.
91 // A disabled register is not available for allocation, but an alias may
92 // be in use. A register can only be moved out of the disabled state if
93 // all aliases are disabled.
96 // A free register is not currently in use and can be allocated
97 // immediately without checking aliases.
100 // A reserved register has been assigned explicitly (e.g., setting up a
101 // call parameter), and it remains reserved until it is used.
104 // A register state may also be a virtual register number, indication that
105 // the physical register is currently allocated to a virtual register. In
106 // that case, LiveVirtRegs contains the inverse mapping.
109 // PhysRegState - One of the RegState enums, or a virtreg.
110 std::vector<unsigned> PhysRegState;
112 // UsedInInstr - BitVector of physregs that are used in the current
113 // instruction, and so cannot be allocated.
114 BitVector UsedInInstr;
116 // Allocatable - vector of allocatable physical registers.
117 BitVector Allocatable;
119 // SkippedInstrs - Descriptors of instructions whose clobber list was
120 // ignored because all registers were spilled. It is still necessary to
121 // mark all the clobbered registers as used by the function.
122 SmallPtrSet<const TargetInstrDesc*, 4> SkippedInstrs;
124 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
125 // completely after spilling all live registers. LiveRegMap entries should
132 spillImpossible = ~0u
135 virtual const char *getPassName() const {
136 return "Fast Register Allocator";
139 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
140 AU.setPreservesCFG();
141 AU.addRequiredID(PHIEliminationID);
142 AU.addRequiredID(TwoAddressInstructionPassID);
143 MachineFunctionPass::getAnalysisUsage(AU);
147 bool runOnMachineFunction(MachineFunction &Fn);
148 void AllocateBasicBlock();
149 void handleThroughOperands(MachineInstr *MI,
150 SmallVectorImpl<unsigned> &VirtDead);
151 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
152 bool isLastUseOfLocalReg(MachineOperand&);
154 void addKillFlag(const LiveReg&);
155 void killVirtReg(LiveRegMap::iterator);
156 void killVirtReg(unsigned VirtReg);
157 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
158 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
160 void usePhysReg(MachineOperand&);
161 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
162 unsigned calcSpillCost(unsigned PhysReg) const;
163 void assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg);
164 void allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint);
165 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
166 unsigned VirtReg, unsigned Hint);
167 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
168 unsigned VirtReg, unsigned Hint);
169 void spillAll(MachineInstr *MI);
170 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
175 /// getStackSpaceFor - This allocates space for the specified virtual register
176 /// to be held on the stack.
177 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
178 // Find the location Reg would belong...
179 int SS = StackSlotForVirtReg[VirtReg];
181 return SS; // Already has space allocated?
183 // Allocate a new stack object for this spill location...
184 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
188 StackSlotForVirtReg[VirtReg] = FrameIdx;
192 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
193 /// its virtual register, and it is guaranteed to be a block-local register.
195 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
196 // Check for non-debug uses or defs following MO.
197 // This is the most likely way to fail - fast path it.
198 MachineOperand *Next = &MO;
199 while ((Next = Next->getNextOperandForReg()))
200 if (!Next->isDebug())
203 // If the register has ever been spilled or reloaded, we conservatively assume
204 // it is a global register used in multiple blocks.
205 if (StackSlotForVirtReg[MO.getReg()] != -1)
208 // Check that the use/def chain has exactly one operand - MO.
209 return &MRI->reg_nodbg_begin(MO.getReg()).getOperand() == &MO;
212 /// addKillFlag - Set kill flags on last use of a virtual register.
213 void RAFast::addKillFlag(const LiveReg &LR) {
214 if (!LR.LastUse) return;
215 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
216 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
217 if (MO.getReg() == LR.PhysReg)
220 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
224 /// killVirtReg - Mark virtreg as no longer available.
225 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
226 addKillFlag(LRI->second);
227 const LiveReg &LR = LRI->second;
228 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
229 PhysRegState[LR.PhysReg] = regFree;
230 // Erase from LiveVirtRegs unless we're spilling in bulk.
232 LiveVirtRegs.erase(LRI);
235 /// killVirtReg - Mark virtreg as no longer available.
236 void RAFast::killVirtReg(unsigned VirtReg) {
237 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
238 "killVirtReg needs a virtual register");
239 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
240 if (LRI != LiveVirtRegs.end())
244 /// spillVirtReg - This method spills the value specified by VirtReg into the
245 /// corresponding stack slot if needed.
246 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
247 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
248 "Spilling a physical register is illegal!");
249 LiveRegMap::iterator LRI = LiveVirtRegs.find(VirtReg);
250 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
251 spillVirtReg(MI, LRI);
254 /// spillVirtReg - Do the actual work of spilling.
255 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
256 LiveRegMap::iterator LRI) {
257 LiveReg &LR = LRI->second;
258 assert(PhysRegState[LR.PhysReg] == LRI->first && "Broken RegState mapping");
261 // If this physreg is used by the instruction, we want to kill it on the
262 // instruction, not on the spill.
263 bool SpillKill = LR.LastUse != MI;
265 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->first, TRI)
266 << " in " << PrintReg(LR.PhysReg, TRI));
267 const TargetRegisterClass *RC = MRI->getRegClass(LRI->first);
268 int FI = getStackSpaceFor(LRI->first, RC);
269 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
270 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
271 ++NumStores; // Update statistics
273 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
274 // identify spilled location as the place to find corresponding variable's
276 if (MachineInstr *DBG = LiveDbgValueMap.lookup(LRI->first)) {
277 const MDNode *MDPtr =
278 DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
280 if (DBG->getOperand(1).isImm())
281 Offset = DBG->getOperand(1).getImm();
283 if (MI == MBB->end()) {
284 // If MI is at basic block end then use last instruction's location.
285 MachineBasicBlock::iterator EI = MI;
286 DL = (--EI)->getDebugLoc();
289 DL = MI->getDebugLoc();
290 if (MachineInstr *NewDV =
291 TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
292 MachineBasicBlock *MBB = DBG->getParent();
293 MBB->insert(MI, NewDV);
294 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
295 LiveDbgValueMap[LRI->first] = NewDV;
299 LR.LastUse = 0; // Don't kill register again
304 /// spillAll - Spill all dirty virtregs without killing them.
305 void RAFast::spillAll(MachineInstr *MI) {
306 if (LiveVirtRegs.empty()) return;
307 isBulkSpilling = true;
308 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
309 // of spilling here is deterministic, if arbitrary.
310 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
313 LiveVirtRegs.clear();
314 isBulkSpilling = false;
317 /// usePhysReg - Handle the direct use of a physical register.
318 /// Check that the register is not used by a virtreg.
319 /// Kill the physreg, marking it free.
320 /// This may add implicit kills to MO->getParent() and invalidate MO.
321 void RAFast::usePhysReg(MachineOperand &MO) {
322 unsigned PhysReg = MO.getReg();
323 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
324 "Bad usePhysReg operand");
326 switch (PhysRegState[PhysReg]) {
330 PhysRegState[PhysReg] = regFree;
333 UsedInInstr.set(PhysReg);
337 // The physreg was allocated to a virtual register. That means the value we
338 // wanted has been clobbered.
339 llvm_unreachable("Instruction uses an allocated register");
342 // Maybe a superregister is reserved?
343 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
344 unsigned Alias = *AS; ++AS) {
345 switch (PhysRegState[Alias]) {
349 assert(TRI->isSuperRegister(PhysReg, Alias) &&
350 "Instruction is not using a subregister of a reserved register");
351 // Leave the superregister in the working set.
352 PhysRegState[Alias] = regFree;
353 UsedInInstr.set(Alias);
354 MO.getParent()->addRegisterKilled(Alias, TRI, true);
357 if (TRI->isSuperRegister(PhysReg, Alias)) {
358 // Leave the superregister in the working set.
359 UsedInInstr.set(Alias);
360 MO.getParent()->addRegisterKilled(Alias, TRI, true);
363 // Some other alias was in the working set - clear it.
364 PhysRegState[Alias] = regDisabled;
367 llvm_unreachable("Instruction uses an alias of an allocated register");
371 // All aliases are disabled, bring register into working set.
372 PhysRegState[PhysReg] = regFree;
373 UsedInInstr.set(PhysReg);
377 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
378 /// virtregs. This is very similar to defineVirtReg except the physreg is
379 /// reserved instead of allocated.
380 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
382 UsedInInstr.set(PhysReg);
383 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
387 spillVirtReg(MI, VirtReg);
391 PhysRegState[PhysReg] = NewState;
395 // This is a disabled register, disable all aliases.
396 PhysRegState[PhysReg] = NewState;
397 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
398 unsigned Alias = *AS; ++AS) {
399 switch (unsigned VirtReg = PhysRegState[Alias]) {
403 spillVirtReg(MI, VirtReg);
407 PhysRegState[Alias] = regDisabled;
408 if (TRI->isSuperRegister(PhysReg, Alias))
416 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
417 // aliases so it is free for allocation.
418 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
419 // can be allocated directly.
420 // Returns spillImpossible when PhysReg or an alias can't be spilled.
421 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
422 if (UsedInInstr.test(PhysReg)) {
423 DEBUG(dbgs() << "PhysReg: " << PhysReg << " is already used in instr.\n");
424 return spillImpossible;
426 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
432 DEBUG(dbgs() << "VirtReg: " << VirtReg << " corresponding to PhysReg: "
433 << PhysReg << " is reserved already.\n");
434 return spillImpossible;
436 return LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
439 // This is a disabled register, add up cost of aliases.
440 DEBUG(dbgs() << "\tRegister: " << PhysReg << " is disabled.\n");
442 for (const unsigned *AS = TRI->getAliasSet(PhysReg);
443 unsigned Alias = *AS; ++AS) {
444 if (UsedInInstr.test(Alias))
445 return spillImpossible;
446 switch (unsigned VirtReg = PhysRegState[Alias]) {
453 return spillImpossible;
455 Cost += LiveVirtRegs.lookup(VirtReg).Dirty ? spillDirty : spillClean;
463 /// assignVirtToPhysReg - This method updates local state so that we know
464 /// that PhysReg is the proper container for VirtReg now. The physical
465 /// register must not be used for anything else when this is called.
467 void RAFast::assignVirtToPhysReg(LiveRegEntry &LRE, unsigned PhysReg) {
468 DEBUG(dbgs() << "Assigning " << PrintReg(LRE.first, TRI) << " to "
469 << PrintReg(PhysReg, TRI) << "\n");
470 PhysRegState[PhysReg] = LRE.first;
471 assert(!LRE.second.PhysReg && "Already assigned a physreg");
472 LRE.second.PhysReg = PhysReg;
475 /// allocVirtReg - Allocate a physical register for VirtReg.
476 void RAFast::allocVirtReg(MachineInstr *MI, LiveRegEntry &LRE, unsigned Hint) {
477 const unsigned VirtReg = LRE.first;
479 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
480 "Can only allocate virtual registers");
482 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
484 // Ignore invalid hints.
485 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
486 !RC->contains(Hint) || !Allocatable.test(Hint)))
489 // Take hint when possible.
491 switch(calcSpillCost(Hint)) {
493 definePhysReg(MI, Hint, regFree);
496 return assignVirtToPhysReg(LRE, Hint);
497 case spillImpossible:
502 TargetRegisterClass::iterator AOB = RC->allocation_order_begin(*MF);
503 TargetRegisterClass::iterator AOE = RC->allocation_order_end(*MF);
505 // First try to find a completely free register.
506 for (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
507 unsigned PhysReg = *I;
508 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.test(PhysReg) &&
509 Allocatable.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 (TargetRegisterClass::iterator I = AOB; I != AOE; ++I) {
518 if (!Allocatable.test(*I)) {
519 DEBUG(dbgs() << "\tRegister " << *I << " is not allocatable.\n");
522 unsigned Cost = calcSpillCost(*I);
523 DEBUG(dbgs() << "\tRegister: " << *I << "\n");
524 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
525 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
526 // Cost is 0 when all aliases are already disabled.
528 return assignVirtToPhysReg(LRE, *I);
530 BestReg = *I, BestCost = Cost;
534 definePhysReg(MI, BestReg, regFree);
535 return assignVirtToPhysReg(LRE, BestReg);
538 // Nothing we can do.
540 raw_string_ostream Msg(msg);
541 Msg << "Ran out of registers during register allocation!";
542 if (MI->isInlineAsm()) {
543 Msg << "\nPlease check your inline asm statement for "
544 << "invalid constraints:\n";
547 report_fatal_error(Msg.str());
550 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
551 RAFast::LiveRegMap::iterator
552 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
553 unsigned VirtReg, unsigned Hint) {
554 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
555 "Not a virtual register");
556 LiveRegMap::iterator LRI;
558 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
559 LiveReg &LR = LRI->second;
561 // If there is no hint, peek at the only use of this register.
562 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
563 MRI->hasOneNonDBGUse(VirtReg)) {
564 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
565 // It's a copy, use the destination register as a hint.
566 if (UseMI.isCopyLike())
567 Hint = UseMI.getOperand(0).getReg();
569 allocVirtReg(MI, *LRI, Hint);
570 } else if (LR.LastUse) {
571 // Redefining a live register - kill at the last use, unless it is this
572 // instruction defining VirtReg multiple times.
573 if (LR.LastUse != MI || LR.LastUse->getOperand(LR.LastOpNum).isUse())
576 assert(LR.PhysReg && "Register not assigned");
578 LR.LastOpNum = OpNum;
580 UsedInInstr.set(LR.PhysReg);
584 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
585 RAFast::LiveRegMap::iterator
586 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
587 unsigned VirtReg, unsigned Hint) {
588 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
589 "Not a virtual register");
590 LiveRegMap::iterator LRI;
592 tie(LRI, New) = LiveVirtRegs.insert(std::make_pair(VirtReg, LiveReg()));
593 LiveReg &LR = LRI->second;
594 MachineOperand &MO = MI->getOperand(OpNum);
596 allocVirtReg(MI, *LRI, Hint);
597 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
598 int FrameIndex = getStackSpaceFor(VirtReg, RC);
599 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
600 << PrintReg(LR.PhysReg, TRI) << "\n");
601 TII->loadRegFromStackSlot(*MBB, MI, LR.PhysReg, FrameIndex, RC, TRI);
603 } else if (LR.Dirty) {
604 if (isLastUseOfLocalReg(MO)) {
605 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
610 } else if (MO.isKill()) {
611 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
613 } else if (MO.isDead()) {
614 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
617 } else if (MO.isKill()) {
618 // We must remove kill flags from uses of reloaded registers because the
619 // register would be killed immediately, and there might be a second use:
620 // %foo = OR %x<kill>, %x
621 // This would cause a second reload of %x into a different register.
622 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
624 } else if (MO.isDead()) {
625 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
628 assert(LR.PhysReg && "Register not assigned");
630 LR.LastOpNum = OpNum;
631 UsedInInstr.set(LR.PhysReg);
635 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
636 // subregs. This may invalidate any operand pointers.
637 // Return true if the operand kills its register.
638 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
639 MachineOperand &MO = MI->getOperand(OpNum);
640 if (!MO.getSubReg()) {
642 return MO.isKill() || MO.isDead();
645 // Handle subregister index.
646 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
649 // A kill flag implies killing the full register. Add corresponding super
652 MI->addRegisterKilled(PhysReg, TRI, true);
658 // Handle special instruction operand like early clobbers and tied ops when
659 // there are additional physreg defines.
660 void RAFast::handleThroughOperands(MachineInstr *MI,
661 SmallVectorImpl<unsigned> &VirtDead) {
662 DEBUG(dbgs() << "Scanning for through registers:");
663 SmallSet<unsigned, 8> ThroughRegs;
664 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
665 MachineOperand &MO = MI->getOperand(i);
666 if (!MO.isReg()) continue;
667 unsigned Reg = MO.getReg();
668 if (!TargetRegisterInfo::isVirtualRegister(Reg))
670 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
671 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
672 if (ThroughRegs.insert(Reg))
673 DEBUG(dbgs() << ' ' << PrintReg(Reg));
677 // If any physreg defines collide with preallocated through registers,
678 // we must spill and reallocate.
679 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
680 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
681 MachineOperand &MO = MI->getOperand(i);
682 if (!MO.isReg() || !MO.isDef()) continue;
683 unsigned Reg = MO.getReg();
684 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
685 UsedInInstr.set(Reg);
686 if (ThroughRegs.count(PhysRegState[Reg]))
687 definePhysReg(MI, Reg, regFree);
688 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
689 UsedInInstr.set(*AS);
690 if (ThroughRegs.count(PhysRegState[*AS]))
691 definePhysReg(MI, *AS, regFree);
695 SmallVector<unsigned, 8> PartialDefs;
696 DEBUG(dbgs() << "Allocating tied uses and early clobbers.\n");
697 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
698 MachineOperand &MO = MI->getOperand(i);
699 if (!MO.isReg()) continue;
700 unsigned Reg = MO.getReg();
701 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
704 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
705 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
707 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
708 unsigned PhysReg = LRI->second.PhysReg;
709 setPhysReg(MI, i, PhysReg);
710 // Note: we don't update the def operand yet. That would cause the normal
711 // def-scan to attempt spilling.
712 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
713 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
714 // Reload the register, but don't assign to the operand just yet.
715 // That would confuse the later phys-def processing pass.
716 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
717 PartialDefs.push_back(LRI->second.PhysReg);
718 } else if (MO.isEarlyClobber()) {
719 // Note: defineVirtReg may invalidate MO.
720 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
721 unsigned PhysReg = LRI->second.PhysReg;
722 if (setPhysReg(MI, i, PhysReg))
723 VirtDead.push_back(Reg);
727 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
729 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
730 MachineOperand &MO = MI->getOperand(i);
731 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
732 unsigned Reg = MO.getReg();
733 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
734 DEBUG(dbgs() << "\tSetting reg " << Reg << " as used in instr\n");
735 UsedInInstr.set(Reg);
738 // Also mark PartialDefs as used to avoid reallocation.
739 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
740 UsedInInstr.set(PartialDefs[i]);
743 void RAFast::AllocateBasicBlock() {
744 DEBUG(dbgs() << "\nAllocating " << *MBB);
746 // FIXME: This should probably be added by instruction selection instead?
747 // If the last instruction in the block is a return, make sure to mark it as
748 // using all of the live-out values in the function. Things marked both call
749 // and return are tail calls; do not do this for them. The tail callee need
750 // not take the same registers as input that it produces as output, and there
751 // are dependencies for its input registers elsewhere.
752 if (!MBB->empty() && MBB->back().getDesc().isReturn() &&
753 !MBB->back().getDesc().isCall()) {
754 MachineInstr *Ret = &MBB->back();
756 for (MachineRegisterInfo::liveout_iterator
757 I = MF->getRegInfo().liveout_begin(),
758 E = MF->getRegInfo().liveout_end(); I != E; ++I) {
759 assert(TargetRegisterInfo::isPhysicalRegister(*I) &&
760 "Cannot have a live-out virtual register.");
762 // Add live-out registers as implicit uses.
763 Ret->addRegisterKilled(*I, TRI, true);
767 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
768 assert(LiveVirtRegs.empty() && "Mapping not cleared form last block?");
770 MachineBasicBlock::iterator MII = MBB->begin();
772 // Add live-in registers as live.
773 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
774 E = MBB->livein_end(); I != E; ++I)
775 if (Allocatable.test(*I))
776 definePhysReg(MII, *I, regReserved);
778 SmallVector<unsigned, 8> VirtDead;
779 SmallVector<MachineInstr*, 32> Coalesced;
781 // Otherwise, sequentially allocate each instruction in the MBB.
782 while (MII != MBB->end()) {
783 MachineInstr *MI = MII++;
784 const TargetInstrDesc &TID = MI->getDesc();
786 dbgs() << "\n>> " << *MI << "Regs:";
787 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
788 if (PhysRegState[Reg] == regDisabled) continue;
789 dbgs() << " " << TRI->getName(Reg);
790 switch(PhysRegState[Reg]) {
797 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
798 if (LiveVirtRegs[PhysRegState[Reg]].Dirty)
800 assert(LiveVirtRegs[PhysRegState[Reg]].PhysReg == Reg &&
806 // Check that LiveVirtRegs is the inverse.
807 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
808 e = LiveVirtRegs.end(); i != e; ++i) {
809 assert(TargetRegisterInfo::isVirtualRegister(i->first) &&
811 assert(TargetRegisterInfo::isPhysicalRegister(i->second.PhysReg) &&
813 assert(PhysRegState[i->second.PhysReg] == i->first &&
818 // Debug values are not allowed to change codegen in any way.
819 if (MI->isDebugValue()) {
820 bool ScanDbgValue = true;
821 while (ScanDbgValue) {
822 ScanDbgValue = false;
823 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
824 MachineOperand &MO = MI->getOperand(i);
825 if (!MO.isReg()) continue;
826 unsigned Reg = MO.getReg();
827 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
828 LiveDbgValueMap[Reg] = MI;
829 LiveRegMap::iterator LRI = LiveVirtRegs.find(Reg);
830 if (LRI != LiveVirtRegs.end())
831 setPhysReg(MI, i, LRI->second.PhysReg);
833 int SS = StackSlotForVirtReg[Reg];
835 // We can't allocate a physreg for a DebugValue, sorry!
836 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
840 // Modify DBG_VALUE now that the value is in a spill slot.
841 int64_t Offset = MI->getOperand(1).getImm();
842 const MDNode *MDPtr =
843 MI->getOperand(MI->getNumOperands()-1).getMetadata();
844 DebugLoc DL = MI->getDebugLoc();
845 if (MachineInstr *NewDV =
846 TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
847 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
849 MachineBasicBlock *MBB = MI->getParent();
850 MBB->insert(MBB->erase(MI), NewDV);
851 // Scan NewDV operands from the beginning.
856 // We can't allocate a physreg for a DebugValue; sorry!
857 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
868 // If this is a copy, we may be able to coalesce.
869 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
871 CopyDst = MI->getOperand(0).getReg();
872 CopySrc = MI->getOperand(1).getReg();
873 CopyDstSub = MI->getOperand(0).getSubReg();
874 CopySrcSub = MI->getOperand(1).getSubReg();
877 // Track registers used by instruction.
881 // Mark physreg uses and early clobbers as used.
882 // Find the end of the virtreg operands
883 unsigned VirtOpEnd = 0;
884 bool hasTiedOps = false;
885 bool hasEarlyClobbers = false;
886 bool hasPartialRedefs = false;
887 bool hasPhysDefs = false;
888 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
889 MachineOperand &MO = MI->getOperand(i);
890 if (!MO.isReg()) continue;
891 unsigned Reg = MO.getReg();
893 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
896 hasTiedOps = hasTiedOps ||
897 TID.getOperandConstraint(i, TOI::TIED_TO) != -1;
899 if (MO.isEarlyClobber())
900 hasEarlyClobbers = true;
901 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
902 hasPartialRedefs = true;
906 if (!Allocatable.test(Reg)) continue;
909 } else if (MO.isEarlyClobber()) {
910 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
911 regFree : regReserved);
912 hasEarlyClobbers = true;
917 // The instruction may have virtual register operands that must be allocated
918 // the same register at use-time and def-time: early clobbers and tied
919 // operands. If there are also physical defs, these registers must avoid
920 // both physical defs and uses, making them more constrained than normal
922 // Similarly, if there are multiple defs and tied operands, we must make
923 // sure the same register is allocated to uses and defs.
924 // We didn't detect inline asm tied operands above, so just make this extra
925 // pass for all inline asm.
926 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
927 (hasTiedOps && (hasPhysDefs || TID.getNumDefs() > 1))) {
928 handleThroughOperands(MI, VirtDead);
929 // Don't attempt coalescing when we have funny stuff going on.
931 // Pretend we have early clobbers so the use operands get marked below.
932 // This is not necessary for the common case of a single tied use.
933 hasEarlyClobbers = true;
937 // Allocate virtreg uses.
938 for (unsigned i = 0; i != VirtOpEnd; ++i) {
939 MachineOperand &MO = MI->getOperand(i);
940 if (!MO.isReg()) continue;
941 unsigned Reg = MO.getReg();
942 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
944 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
945 unsigned PhysReg = LRI->second.PhysReg;
946 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
947 if (setPhysReg(MI, i, PhysReg))
952 MRI->addPhysRegsUsed(UsedInInstr);
954 // Track registers defined by instruction - early clobbers and tied uses at
957 if (hasEarlyClobbers) {
958 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
959 MachineOperand &MO = MI->getOperand(i);
960 if (!MO.isReg()) continue;
961 unsigned Reg = MO.getReg();
962 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
963 // Look for physreg defs and tied uses.
964 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
965 UsedInInstr.set(Reg);
966 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
967 UsedInInstr.set(*AS);
971 unsigned DefOpEnd = MI->getNumOperands();
973 // Spill all virtregs before a call. This serves two purposes: 1. If an
974 // exception is thrown, the landing pad is going to expect to find
975 // registers in their spill slots, and 2. we don't have to wade through
976 // all the <imp-def> operands on the call instruction.
977 DefOpEnd = VirtOpEnd;
978 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
981 // The imp-defs are skipped below, but we still need to mark those
982 // registers as used by the function.
983 SkippedInstrs.insert(&TID);
987 // Allocate defs and collect dead defs.
988 for (unsigned i = 0; i != DefOpEnd; ++i) {
989 MachineOperand &MO = MI->getOperand(i);
990 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
992 unsigned Reg = MO.getReg();
994 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
995 if (!Allocatable.test(Reg)) continue;
996 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
997 regFree : regReserved);
1000 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
1001 unsigned PhysReg = LRI->second.PhysReg;
1002 if (setPhysReg(MI, i, PhysReg)) {
1003 VirtDead.push_back(Reg);
1004 CopyDst = 0; // cancel coalescing;
1006 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1009 // Kill dead defs after the scan to ensure that multiple defs of the same
1010 // register are allocated identically. We didn't need to do this for uses
1011 // because we are crerating our own kill flags, and they are always at the
1013 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1014 killVirtReg(VirtDead[i]);
1017 MRI->addPhysRegsUsed(UsedInInstr);
1019 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1020 DEBUG(dbgs() << "-- coalescing: " << *MI);
1021 Coalesced.push_back(MI);
1023 DEBUG(dbgs() << "<< " << *MI);
1027 // Spill all physical registers holding virtual registers now.
1028 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1029 spillAll(MBB->getFirstTerminator());
1031 // Erase all the coalesced copies. We are delaying it until now because
1032 // LiveVirtRegs might refer to the instrs.
1033 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1034 MBB->erase(Coalesced[i]);
1035 NumCopies += Coalesced.size();
1040 /// runOnMachineFunction - Register allocate the whole function
1042 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1043 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1044 << "********** Function: "
1045 << ((Value*)Fn.getFunction())->getName() << '\n');
1047 MRI = &MF->getRegInfo();
1048 TM = &Fn.getTarget();
1049 TRI = TM->getRegisterInfo();
1050 TII = TM->getInstrInfo();
1052 UsedInInstr.resize(TRI->getNumRegs());
1053 Allocatable = TRI->getAllocatableSet(*MF);
1055 // initialize the virtual->physical register map to have a 'null'
1056 // mapping for all virtual registers
1057 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1059 // Loop over all of the basic blocks, eliminating virtual register references
1060 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1061 MBBi != MBBe; ++MBBi) {
1063 AllocateBasicBlock();
1066 // Make sure the set of used physregs is closed under subreg operations.
1067 MRI->closePhysRegsUsed(*TRI);
1069 // Add the clobber lists for all the instructions we skipped earlier.
1070 for (SmallPtrSet<const TargetInstrDesc*, 4>::const_iterator
1071 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1072 if (const unsigned *Defs = (*I)->getImplicitDefs())
1074 MRI->setPhysRegUsed(*Defs++);
1076 SkippedInstrs.clear();
1077 StackSlotForVirtReg.clear();
1078 LiveDbgValueMap.clear();
1082 FunctionPass *llvm::createFastRegisterAllocator() {
1083 return new RAFast();