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/CodeGen/RegisterClassInfo.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/SparseSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
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 isBulkSpilling(false) {}
55 const TargetMachine *TM;
57 MachineRegisterInfo *MRI;
58 const TargetRegisterInfo *TRI;
59 const TargetInstrInfo *TII;
60 RegisterClassInfo RegClassInfo;
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 VirtReg; // Virtual register number.
73 unsigned PhysReg; // Currently held here.
74 unsigned short LastOpNum; // OpNum on LastUse.
75 bool Dirty; // Register needs spill.
77 explicit LiveReg(unsigned v)
78 : LastUse(0), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false) {}
80 unsigned getSparseSetIndex() const {
81 return TargetRegisterInfo::virtReg2Index(VirtReg);
85 typedef SparseSet<LiveReg> LiveRegMap;
87 // LiveVirtRegs - This map contains entries for each virtual register
88 // that is currently available in a physical register.
89 LiveRegMap LiveVirtRegs;
91 DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
93 // RegState - Track the state of a physical register.
95 // A disabled register is not available for allocation, but an alias may
96 // be in use. A register can only be moved out of the disabled state if
97 // all aliases are disabled.
100 // A free register is not currently in use and can be allocated
101 // immediately without checking aliases.
104 // A reserved register has been assigned explicitly (e.g., setting up a
105 // call parameter), and it remains reserved until it is used.
108 // A register state may also be a virtual register number, indication that
109 // the physical register is currently allocated to a virtual register. In
110 // that case, LiveVirtRegs contains the inverse mapping.
113 // PhysRegState - One of the RegState enums, or a virtreg.
114 std::vector<unsigned> PhysRegState;
116 typedef SparseSet<unsigned> UsedInInstrSet;
118 // UsedInInstr - Set of physregs that are used in the current instruction,
119 // and so cannot be allocated.
120 UsedInInstrSet UsedInInstr;
122 // SkippedInstrs - Descriptors of instructions whose clobber list was
123 // ignored because all registers were spilled. It is still necessary to
124 // mark all the clobbered registers as used by the function.
125 SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
127 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
128 // completely after spilling all live registers. LiveRegMap entries should
135 spillImpossible = ~0u
138 virtual const char *getPassName() const {
139 return "Fast Register Allocator";
142 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.setPreservesCFG();
144 MachineFunctionPass::getAnalysisUsage(AU);
148 bool runOnMachineFunction(MachineFunction &Fn);
149 void AllocateBasicBlock();
150 void handleThroughOperands(MachineInstr *MI,
151 SmallVectorImpl<unsigned> &VirtDead);
152 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
153 bool isLastUseOfLocalReg(MachineOperand&);
155 void addKillFlag(const LiveReg&);
156 void killVirtReg(LiveRegMap::iterator);
157 void killVirtReg(unsigned VirtReg);
158 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
159 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
161 void usePhysReg(MachineOperand&);
162 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
163 unsigned calcSpillCost(unsigned PhysReg) const;
164 void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
165 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
166 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
168 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
169 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
171 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
172 LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
174 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
175 unsigned VirtReg, unsigned Hint);
176 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
177 unsigned VirtReg, unsigned Hint);
178 void spillAll(MachineBasicBlock::iterator MI);
179 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
180 void addRetOperands(MachineBasicBlock *MBB);
185 /// getStackSpaceFor - This allocates space for the specified virtual register
186 /// to be held on the stack.
187 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
188 // Find the location Reg would belong...
189 int SS = StackSlotForVirtReg[VirtReg];
191 return SS; // Already has space allocated?
193 // Allocate a new stack object for this spill location...
194 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
198 StackSlotForVirtReg[VirtReg] = FrameIdx;
202 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
203 /// its virtual register, and it is guaranteed to be a block-local register.
205 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
206 // If the register has ever been spilled or reloaded, we conservatively assume
207 // it is a global register used in multiple blocks.
208 if (StackSlotForVirtReg[MO.getReg()] != -1)
211 // Check that the use/def chain has exactly one operand - MO.
212 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
213 if (&I.getOperand() != &MO)
215 return ++I == MRI->reg_nodbg_end();
218 /// addKillFlag - Set kill flags on last use of a virtual register.
219 void RAFast::addKillFlag(const LiveReg &LR) {
220 if (!LR.LastUse) return;
221 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
222 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
223 if (MO.getReg() == LR.PhysReg)
226 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
230 /// killVirtReg - Mark virtreg as no longer available.
231 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
233 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
234 "Broken RegState mapping");
235 PhysRegState[LRI->PhysReg] = regFree;
236 // Erase from LiveVirtRegs unless we're spilling in bulk.
238 LiveVirtRegs.erase(LRI);
241 /// killVirtReg - Mark virtreg as no longer available.
242 void RAFast::killVirtReg(unsigned VirtReg) {
243 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
244 "killVirtReg needs a virtual register");
245 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
246 if (LRI != LiveVirtRegs.end())
250 /// spillVirtReg - This method spills the value specified by VirtReg into the
251 /// corresponding stack slot if needed.
252 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
253 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
254 "Spilling a physical register is illegal!");
255 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
256 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
257 spillVirtReg(MI, LRI);
260 /// spillVirtReg - Do the actual work of spilling.
261 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
262 LiveRegMap::iterator LRI) {
264 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
267 // If this physreg is used by the instruction, we want to kill it on the
268 // instruction, not on the spill.
269 bool SpillKill = LR.LastUse != MI;
271 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
272 << " in " << PrintReg(LR.PhysReg, TRI));
273 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
274 int FI = getStackSpaceFor(LRI->VirtReg, RC);
275 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
276 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
277 ++NumStores; // Update statistics
279 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
280 // identify spilled location as the place to find corresponding variable's
282 SmallVector<MachineInstr *, 4> &LRIDbgValues =
283 LiveDbgValueMap[LRI->VirtReg];
284 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
285 MachineInstr *DBG = LRIDbgValues[li];
286 const MDNode *MDPtr =
287 DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
289 if (DBG->getOperand(1).isImm())
290 Offset = DBG->getOperand(1).getImm();
292 if (MI == MBB->end()) {
293 // If MI is at basic block end then use last instruction's location.
294 MachineBasicBlock::iterator EI = MI;
295 DL = (--EI)->getDebugLoc();
298 DL = MI->getDebugLoc();
299 if (MachineInstr *NewDV =
300 TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
301 MachineBasicBlock *MBB = DBG->getParent();
302 MBB->insert(MI, NewDV);
303 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
306 // Now this register is spilled there is should not be any DBG_VALUE
307 // pointing to this register because they are all pointing to spilled value
309 LRIDbgValues.clear();
311 LR.LastUse = 0; // Don't kill register again
316 /// spillAll - Spill all dirty virtregs without killing them.
317 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
318 if (LiveVirtRegs.empty()) return;
319 isBulkSpilling = true;
320 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
321 // of spilling here is deterministic, if arbitrary.
322 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
325 LiveVirtRegs.clear();
326 isBulkSpilling = false;
329 /// usePhysReg - Handle the direct use of a physical register.
330 /// Check that the register is not used by a virtreg.
331 /// Kill the physreg, marking it free.
332 /// This may add implicit kills to MO->getParent() and invalidate MO.
333 void RAFast::usePhysReg(MachineOperand &MO) {
334 unsigned PhysReg = MO.getReg();
335 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
336 "Bad usePhysReg operand");
338 switch (PhysRegState[PhysReg]) {
342 PhysRegState[PhysReg] = regFree;
345 UsedInInstr.insert(PhysReg);
349 // The physreg was allocated to a virtual register. That means the value we
350 // wanted has been clobbered.
351 llvm_unreachable("Instruction uses an allocated register");
354 // Maybe a superregister is reserved?
355 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
356 unsigned Alias = *AI;
357 switch (PhysRegState[Alias]) {
361 assert(TRI->isSuperRegister(PhysReg, Alias) &&
362 "Instruction is not using a subregister of a reserved register");
363 // Leave the superregister in the working set.
364 PhysRegState[Alias] = regFree;
365 UsedInInstr.insert(Alias);
366 MO.getParent()->addRegisterKilled(Alias, TRI, true);
369 if (TRI->isSuperRegister(PhysReg, Alias)) {
370 // Leave the superregister in the working set.
371 UsedInInstr.insert(Alias);
372 MO.getParent()->addRegisterKilled(Alias, TRI, true);
375 // Some other alias was in the working set - clear it.
376 PhysRegState[Alias] = regDisabled;
379 llvm_unreachable("Instruction uses an alias of an allocated register");
383 // All aliases are disabled, bring register into working set.
384 PhysRegState[PhysReg] = regFree;
385 UsedInInstr.insert(PhysReg);
389 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
390 /// virtregs. This is very similar to defineVirtReg except the physreg is
391 /// reserved instead of allocated.
392 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
394 UsedInInstr.insert(PhysReg);
395 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
399 spillVirtReg(MI, VirtReg);
403 PhysRegState[PhysReg] = NewState;
407 // This is a disabled register, disable all aliases.
408 PhysRegState[PhysReg] = NewState;
409 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
410 unsigned Alias = *AI;
411 switch (unsigned VirtReg = PhysRegState[Alias]) {
415 spillVirtReg(MI, VirtReg);
419 PhysRegState[Alias] = regDisabled;
420 if (TRI->isSuperRegister(PhysReg, Alias))
428 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
429 // aliases so it is free for allocation.
430 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
431 // can be allocated directly.
432 // Returns spillImpossible when PhysReg or an alias can't be spilled.
433 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
434 if (UsedInInstr.count(PhysReg)) {
435 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
436 return spillImpossible;
438 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
444 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
445 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
446 return spillImpossible;
448 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
449 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
450 return I->Dirty ? spillDirty : spillClean;
454 // This is a disabled register, add up cost of aliases.
455 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
457 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
458 unsigned Alias = *AI;
459 if (UsedInInstr.count(Alias))
460 return spillImpossible;
461 switch (unsigned VirtReg = PhysRegState[Alias]) {
468 return spillImpossible;
470 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
471 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
472 Cost += I->Dirty ? spillDirty : spillClean;
481 /// assignVirtToPhysReg - This method updates local state so that we know
482 /// that PhysReg is the proper container for VirtReg now. The physical
483 /// register must not be used for anything else when this is called.
485 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
486 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
487 << PrintReg(PhysReg, TRI) << "\n");
488 PhysRegState[PhysReg] = LR.VirtReg;
489 assert(!LR.PhysReg && "Already assigned a physreg");
490 LR.PhysReg = PhysReg;
493 RAFast::LiveRegMap::iterator
494 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
495 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
496 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
497 assignVirtToPhysReg(*LRI, PhysReg);
501 /// allocVirtReg - Allocate a physical register for VirtReg.
502 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
503 LiveRegMap::iterator LRI,
505 const unsigned VirtReg = LRI->VirtReg;
507 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
508 "Can only allocate virtual registers");
510 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
512 // Ignore invalid hints.
513 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
514 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
517 // Take hint when possible.
519 // Ignore the hint if we would have to spill a dirty register.
520 unsigned Cost = calcSpillCost(Hint);
521 if (Cost < spillDirty) {
523 definePhysReg(MI, Hint, regFree);
524 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
525 // That invalidates LRI, so run a new lookup for VirtReg.
526 return assignVirtToPhysReg(VirtReg, Hint);
530 ArrayRef<unsigned> AO = RegClassInfo.getOrder(RC);
532 // First try to find a completely free register.
533 for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
534 unsigned PhysReg = *I;
535 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.count(PhysReg)) {
536 assignVirtToPhysReg(*LRI, PhysReg);
541 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
542 << RC->getName() << "\n");
544 unsigned BestReg = 0, BestCost = spillImpossible;
545 for (ArrayRef<unsigned>::iterator I = AO.begin(), E = AO.end(); I != E; ++I) {
546 unsigned Cost = calcSpillCost(*I);
547 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
548 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
549 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
550 // Cost is 0 when all aliases are already disabled.
552 assignVirtToPhysReg(*LRI, *I);
556 BestReg = *I, BestCost = Cost;
560 definePhysReg(MI, BestReg, regFree);
561 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
562 // That invalidates LRI, so run a new lookup for VirtReg.
563 return assignVirtToPhysReg(VirtReg, BestReg);
566 // Nothing we can do. Report an error and keep going with a bad allocation.
567 MI->emitError("ran out of registers during register allocation");
568 definePhysReg(MI, *AO.begin(), regFree);
569 return assignVirtToPhysReg(VirtReg, *AO.begin());
572 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
573 RAFast::LiveRegMap::iterator
574 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
575 unsigned VirtReg, unsigned Hint) {
576 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
577 "Not a virtual register");
578 LiveRegMap::iterator LRI;
580 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
582 // If there is no hint, peek at the only use of this register.
583 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
584 MRI->hasOneNonDBGUse(VirtReg)) {
585 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
586 // It's a copy, use the destination register as a hint.
587 if (UseMI.isCopyLike())
588 Hint = UseMI.getOperand(0).getReg();
590 LRI = allocVirtReg(MI, LRI, Hint);
591 } else if (LRI->LastUse) {
592 // Redefining a live register - kill at the last use, unless it is this
593 // instruction defining VirtReg multiple times.
594 if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
597 assert(LRI->PhysReg && "Register not assigned");
599 LRI->LastOpNum = OpNum;
601 UsedInInstr.insert(LRI->PhysReg);
605 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
606 RAFast::LiveRegMap::iterator
607 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
608 unsigned VirtReg, unsigned Hint) {
609 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
610 "Not a virtual register");
611 LiveRegMap::iterator LRI;
613 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
614 MachineOperand &MO = MI->getOperand(OpNum);
616 LRI = allocVirtReg(MI, LRI, Hint);
617 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
618 int FrameIndex = getStackSpaceFor(VirtReg, RC);
619 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
620 << PrintReg(LRI->PhysReg, TRI) << "\n");
621 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
623 } else if (LRI->Dirty) {
624 if (isLastUseOfLocalReg(MO)) {
625 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
630 } else if (MO.isKill()) {
631 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
633 } else if (MO.isDead()) {
634 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
637 } else if (MO.isKill()) {
638 // We must remove kill flags from uses of reloaded registers because the
639 // register would be killed immediately, and there might be a second use:
640 // %foo = OR %x<kill>, %x
641 // This would cause a second reload of %x into a different register.
642 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
644 } else if (MO.isDead()) {
645 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
648 assert(LRI->PhysReg && "Register not assigned");
650 LRI->LastOpNum = OpNum;
651 UsedInInstr.insert(LRI->PhysReg);
655 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
656 // subregs. This may invalidate any operand pointers.
657 // Return true if the operand kills its register.
658 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
659 MachineOperand &MO = MI->getOperand(OpNum);
660 bool Dead = MO.isDead();
661 if (!MO.getSubReg()) {
663 return MO.isKill() || Dead;
666 // Handle subregister index.
667 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
670 // A kill flag implies killing the full register. Add corresponding super
673 MI->addRegisterKilled(PhysReg, TRI, true);
677 // A <def,read-undef> of a sub-register requires an implicit def of the full
679 if (MO.isDef() && MO.isUndef())
680 MI->addRegisterDefined(PhysReg, TRI);
685 // Handle special instruction operand like early clobbers and tied ops when
686 // there are additional physreg defines.
687 void RAFast::handleThroughOperands(MachineInstr *MI,
688 SmallVectorImpl<unsigned> &VirtDead) {
689 DEBUG(dbgs() << "Scanning for through registers:");
690 SmallSet<unsigned, 8> ThroughRegs;
691 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
692 MachineOperand &MO = MI->getOperand(i);
693 if (!MO.isReg()) continue;
694 unsigned Reg = MO.getReg();
695 if (!TargetRegisterInfo::isVirtualRegister(Reg))
697 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
698 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
699 if (ThroughRegs.insert(Reg))
700 DEBUG(dbgs() << ' ' << PrintReg(Reg));
704 // If any physreg defines collide with preallocated through registers,
705 // we must spill and reallocate.
706 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
707 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
708 MachineOperand &MO = MI->getOperand(i);
709 if (!MO.isReg() || !MO.isDef()) continue;
710 unsigned Reg = MO.getReg();
711 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
712 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
713 UsedInInstr.insert(*AI);
714 if (ThroughRegs.count(PhysRegState[*AI]))
715 definePhysReg(MI, *AI, regFree);
719 SmallVector<unsigned, 8> PartialDefs;
720 DEBUG(dbgs() << "Allocating tied uses.\n");
721 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
722 MachineOperand &MO = MI->getOperand(i);
723 if (!MO.isReg()) continue;
724 unsigned Reg = MO.getReg();
725 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
728 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
729 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
731 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
732 unsigned PhysReg = LRI->PhysReg;
733 setPhysReg(MI, i, PhysReg);
734 // Note: we don't update the def operand yet. That would cause the normal
735 // def-scan to attempt spilling.
736 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
737 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
738 // Reload the register, but don't assign to the operand just yet.
739 // That would confuse the later phys-def processing pass.
740 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
741 PartialDefs.push_back(LRI->PhysReg);
745 DEBUG(dbgs() << "Allocating early clobbers.\n");
746 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
747 MachineOperand &MO = MI->getOperand(i);
748 if (!MO.isReg()) continue;
749 unsigned Reg = MO.getReg();
750 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
751 if (!MO.isEarlyClobber())
753 // Note: defineVirtReg may invalidate MO.
754 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
755 unsigned PhysReg = LRI->PhysReg;
756 if (setPhysReg(MI, i, PhysReg))
757 VirtDead.push_back(Reg);
760 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
762 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
763 MachineOperand &MO = MI->getOperand(i);
764 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
765 unsigned Reg = MO.getReg();
766 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
767 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
768 << " as used in instr\n");
769 UsedInInstr.insert(Reg);
772 // Also mark PartialDefs as used to avoid reallocation.
773 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
774 UsedInInstr.insert(PartialDefs[i]);
777 /// addRetOperand - ensure that a return instruction has an operand for each
778 /// value live out of the function.
780 /// Things marked both call and return are tail calls; do not do this for them.
781 /// The tail callee need not take the same registers as input that it produces
782 /// as output, and there are dependencies for its input registers elsewhere.
784 /// FIXME: This should be done as part of instruction selection, and this helper
785 /// should be deleted. Until then, we use custom logic here to create the proper
786 /// operand under all circumstances. We can't use addRegisterKilled because that
787 /// doesn't make sense for undefined values. We can't simply avoid calling it
788 /// for undefined values, because we must ensure that the operand always exists.
789 void RAFast::addRetOperands(MachineBasicBlock *MBB) {
790 if (MBB->empty() || !MBB->back().isReturn() || MBB->back().isCall())
793 MachineInstr *MI = &MBB->back();
795 for (MachineRegisterInfo::liveout_iterator
796 I = MBB->getParent()->getRegInfo().liveout_begin(),
797 E = MBB->getParent()->getRegInfo().liveout_end(); I != E; ++I) {
799 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
800 "Cannot have a live-out virtual register.");
802 bool hasDef = PhysRegState[Reg] == regReserved;
804 // Check if this register already has an operand.
806 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
807 MachineOperand &MO = MI->getOperand(i);
808 if (!MO.isReg() || !MO.isUse())
811 unsigned OperReg = MO.getReg();
812 if (!TargetRegisterInfo::isPhysicalRegister(OperReg))
815 if (OperReg == Reg || TRI->isSuperRegister(OperReg, Reg)) {
816 // If the ret already has an operand for this physreg or a superset,
817 // don't duplicate it. Set the kill flag if the value is defined.
818 if (hasDef && !MO.isKill())
825 MI->addOperand(MachineOperand::CreateReg(Reg,
832 void RAFast::AllocateBasicBlock() {
833 DEBUG(dbgs() << "\nAllocating " << *MBB);
835 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
836 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
838 MachineBasicBlock::iterator MII = MBB->begin();
840 // Add live-in registers as live.
841 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
842 E = MBB->livein_end(); I != E; ++I)
843 if (MRI->isAllocatable(*I))
844 definePhysReg(MII, *I, regReserved);
846 SmallVector<unsigned, 8> VirtDead;
847 SmallVector<MachineInstr*, 32> Coalesced;
849 // Otherwise, sequentially allocate each instruction in the MBB.
850 while (MII != MBB->end()) {
851 MachineInstr *MI = MII++;
852 const MCInstrDesc &MCID = MI->getDesc();
854 dbgs() << "\n>> " << *MI << "Regs:";
855 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
856 if (PhysRegState[Reg] == regDisabled) continue;
857 dbgs() << " " << TRI->getName(Reg);
858 switch(PhysRegState[Reg]) {
865 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
866 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
867 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
870 assert(I->PhysReg == Reg && "Bad inverse map");
876 // Check that LiveVirtRegs is the inverse.
877 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
878 e = LiveVirtRegs.end(); i != e; ++i) {
879 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
881 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
883 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
887 // Debug values are not allowed to change codegen in any way.
888 if (MI->isDebugValue()) {
889 bool ScanDbgValue = true;
890 while (ScanDbgValue) {
891 ScanDbgValue = false;
892 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
893 MachineOperand &MO = MI->getOperand(i);
894 if (!MO.isReg()) continue;
895 unsigned Reg = MO.getReg();
896 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
897 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
898 if (LRI != LiveVirtRegs.end())
899 setPhysReg(MI, i, LRI->PhysReg);
901 int SS = StackSlotForVirtReg[Reg];
903 // We can't allocate a physreg for a DebugValue, sorry!
904 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
908 // Modify DBG_VALUE now that the value is in a spill slot.
909 int64_t Offset = MI->getOperand(1).getImm();
910 const MDNode *MDPtr =
911 MI->getOperand(MI->getNumOperands()-1).getMetadata();
912 DebugLoc DL = MI->getDebugLoc();
913 if (MachineInstr *NewDV =
914 TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
915 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
917 MachineBasicBlock *MBB = MI->getParent();
918 MBB->insert(MBB->erase(MI), NewDV);
919 // Scan NewDV operands from the beginning.
924 // We can't allocate a physreg for a DebugValue; sorry!
925 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
930 LiveDbgValueMap[Reg].push_back(MI);
937 // If this is a copy, we may be able to coalesce.
938 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
940 CopyDst = MI->getOperand(0).getReg();
941 CopySrc = MI->getOperand(1).getReg();
942 CopyDstSub = MI->getOperand(0).getSubReg();
943 CopySrcSub = MI->getOperand(1).getSubReg();
946 // Track registers used by instruction.
950 // Mark physreg uses and early clobbers as used.
951 // Find the end of the virtreg operands
952 unsigned VirtOpEnd = 0;
953 bool hasTiedOps = false;
954 bool hasEarlyClobbers = false;
955 bool hasPartialRedefs = false;
956 bool hasPhysDefs = false;
957 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
958 MachineOperand &MO = MI->getOperand(i);
959 // Make sure MRI knows about registers clobbered by regmasks.
960 if (MO.isRegMask()) {
961 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
964 if (!MO.isReg()) continue;
965 unsigned Reg = MO.getReg();
967 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
970 hasTiedOps = hasTiedOps ||
971 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
973 if (MO.isEarlyClobber())
974 hasEarlyClobbers = true;
975 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
976 hasPartialRedefs = true;
980 if (!MRI->isAllocatable(Reg)) continue;
983 } else if (MO.isEarlyClobber()) {
984 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
985 regFree : regReserved);
986 hasEarlyClobbers = true;
991 // The instruction may have virtual register operands that must be allocated
992 // the same register at use-time and def-time: early clobbers and tied
993 // operands. If there are also physical defs, these registers must avoid
994 // both physical defs and uses, making them more constrained than normal
996 // Similarly, if there are multiple defs and tied operands, we must make
997 // sure the same register is allocated to uses and defs.
998 // We didn't detect inline asm tied operands above, so just make this extra
999 // pass for all inline asm.
1000 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
1001 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
1002 handleThroughOperands(MI, VirtDead);
1003 // Don't attempt coalescing when we have funny stuff going on.
1005 // Pretend we have early clobbers so the use operands get marked below.
1006 // This is not necessary for the common case of a single tied use.
1007 hasEarlyClobbers = true;
1011 // Allocate virtreg uses.
1012 for (unsigned i = 0; i != VirtOpEnd; ++i) {
1013 MachineOperand &MO = MI->getOperand(i);
1014 if (!MO.isReg()) continue;
1015 unsigned Reg = MO.getReg();
1016 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
1018 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
1019 unsigned PhysReg = LRI->PhysReg;
1020 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
1021 if (setPhysReg(MI, i, PhysReg))
1026 for (UsedInInstrSet::iterator
1027 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
1028 MRI->setPhysRegUsed(*I);
1030 // Track registers defined by instruction - early clobbers and tied uses at
1032 UsedInInstr.clear();
1033 if (hasEarlyClobbers) {
1034 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035 MachineOperand &MO = MI->getOperand(i);
1036 if (!MO.isReg()) continue;
1037 unsigned Reg = MO.getReg();
1038 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1039 // Look for physreg defs and tied uses.
1040 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
1041 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
1042 UsedInInstr.insert(*AI);
1046 unsigned DefOpEnd = MI->getNumOperands();
1048 // Spill all virtregs before a call. This serves two purposes: 1. If an
1049 // exception is thrown, the landing pad is going to expect to find
1050 // registers in their spill slots, and 2. we don't have to wade through
1051 // all the <imp-def> operands on the call instruction.
1052 DefOpEnd = VirtOpEnd;
1053 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1056 // The imp-defs are skipped below, but we still need to mark those
1057 // registers as used by the function.
1058 SkippedInstrs.insert(&MCID);
1062 // Allocate defs and collect dead defs.
1063 for (unsigned i = 0; i != DefOpEnd; ++i) {
1064 MachineOperand &MO = MI->getOperand(i);
1065 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1067 unsigned Reg = MO.getReg();
1069 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1070 if (!MRI->isAllocatable(Reg)) continue;
1071 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
1072 regFree : regReserved);
1075 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
1076 unsigned PhysReg = LRI->PhysReg;
1077 if (setPhysReg(MI, i, PhysReg)) {
1078 VirtDead.push_back(Reg);
1079 CopyDst = 0; // cancel coalescing;
1081 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1084 // Kill dead defs after the scan to ensure that multiple defs of the same
1085 // register are allocated identically. We didn't need to do this for uses
1086 // because we are crerating our own kill flags, and they are always at the
1088 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1089 killVirtReg(VirtDead[i]);
1092 for (UsedInInstrSet::iterator
1093 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
1094 MRI->setPhysRegUsed(*I);
1096 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1097 DEBUG(dbgs() << "-- coalescing: " << *MI);
1098 Coalesced.push_back(MI);
1100 DEBUG(dbgs() << "<< " << *MI);
1104 // Spill all physical registers holding virtual registers now.
1105 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1106 spillAll(MBB->getFirstTerminator());
1108 // Erase all the coalesced copies. We are delaying it until now because
1109 // LiveVirtRegs might refer to the instrs.
1110 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1111 MBB->erase(Coalesced[i]);
1112 NumCopies += Coalesced.size();
1114 // addRetOperands must run after we've seen all defs in this block.
1115 addRetOperands(MBB);
1120 /// runOnMachineFunction - Register allocate the whole function
1122 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1123 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1124 << "********** Function: " << Fn.getName() << '\n');
1126 MRI = &MF->getRegInfo();
1127 TM = &Fn.getTarget();
1128 TRI = TM->getRegisterInfo();
1129 TII = TM->getInstrInfo();
1130 MRI->freezeReservedRegs(Fn);
1131 RegClassInfo.runOnMachineFunction(Fn);
1132 UsedInInstr.clear();
1133 UsedInInstr.setUniverse(TRI->getNumRegs());
1135 assert(!MRI->isSSA() && "regalloc requires leaving SSA");
1137 // initialize the virtual->physical register map to have a 'null'
1138 // mapping for all virtual registers
1139 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1140 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1142 // Loop over all of the basic blocks, eliminating virtual register references
1143 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1144 MBBi != MBBe; ++MBBi) {
1146 AllocateBasicBlock();
1149 // Add the clobber lists for all the instructions we skipped earlier.
1150 for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
1151 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1152 if (const uint16_t *Defs = (*I)->getImplicitDefs())
1154 MRI->setPhysRegUsed(*Defs++);
1156 // All machine operands and other references to virtual registers have been
1157 // replaced. Remove the virtual registers.
1158 MRI->clearVirtRegs();
1160 SkippedInstrs.clear();
1161 StackSlotForVirtReg.clear();
1162 LiveDbgValueMap.clear();
1166 FunctionPass *llvm::createFastRegisterAllocator() {
1167 return new RAFast();