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/CodeGen/Passes.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/SparseSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/CodeGen/RegisterClassInfo.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.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);
184 /// getStackSpaceFor - This allocates space for the specified virtual register
185 /// to be held on the stack.
186 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
187 // Find the location Reg would belong...
188 int SS = StackSlotForVirtReg[VirtReg];
190 return SS; // Already has space allocated?
192 // Allocate a new stack object for this spill location...
193 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
197 StackSlotForVirtReg[VirtReg] = FrameIdx;
201 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
202 /// its virtual register, and it is guaranteed to be a block-local register.
204 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
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 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
212 if (&I.getOperand() != &MO)
214 return ++I == MRI->reg_nodbg_end();
217 /// addKillFlag - Set kill flags on last use of a virtual register.
218 void RAFast::addKillFlag(const LiveReg &LR) {
219 if (!LR.LastUse) return;
220 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
221 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
222 if (MO.getReg() == LR.PhysReg)
225 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
229 /// killVirtReg - Mark virtreg as no longer available.
230 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
232 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
233 "Broken RegState mapping");
234 PhysRegState[LRI->PhysReg] = regFree;
235 // Erase from LiveVirtRegs unless we're spilling in bulk.
237 LiveVirtRegs.erase(LRI);
240 /// killVirtReg - Mark virtreg as no longer available.
241 void RAFast::killVirtReg(unsigned VirtReg) {
242 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
243 "killVirtReg needs a virtual register");
244 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
245 if (LRI != LiveVirtRegs.end())
249 /// spillVirtReg - This method spills the value specified by VirtReg into the
250 /// corresponding stack slot if needed.
251 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
252 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
253 "Spilling a physical register is illegal!");
254 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
255 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
256 spillVirtReg(MI, LRI);
259 /// spillVirtReg - Do the actual work of spilling.
260 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
261 LiveRegMap::iterator LRI) {
263 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
266 // If this physreg is used by the instruction, we want to kill it on the
267 // instruction, not on the spill.
268 bool SpillKill = LR.LastUse != MI;
270 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
271 << " in " << PrintReg(LR.PhysReg, TRI));
272 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
273 int FI = getStackSpaceFor(LRI->VirtReg, RC);
274 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
275 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
276 ++NumStores; // Update statistics
278 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
279 // identify spilled location as the place to find corresponding variable's
281 SmallVector<MachineInstr *, 4> &LRIDbgValues =
282 LiveDbgValueMap[LRI->VirtReg];
283 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
284 MachineInstr *DBG = LRIDbgValues[li];
285 const MDNode *MDPtr =
286 DBG->getOperand(DBG->getNumOperands()-1).getMetadata();
288 if (DBG->getOperand(1).isImm())
289 Offset = DBG->getOperand(1).getImm();
291 if (MI == MBB->end()) {
292 // If MI is at basic block end then use last instruction's location.
293 MachineBasicBlock::iterator EI = MI;
294 DL = (--EI)->getDebugLoc();
297 DL = MI->getDebugLoc();
298 if (MachineInstr *NewDV =
299 TII->emitFrameIndexDebugValue(*MF, FI, Offset, MDPtr, DL)) {
300 MachineBasicBlock *MBB = DBG->getParent();
301 MBB->insert(MI, NewDV);
302 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
305 // Now this register is spilled there is should not be any DBG_VALUE
306 // pointing to this register because they are all pointing to spilled value
308 LRIDbgValues.clear();
310 LR.LastUse = 0; // Don't kill register again
315 /// spillAll - Spill all dirty virtregs without killing them.
316 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
317 if (LiveVirtRegs.empty()) return;
318 isBulkSpilling = true;
319 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
320 // of spilling here is deterministic, if arbitrary.
321 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
324 LiveVirtRegs.clear();
325 isBulkSpilling = false;
328 /// usePhysReg - Handle the direct use of a physical register.
329 /// Check that the register is not used by a virtreg.
330 /// Kill the physreg, marking it free.
331 /// This may add implicit kills to MO->getParent() and invalidate MO.
332 void RAFast::usePhysReg(MachineOperand &MO) {
333 unsigned PhysReg = MO.getReg();
334 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
335 "Bad usePhysReg operand");
337 switch (PhysRegState[PhysReg]) {
341 PhysRegState[PhysReg] = regFree;
344 UsedInInstr.insert(PhysReg);
348 // The physreg was allocated to a virtual register. That means the value we
349 // wanted has been clobbered.
350 llvm_unreachable("Instruction uses an allocated register");
353 // Maybe a superregister is reserved?
354 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
355 unsigned Alias = *AI;
356 switch (PhysRegState[Alias]) {
360 assert(TRI->isSuperRegister(PhysReg, Alias) &&
361 "Instruction is not using a subregister of a reserved register");
362 // Leave the superregister in the working set.
363 PhysRegState[Alias] = regFree;
364 UsedInInstr.insert(Alias);
365 MO.getParent()->addRegisterKilled(Alias, TRI, true);
368 if (TRI->isSuperRegister(PhysReg, Alias)) {
369 // Leave the superregister in the working set.
370 UsedInInstr.insert(Alias);
371 MO.getParent()->addRegisterKilled(Alias, TRI, true);
374 // Some other alias was in the working set - clear it.
375 PhysRegState[Alias] = regDisabled;
378 llvm_unreachable("Instruction uses an alias of an allocated register");
382 // All aliases are disabled, bring register into working set.
383 PhysRegState[PhysReg] = regFree;
384 UsedInInstr.insert(PhysReg);
388 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
389 /// virtregs. This is very similar to defineVirtReg except the physreg is
390 /// reserved instead of allocated.
391 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
393 UsedInInstr.insert(PhysReg);
394 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
398 spillVirtReg(MI, VirtReg);
402 PhysRegState[PhysReg] = NewState;
406 // This is a disabled register, disable all aliases.
407 PhysRegState[PhysReg] = NewState;
408 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
409 unsigned Alias = *AI;
410 switch (unsigned VirtReg = PhysRegState[Alias]) {
414 spillVirtReg(MI, VirtReg);
418 PhysRegState[Alias] = regDisabled;
419 if (TRI->isSuperRegister(PhysReg, Alias))
427 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
428 // aliases so it is free for allocation.
429 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
430 // can be allocated directly.
431 // Returns spillImpossible when PhysReg or an alias can't be spilled.
432 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
433 if (UsedInInstr.count(PhysReg)) {
434 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
435 return spillImpossible;
437 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
443 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
444 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
445 return spillImpossible;
447 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
448 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
449 return I->Dirty ? spillDirty : spillClean;
453 // This is a disabled register, add up cost of aliases.
454 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
456 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
457 unsigned Alias = *AI;
458 if (UsedInInstr.count(Alias))
459 return spillImpossible;
460 switch (unsigned VirtReg = PhysRegState[Alias]) {
467 return spillImpossible;
469 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
470 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
471 Cost += I->Dirty ? spillDirty : spillClean;
480 /// assignVirtToPhysReg - This method updates local state so that we know
481 /// that PhysReg is the proper container for VirtReg now. The physical
482 /// register must not be used for anything else when this is called.
484 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
485 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
486 << PrintReg(PhysReg, TRI) << "\n");
487 PhysRegState[PhysReg] = LR.VirtReg;
488 assert(!LR.PhysReg && "Already assigned a physreg");
489 LR.PhysReg = PhysReg;
492 RAFast::LiveRegMap::iterator
493 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
494 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
495 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
496 assignVirtToPhysReg(*LRI, PhysReg);
500 /// allocVirtReg - Allocate a physical register for VirtReg.
501 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
502 LiveRegMap::iterator LRI,
504 const unsigned VirtReg = LRI->VirtReg;
506 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
507 "Can only allocate virtual registers");
509 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
511 // Ignore invalid hints.
512 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
513 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
516 // Take hint when possible.
518 // Ignore the hint if we would have to spill a dirty register.
519 unsigned Cost = calcSpillCost(Hint);
520 if (Cost < spillDirty) {
522 definePhysReg(MI, Hint, regFree);
523 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
524 // That invalidates LRI, so run a new lookup for VirtReg.
525 return assignVirtToPhysReg(VirtReg, Hint);
529 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
531 // First try to find a completely free register.
532 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
533 unsigned PhysReg = *I;
534 if (PhysRegState[PhysReg] == regFree && !UsedInInstr.count(PhysReg)) {
535 assignVirtToPhysReg(*LRI, PhysReg);
540 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
541 << RC->getName() << "\n");
543 unsigned BestReg = 0, BestCost = spillImpossible;
544 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
545 unsigned Cost = calcSpillCost(*I);
546 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
547 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
548 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
549 // Cost is 0 when all aliases are already disabled.
551 assignVirtToPhysReg(*LRI, *I);
555 BestReg = *I, BestCost = Cost;
559 definePhysReg(MI, BestReg, regFree);
560 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
561 // That invalidates LRI, so run a new lookup for VirtReg.
562 return assignVirtToPhysReg(VirtReg, BestReg);
565 // Nothing we can do. Report an error and keep going with a bad allocation.
566 MI->emitError("ran out of registers during register allocation");
567 definePhysReg(MI, *AO.begin(), regFree);
568 return assignVirtToPhysReg(VirtReg, *AO.begin());
571 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
572 RAFast::LiveRegMap::iterator
573 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
574 unsigned VirtReg, unsigned Hint) {
575 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
576 "Not a virtual register");
577 LiveRegMap::iterator LRI;
579 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
581 // If there is no hint, peek at the only use of this register.
582 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
583 MRI->hasOneNonDBGUse(VirtReg)) {
584 const MachineInstr &UseMI = *MRI->use_nodbg_begin(VirtReg);
585 // It's a copy, use the destination register as a hint.
586 if (UseMI.isCopyLike())
587 Hint = UseMI.getOperand(0).getReg();
589 LRI = allocVirtReg(MI, LRI, Hint);
590 } else if (LRI->LastUse) {
591 // Redefining a live register - kill at the last use, unless it is this
592 // instruction defining VirtReg multiple times.
593 if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
596 assert(LRI->PhysReg && "Register not assigned");
598 LRI->LastOpNum = OpNum;
600 UsedInInstr.insert(LRI->PhysReg);
604 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
605 RAFast::LiveRegMap::iterator
606 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
607 unsigned VirtReg, unsigned Hint) {
608 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
609 "Not a virtual register");
610 LiveRegMap::iterator LRI;
612 tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
613 MachineOperand &MO = MI->getOperand(OpNum);
615 LRI = allocVirtReg(MI, LRI, Hint);
616 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
617 int FrameIndex = getStackSpaceFor(VirtReg, RC);
618 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
619 << PrintReg(LRI->PhysReg, TRI) << "\n");
620 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
622 } else if (LRI->Dirty) {
623 if (isLastUseOfLocalReg(MO)) {
624 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
629 } else if (MO.isKill()) {
630 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
632 } else if (MO.isDead()) {
633 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
636 } else if (MO.isKill()) {
637 // We must remove kill flags from uses of reloaded registers because the
638 // register would be killed immediately, and there might be a second use:
639 // %foo = OR %x<kill>, %x
640 // This would cause a second reload of %x into a different register.
641 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
643 } else if (MO.isDead()) {
644 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
647 assert(LRI->PhysReg && "Register not assigned");
649 LRI->LastOpNum = OpNum;
650 UsedInInstr.insert(LRI->PhysReg);
654 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
655 // subregs. This may invalidate any operand pointers.
656 // Return true if the operand kills its register.
657 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
658 MachineOperand &MO = MI->getOperand(OpNum);
659 bool Dead = MO.isDead();
660 if (!MO.getSubReg()) {
662 return MO.isKill() || Dead;
665 // Handle subregister index.
666 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
669 // A kill flag implies killing the full register. Add corresponding super
672 MI->addRegisterKilled(PhysReg, TRI, true);
676 // A <def,read-undef> of a sub-register requires an implicit def of the full
678 if (MO.isDef() && MO.isUndef())
679 MI->addRegisterDefined(PhysReg, TRI);
684 // Handle special instruction operand like early clobbers and tied ops when
685 // there are additional physreg defines.
686 void RAFast::handleThroughOperands(MachineInstr *MI,
687 SmallVectorImpl<unsigned> &VirtDead) {
688 DEBUG(dbgs() << "Scanning for through registers:");
689 SmallSet<unsigned, 8> ThroughRegs;
690 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
691 MachineOperand &MO = MI->getOperand(i);
692 if (!MO.isReg()) continue;
693 unsigned Reg = MO.getReg();
694 if (!TargetRegisterInfo::isVirtualRegister(Reg))
696 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
697 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
698 if (ThroughRegs.insert(Reg))
699 DEBUG(dbgs() << ' ' << PrintReg(Reg));
703 // If any physreg defines collide with preallocated through registers,
704 // we must spill and reallocate.
705 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
706 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
707 MachineOperand &MO = MI->getOperand(i);
708 if (!MO.isReg() || !MO.isDef()) continue;
709 unsigned Reg = MO.getReg();
710 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
711 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
712 UsedInInstr.insert(*AI);
713 if (ThroughRegs.count(PhysRegState[*AI]))
714 definePhysReg(MI, *AI, regFree);
718 SmallVector<unsigned, 8> PartialDefs;
719 DEBUG(dbgs() << "Allocating tied uses.\n");
720 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
721 MachineOperand &MO = MI->getOperand(i);
722 if (!MO.isReg()) continue;
723 unsigned Reg = MO.getReg();
724 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
727 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
728 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
730 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
731 unsigned PhysReg = LRI->PhysReg;
732 setPhysReg(MI, i, PhysReg);
733 // Note: we don't update the def operand yet. That would cause the normal
734 // def-scan to attempt spilling.
735 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
736 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
737 // Reload the register, but don't assign to the operand just yet.
738 // That would confuse the later phys-def processing pass.
739 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
740 PartialDefs.push_back(LRI->PhysReg);
744 DEBUG(dbgs() << "Allocating early clobbers.\n");
745 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
746 MachineOperand &MO = MI->getOperand(i);
747 if (!MO.isReg()) continue;
748 unsigned Reg = MO.getReg();
749 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
750 if (!MO.isEarlyClobber())
752 // Note: defineVirtReg may invalidate MO.
753 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
754 unsigned PhysReg = LRI->PhysReg;
755 if (setPhysReg(MI, i, PhysReg))
756 VirtDead.push_back(Reg);
759 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
761 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
762 MachineOperand &MO = MI->getOperand(i);
763 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
764 unsigned Reg = MO.getReg();
765 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
766 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
767 << " as used in instr\n");
768 UsedInInstr.insert(Reg);
771 // Also mark PartialDefs as used to avoid reallocation.
772 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
773 UsedInInstr.insert(PartialDefs[i]);
776 void RAFast::AllocateBasicBlock() {
777 DEBUG(dbgs() << "\nAllocating " << *MBB);
779 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
780 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
782 MachineBasicBlock::iterator MII = MBB->begin();
784 // Add live-in registers as live.
785 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
786 E = MBB->livein_end(); I != E; ++I)
787 if (MRI->isAllocatable(*I))
788 definePhysReg(MII, *I, regReserved);
790 SmallVector<unsigned, 8> VirtDead;
791 SmallVector<MachineInstr*, 32> Coalesced;
793 // Otherwise, sequentially allocate each instruction in the MBB.
794 while (MII != MBB->end()) {
795 MachineInstr *MI = MII++;
796 const MCInstrDesc &MCID = MI->getDesc();
798 dbgs() << "\n>> " << *MI << "Regs:";
799 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
800 if (PhysRegState[Reg] == regDisabled) continue;
801 dbgs() << " " << TRI->getName(Reg);
802 switch(PhysRegState[Reg]) {
809 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
810 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
811 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
814 assert(I->PhysReg == Reg && "Bad inverse map");
820 // Check that LiveVirtRegs is the inverse.
821 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
822 e = LiveVirtRegs.end(); i != e; ++i) {
823 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
825 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
827 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
831 // Debug values are not allowed to change codegen in any way.
832 if (MI->isDebugValue()) {
833 bool ScanDbgValue = true;
834 while (ScanDbgValue) {
835 ScanDbgValue = false;
836 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
837 MachineOperand &MO = MI->getOperand(i);
838 if (!MO.isReg()) continue;
839 unsigned Reg = MO.getReg();
840 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
841 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
842 if (LRI != LiveVirtRegs.end())
843 setPhysReg(MI, i, LRI->PhysReg);
845 int SS = StackSlotForVirtReg[Reg];
847 // We can't allocate a physreg for a DebugValue, sorry!
848 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
852 // Modify DBG_VALUE now that the value is in a spill slot.
853 int64_t Offset = MI->getOperand(1).getImm();
854 const MDNode *MDPtr =
855 MI->getOperand(MI->getNumOperands()-1).getMetadata();
856 DebugLoc DL = MI->getDebugLoc();
857 if (MachineInstr *NewDV =
858 TII->emitFrameIndexDebugValue(*MF, SS, Offset, MDPtr, DL)) {
859 DEBUG(dbgs() << "Modifying debug info due to spill:" <<
861 MachineBasicBlock *MBB = MI->getParent();
862 MBB->insert(MBB->erase(MI), NewDV);
863 // Scan NewDV operands from the beginning.
868 // We can't allocate a physreg for a DebugValue; sorry!
869 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
874 LiveDbgValueMap[Reg].push_back(MI);
881 // If this is a copy, we may be able to coalesce.
882 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
884 CopyDst = MI->getOperand(0).getReg();
885 CopySrc = MI->getOperand(1).getReg();
886 CopyDstSub = MI->getOperand(0).getSubReg();
887 CopySrcSub = MI->getOperand(1).getSubReg();
890 // Track registers used by instruction.
894 // Mark physreg uses and early clobbers as used.
895 // Find the end of the virtreg operands
896 unsigned VirtOpEnd = 0;
897 bool hasTiedOps = false;
898 bool hasEarlyClobbers = false;
899 bool hasPartialRedefs = false;
900 bool hasPhysDefs = false;
901 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
902 MachineOperand &MO = MI->getOperand(i);
903 // Make sure MRI knows about registers clobbered by regmasks.
904 if (MO.isRegMask()) {
905 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
908 if (!MO.isReg()) continue;
909 unsigned Reg = MO.getReg();
911 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
914 hasTiedOps = hasTiedOps ||
915 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
917 if (MO.isEarlyClobber())
918 hasEarlyClobbers = true;
919 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
920 hasPartialRedefs = true;
924 if (!MRI->isAllocatable(Reg)) continue;
927 } else if (MO.isEarlyClobber()) {
928 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
929 regFree : regReserved);
930 hasEarlyClobbers = true;
935 // The instruction may have virtual register operands that must be allocated
936 // the same register at use-time and def-time: early clobbers and tied
937 // operands. If there are also physical defs, these registers must avoid
938 // both physical defs and uses, making them more constrained than normal
940 // Similarly, if there are multiple defs and tied operands, we must make
941 // sure the same register is allocated to uses and defs.
942 // We didn't detect inline asm tied operands above, so just make this extra
943 // pass for all inline asm.
944 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
945 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
946 handleThroughOperands(MI, VirtDead);
947 // Don't attempt coalescing when we have funny stuff going on.
949 // Pretend we have early clobbers so the use operands get marked below.
950 // This is not necessary for the common case of a single tied use.
951 hasEarlyClobbers = true;
955 // Allocate virtreg uses.
956 for (unsigned i = 0; i != VirtOpEnd; ++i) {
957 MachineOperand &MO = MI->getOperand(i);
958 if (!MO.isReg()) continue;
959 unsigned Reg = MO.getReg();
960 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
962 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
963 unsigned PhysReg = LRI->PhysReg;
964 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
965 if (setPhysReg(MI, i, PhysReg))
970 for (UsedInInstrSet::iterator
971 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
972 MRI->setPhysRegUsed(*I);
974 // Track registers defined by instruction - early clobbers and tied uses at
977 if (hasEarlyClobbers) {
978 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
979 MachineOperand &MO = MI->getOperand(i);
980 if (!MO.isReg()) continue;
981 unsigned Reg = MO.getReg();
982 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
983 // Look for physreg defs and tied uses.
984 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
985 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
986 UsedInInstr.insert(*AI);
990 unsigned DefOpEnd = MI->getNumOperands();
992 // Spill all virtregs before a call. This serves two purposes: 1. If an
993 // exception is thrown, the landing pad is going to expect to find
994 // registers in their spill slots, and 2. we don't have to wade through
995 // all the <imp-def> operands on the call instruction.
996 DefOpEnd = VirtOpEnd;
997 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1000 // The imp-defs are skipped below, but we still need to mark those
1001 // registers as used by the function.
1002 SkippedInstrs.insert(&MCID);
1006 // Allocate defs and collect dead defs.
1007 for (unsigned i = 0; i != DefOpEnd; ++i) {
1008 MachineOperand &MO = MI->getOperand(i);
1009 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1011 unsigned Reg = MO.getReg();
1013 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1014 if (!MRI->isAllocatable(Reg)) continue;
1015 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
1016 regFree : regReserved);
1019 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
1020 unsigned PhysReg = LRI->PhysReg;
1021 if (setPhysReg(MI, i, PhysReg)) {
1022 VirtDead.push_back(Reg);
1023 CopyDst = 0; // cancel coalescing;
1025 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1028 // Kill dead defs after the scan to ensure that multiple defs of the same
1029 // register are allocated identically. We didn't need to do this for uses
1030 // because we are crerating our own kill flags, and they are always at the
1032 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1033 killVirtReg(VirtDead[i]);
1036 for (UsedInInstrSet::iterator
1037 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
1038 MRI->setPhysRegUsed(*I);
1040 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1041 DEBUG(dbgs() << "-- coalescing: " << *MI);
1042 Coalesced.push_back(MI);
1044 DEBUG(dbgs() << "<< " << *MI);
1048 // Spill all physical registers holding virtual registers now.
1049 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1050 spillAll(MBB->getFirstTerminator());
1052 // Erase all the coalesced copies. We are delaying it until now because
1053 // LiveVirtRegs might refer to the instrs.
1054 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1055 MBB->erase(Coalesced[i]);
1056 NumCopies += Coalesced.size();
1061 /// runOnMachineFunction - Register allocate the whole function
1063 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1064 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1065 << "********** Function: " << Fn.getName() << '\n');
1067 MRI = &MF->getRegInfo();
1068 TM = &Fn.getTarget();
1069 TRI = TM->getRegisterInfo();
1070 TII = TM->getInstrInfo();
1071 MRI->freezeReservedRegs(Fn);
1072 RegClassInfo.runOnMachineFunction(Fn);
1073 UsedInInstr.clear();
1074 UsedInInstr.setUniverse(TRI->getNumRegs());
1076 assert(!MRI->isSSA() && "regalloc requires leaving SSA");
1078 // initialize the virtual->physical register map to have a 'null'
1079 // mapping for all virtual registers
1080 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1081 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1083 // Loop over all of the basic blocks, eliminating virtual register references
1084 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1085 MBBi != MBBe; ++MBBi) {
1087 AllocateBasicBlock();
1090 // Add the clobber lists for all the instructions we skipped earlier.
1091 for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
1092 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1093 if (const uint16_t *Defs = (*I)->getImplicitDefs())
1095 MRI->setPhysRegUsed(*Defs++);
1097 // All machine operands and other references to virtual registers have been
1098 // replaced. Remove the virtual registers.
1099 MRI->clearVirtRegs();
1101 SkippedInstrs.clear();
1102 StackSlotForVirtReg.clear();
1103 LiveDbgValueMap.clear();
1107 FunctionPass *llvm::createFastRegisterAllocator() {
1108 return new RAFast();