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 /// \file This register allocator allocates registers to a basic block at a
11 /// time, attempting to keep values in registers and reusing registers as
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/IndexedMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/SparseSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineBasicBlock.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegAllocRegistry.h"
32 #include "llvm/CodeGen/RegisterClassInfo.h"
33 #include "llvm/CodeGen/TargetInstrInfo.h"
34 #include "llvm/CodeGen/TargetOpcodes.h"
35 #include "llvm/CodeGen/TargetRegisterInfo.h"
36 #include "llvm/CodeGen/TargetSubtargetInfo.h"
37 #include "llvm/IR/DebugLoc.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/MC/MCInstrDesc.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/raw_ostream.h"
53 #define DEBUG_TYPE "regalloc"
55 STATISTIC(NumStores, "Number of stores added");
56 STATISTIC(NumLoads , "Number of loads added");
57 STATISTIC(NumCopies, "Number of copies coalesced");
59 static RegisterRegAlloc
60 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
64 class RegAllocFast : public MachineFunctionPass {
68 RegAllocFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1) {}
71 MachineFrameInfo *MFI;
72 MachineRegisterInfo *MRI;
73 const TargetRegisterInfo *TRI;
74 const TargetInstrInfo *TII;
75 RegisterClassInfo RegClassInfo;
77 /// Basic block currently being allocated.
78 MachineBasicBlock *MBB;
80 /// Maps virtual regs to the frame index where these values are spilled.
81 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
83 /// Everything we know about a live virtual register.
85 MachineInstr *LastUse = nullptr; ///< Last instr to use reg.
86 unsigned VirtReg; ///< Virtual register number.
87 MCPhysReg PhysReg = 0; ///< Currently held here.
88 unsigned short LastOpNum = 0; ///< OpNum on LastUse.
89 bool Dirty = false; ///< Register needs spill.
91 explicit LiveReg(unsigned v) : VirtReg(v) {}
93 unsigned getSparseSetIndex() const {
94 return TargetRegisterInfo::virtReg2Index(VirtReg);
98 using LiveRegMap = SparseSet<LiveReg>;
100 /// This map contains entries for each virtual register that is currently
101 /// available in a physical register.
102 LiveRegMap LiveVirtRegs;
104 DenseMap<unsigned, SmallVector<MachineInstr *, 4>> LiveDbgValueMap;
106 /// Track the state of a physical register.
108 /// A disabled register is not available for allocation, but an alias may
109 /// be in use. A register can only be moved out of the disabled state if
110 /// all aliases are disabled.
113 /// A free register is not currently in use and can be allocated
114 /// immediately without checking aliases.
117 /// A reserved register has been assigned explicitly (e.g., setting up a
118 /// call parameter), and it remains reserved until it is used.
121 /// A register state may also be a virtual register number, indication
122 /// that the physical register is currently allocated to a virtual
123 /// register. In that case, LiveVirtRegs contains the inverse mapping.
126 /// One of the RegState enums, or a virtreg.
127 std::vector<unsigned> PhysRegState;
129 SmallVector<unsigned, 16> VirtDead;
130 SmallVector<MachineInstr *, 32> Coalesced;
132 /// Set of register units.
133 using UsedInInstrSet = SparseSet<unsigned>;
135 /// Set of register units that are used in the current instruction, and so
136 /// cannot be allocated.
137 UsedInInstrSet UsedInInstr;
139 /// Mark a physreg as used in this instruction.
140 void markRegUsedInInstr(MCPhysReg PhysReg) {
141 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
142 UsedInInstr.insert(*Units);
145 /// Check if a physreg or any of its aliases are used in this instruction.
146 bool isRegUsedInInstr(MCPhysReg PhysReg) const {
147 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
148 if (UsedInInstr.count(*Units))
153 /// This flag is set when LiveRegMap will be cleared completely after
154 /// spilling all live registers. LiveRegMap entries should not be erased.
155 bool isBulkSpilling = false;
160 spillImpossible = ~0u
164 StringRef getPassName() const override { return "Fast Register Allocator"; }
166 void getAnalysisUsage(AnalysisUsage &AU) const override {
167 AU.setPreservesCFG();
168 MachineFunctionPass::getAnalysisUsage(AU);
171 MachineFunctionProperties getRequiredProperties() const override {
172 return MachineFunctionProperties().set(
173 MachineFunctionProperties::Property::NoPHIs);
176 MachineFunctionProperties getSetProperties() const override {
177 return MachineFunctionProperties().set(
178 MachineFunctionProperties::Property::NoVRegs);
182 bool runOnMachineFunction(MachineFunction &Fn) override;
183 void allocateBasicBlock(MachineBasicBlock &MBB);
184 void handleThroughOperands(MachineInstr &MI,
185 SmallVectorImpl<unsigned> &VirtDead);
186 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass &RC);
187 bool isLastUseOfLocalReg(const MachineOperand &MO) const;
189 void addKillFlag(const LiveReg &LRI);
190 void killVirtReg(LiveRegMap::iterator LRI);
191 void killVirtReg(unsigned VirtReg);
192 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
193 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
195 void usePhysReg(MachineOperand &MO);
196 void definePhysReg(MachineInstr &MI, MCPhysReg PhysReg, RegState NewState);
197 unsigned calcSpillCost(MCPhysReg PhysReg) const;
198 void assignVirtToPhysReg(LiveReg&, MCPhysReg PhysReg);
200 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
201 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
204 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
205 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
208 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, MCPhysReg PhysReg);
209 LiveRegMap::iterator allocVirtReg(MachineInstr &MI, LiveRegMap::iterator,
211 LiveRegMap::iterator defineVirtReg(MachineInstr &MI, unsigned OpNum,
212 unsigned VirtReg, unsigned Hint);
213 LiveRegMap::iterator reloadVirtReg(MachineInstr &MI, unsigned OpNum,
214 unsigned VirtReg, unsigned Hint);
215 void spillAll(MachineBasicBlock::iterator MI);
216 bool setPhysReg(MachineInstr &MI, unsigned OpNum, MCPhysReg PhysReg);
221 } // end anonymous namespace
223 char RegAllocFast::ID = 0;
225 INITIALIZE_PASS(RegAllocFast, "regallocfast", "Fast Register Allocator", false,
228 /// This allocates space for the specified virtual register to be held on the
230 int RegAllocFast::getStackSpaceFor(unsigned VirtReg,
231 const TargetRegisterClass &RC) {
232 // Find the location Reg would belong...
233 int SS = StackSlotForVirtReg[VirtReg];
234 // Already has space allocated?
238 // Allocate a new stack object for this spill location...
239 unsigned Size = TRI->getSpillSize(RC);
240 unsigned Align = TRI->getSpillAlignment(RC);
241 int FrameIdx = MFI->CreateSpillStackObject(Size, Align);
244 StackSlotForVirtReg[VirtReg] = FrameIdx;
248 /// Return true if MO is the only remaining reference to its virtual register,
249 /// and it is guaranteed to be a block-local register.
250 bool RegAllocFast::isLastUseOfLocalReg(const MachineOperand &MO) const {
251 // If the register has ever been spilled or reloaded, we conservatively assume
252 // it is a global register used in multiple blocks.
253 if (StackSlotForVirtReg[MO.getReg()] != -1)
256 // Check that the use/def chain has exactly one operand - MO.
257 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
260 return ++I == MRI->reg_nodbg_end();
263 /// Set kill flags on last use of a virtual register.
264 void RegAllocFast::addKillFlag(const LiveReg &LR) {
265 if (!LR.LastUse) return;
266 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
267 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
268 if (MO.getReg() == LR.PhysReg)
270 // else, don't do anything we are problably redefining a
271 // subreg of this register and given we don't track which
272 // lanes are actually dead, we cannot insert a kill flag here.
273 // Otherwise we may end up in a situation like this:
274 // ... = (MO) physreg:sub1, implicit killed physreg
275 // ... <== Here we would allow later pass to reuse physreg:sub1
276 // which is potentially wrong.
278 // ... = LR.sub1 <== This is going to use physreg:sub1
282 /// Mark virtreg as no longer available.
283 void RegAllocFast::killVirtReg(LiveRegMap::iterator LRI) {
285 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
286 "Broken RegState mapping");
287 PhysRegState[LRI->PhysReg] = regFree;
288 // Erase from LiveVirtRegs unless we're spilling in bulk.
290 LiveVirtRegs.erase(LRI);
293 /// Mark virtreg as no longer available.
294 void RegAllocFast::killVirtReg(unsigned VirtReg) {
295 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
296 "killVirtReg needs a virtual register");
297 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
298 if (LRI != LiveVirtRegs.end())
302 /// This method spills the value specified by VirtReg into the corresponding
303 /// stack slot if needed.
304 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
306 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
307 "Spilling a physical register is illegal!");
308 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
309 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
310 spillVirtReg(MI, LRI);
313 /// Do the actual work of spilling.
314 void RegAllocFast::spillVirtReg(MachineBasicBlock::iterator MI,
315 LiveRegMap::iterator LRI) {
317 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
320 // If this physreg is used by the instruction, we want to kill it on the
321 // instruction, not on the spill.
322 bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
324 DEBUG(dbgs() << "Spilling " << printReg(LRI->VirtReg, TRI)
325 << " in " << printReg(LR.PhysReg, TRI));
326 const TargetRegisterClass &RC = *MRI->getRegClass(LRI->VirtReg);
327 int FI = getStackSpaceFor(LRI->VirtReg, RC);
328 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
329 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, &RC, TRI);
330 ++NumStores; // Update statistics
332 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
333 // identify spilled location as the place to find corresponding variable's
335 SmallVectorImpl<MachineInstr *> &LRIDbgValues =
336 LiveDbgValueMap[LRI->VirtReg];
337 for (MachineInstr *DBG : LRIDbgValues) {
338 MachineInstr *NewDV = buildDbgValueForSpill(*MBB, MI, *DBG, FI);
339 assert(NewDV->getParent() == MBB && "dangling parent pointer");
341 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
343 // Now this register is spilled there is should not be any DBG_VALUE
344 // pointing to this register because they are all pointing to spilled value
346 LRIDbgValues.clear();
348 LR.LastUse = nullptr; // Don't kill register again
353 /// Spill all dirty virtregs without killing them.
354 void RegAllocFast::spillAll(MachineBasicBlock::iterator MI) {
355 if (LiveVirtRegs.empty()) return;
356 isBulkSpilling = true;
357 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
358 // of spilling here is deterministic, if arbitrary.
359 for (LiveRegMap::iterator I = LiveVirtRegs.begin(), E = LiveVirtRegs.end();
362 LiveVirtRegs.clear();
363 isBulkSpilling = false;
366 /// Handle the direct use of a physical register. Check that the register is
367 /// not used by a virtreg. Kill the physreg, marking it free. This may add
368 /// implicit kills to MO->getParent() and invalidate MO.
369 void RegAllocFast::usePhysReg(MachineOperand &MO) {
370 // Ignore undef uses.
374 unsigned PhysReg = MO.getReg();
375 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
376 "Bad usePhysReg operand");
378 markRegUsedInInstr(PhysReg);
379 switch (PhysRegState[PhysReg]) {
383 PhysRegState[PhysReg] = regFree;
389 // The physreg was allocated to a virtual register. That means the value we
390 // wanted has been clobbered.
391 llvm_unreachable("Instruction uses an allocated register");
394 // Maybe a superregister is reserved?
395 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
396 MCPhysReg Alias = *AI;
397 switch (PhysRegState[Alias]) {
401 // Either PhysReg is a subregister of Alias and we mark the
402 // whole register as free, or PhysReg is the superregister of
403 // Alias and we mark all the aliases as disabled before freeing
405 // In the latter case, since PhysReg was disabled, this means that
406 // its value is defined only by physical sub-registers. This check
407 // is performed by the assert of the default case in this loop.
408 // Note: The value of the superregister may only be partial
409 // defined, that is why regDisabled is a valid state for aliases.
410 assert((TRI->isSuperRegister(PhysReg, Alias) ||
411 TRI->isSuperRegister(Alias, PhysReg)) &&
412 "Instruction is not using a subregister of a reserved register");
415 if (TRI->isSuperRegister(PhysReg, Alias)) {
416 // Leave the superregister in the working set.
417 PhysRegState[Alias] = regFree;
418 MO.getParent()->addRegisterKilled(Alias, TRI, true);
421 // Some other alias was in the working set - clear it.
422 PhysRegState[Alias] = regDisabled;
425 llvm_unreachable("Instruction uses an alias of an allocated register");
429 // All aliases are disabled, bring register into working set.
430 PhysRegState[PhysReg] = regFree;
434 /// Mark PhysReg as reserved or free after spilling any virtregs. This is very
435 /// similar to defineVirtReg except the physreg is reserved instead of
437 void RegAllocFast::definePhysReg(MachineInstr &MI, MCPhysReg PhysReg,
439 markRegUsedInInstr(PhysReg);
440 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
444 spillVirtReg(MI, VirtReg);
448 PhysRegState[PhysReg] = NewState;
452 // This is a disabled register, disable all aliases.
453 PhysRegState[PhysReg] = NewState;
454 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
455 MCPhysReg Alias = *AI;
456 switch (unsigned VirtReg = PhysRegState[Alias]) {
460 spillVirtReg(MI, VirtReg);
464 PhysRegState[Alias] = regDisabled;
465 if (TRI->isSuperRegister(PhysReg, Alias))
472 /// \brief Return the cost of spilling clearing out PhysReg and aliases so it is
473 /// free for allocation. Returns 0 when PhysReg is free or disabled with all
474 /// aliases disabled - it can be allocated directly.
475 /// \returns spillImpossible when PhysReg or an alias can't be spilled.
476 unsigned RegAllocFast::calcSpillCost(MCPhysReg PhysReg) const {
477 if (isRegUsedInInstr(PhysReg)) {
478 DEBUG(dbgs() << printReg(PhysReg, TRI) << " is already used in instr.\n");
479 return spillImpossible;
481 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
487 DEBUG(dbgs() << printReg(VirtReg, TRI) << " corresponding "
488 << printReg(PhysReg, TRI) << " is reserved already.\n");
489 return spillImpossible;
491 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
492 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
493 return I->Dirty ? spillDirty : spillClean;
497 // This is a disabled register, add up cost of aliases.
498 DEBUG(dbgs() << printReg(PhysReg, TRI) << " is disabled.\n");
500 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
501 MCPhysReg Alias = *AI;
502 switch (unsigned VirtReg = PhysRegState[Alias]) {
509 return spillImpossible;
511 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
512 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
513 Cost += I->Dirty ? spillDirty : spillClean;
521 /// \brief This method updates local state so that we know that PhysReg is the
522 /// proper container for VirtReg now. The physical register must not be used
523 /// for anything else when this is called.
524 void RegAllocFast::assignVirtToPhysReg(LiveReg &LR, MCPhysReg PhysReg) {
525 DEBUG(dbgs() << "Assigning " << printReg(LR.VirtReg, TRI) << " to "
526 << printReg(PhysReg, TRI) << "\n");
527 PhysRegState[PhysReg] = LR.VirtReg;
528 assert(!LR.PhysReg && "Already assigned a physreg");
529 LR.PhysReg = PhysReg;
532 RegAllocFast::LiveRegMap::iterator
533 RegAllocFast::assignVirtToPhysReg(unsigned VirtReg, MCPhysReg PhysReg) {
534 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
535 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
536 assignVirtToPhysReg(*LRI, PhysReg);
540 /// Allocates a physical register for VirtReg.
541 RegAllocFast::LiveRegMap::iterator RegAllocFast::allocVirtReg(MachineInstr &MI,
542 LiveRegMap::iterator LRI, unsigned Hint) {
543 const unsigned VirtReg = LRI->VirtReg;
545 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
546 "Can only allocate virtual registers");
548 // Take hint when possible.
549 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
550 if (TargetRegisterInfo::isPhysicalRegister(Hint) &&
551 MRI->isAllocatable(Hint) && RC.contains(Hint)) {
552 // Ignore the hint if we would have to spill a dirty register.
553 unsigned Cost = calcSpillCost(Hint);
554 if (Cost < spillDirty) {
556 definePhysReg(MI, Hint, regFree);
557 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
558 // That invalidates LRI, so run a new lookup for VirtReg.
559 return assignVirtToPhysReg(VirtReg, Hint);
563 // First try to find a completely free register.
564 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(&RC);
565 for (MCPhysReg PhysReg : AO) {
566 if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
567 assignVirtToPhysReg(*LRI, PhysReg);
572 DEBUG(dbgs() << "Allocating " << printReg(VirtReg) << " from "
573 << TRI->getRegClassName(&RC) << "\n");
575 unsigned BestReg = 0;
576 unsigned BestCost = spillImpossible;
577 for (MCPhysReg PhysReg : AO) {
578 unsigned Cost = calcSpillCost(PhysReg);
579 DEBUG(dbgs() << "\tRegister: " << printReg(PhysReg, TRI) << "\n");
580 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
581 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
582 // Cost is 0 when all aliases are already disabled.
584 assignVirtToPhysReg(*LRI, PhysReg);
588 BestReg = PhysReg, BestCost = Cost;
592 definePhysReg(MI, BestReg, regFree);
593 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
594 // That invalidates LRI, so run a new lookup for VirtReg.
595 return assignVirtToPhysReg(VirtReg, BestReg);
598 // Nothing we can do. Report an error and keep going with a bad allocation.
599 if (MI.isInlineAsm())
600 MI.emitError("inline assembly requires more registers than available");
602 MI.emitError("ran out of registers during register allocation");
603 definePhysReg(MI, *AO.begin(), regFree);
604 return assignVirtToPhysReg(VirtReg, *AO.begin());
607 /// Allocates a register for VirtReg and mark it as dirty.
608 RegAllocFast::LiveRegMap::iterator RegAllocFast::defineVirtReg(MachineInstr &MI,
612 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
613 "Not a virtual register");
614 LiveRegMap::iterator LRI;
616 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
618 // If there is no hint, peek at the only use of this register.
619 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
620 MRI->hasOneNonDBGUse(VirtReg)) {
621 const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
622 // It's a copy, use the destination register as a hint.
623 if (UseMI.isCopyLike())
624 Hint = UseMI.getOperand(0).getReg();
626 LRI = allocVirtReg(MI, LRI, Hint);
627 } else if (LRI->LastUse) {
628 // Redefining a live register - kill at the last use, unless it is this
629 // instruction defining VirtReg multiple times.
630 if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
633 assert(LRI->PhysReg && "Register not assigned");
635 LRI->LastOpNum = OpNum;
637 markRegUsedInInstr(LRI->PhysReg);
641 /// Make sure VirtReg is available in a physreg and return it.
642 RegAllocFast::LiveRegMap::iterator RegAllocFast::reloadVirtReg(MachineInstr &MI,
646 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
647 "Not a virtual register");
648 LiveRegMap::iterator LRI;
650 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
651 MachineOperand &MO = MI.getOperand(OpNum);
653 LRI = allocVirtReg(MI, LRI, Hint);
654 const TargetRegisterClass &RC = *MRI->getRegClass(VirtReg);
655 int FrameIndex = getStackSpaceFor(VirtReg, RC);
656 DEBUG(dbgs() << "Reloading " << printReg(VirtReg, TRI) << " into "
657 << printReg(LRI->PhysReg, TRI) << "\n");
658 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, &RC, TRI);
660 } else if (LRI->Dirty) {
661 if (isLastUseOfLocalReg(MO)) {
662 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
667 } else if (MO.isKill()) {
668 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
670 } else if (MO.isDead()) {
671 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
674 } else if (MO.isKill()) {
675 // We must remove kill flags from uses of reloaded registers because the
676 // register would be killed immediately, and there might be a second use:
677 // %foo = OR killed %x, %x
678 // This would cause a second reload of %x into a different register.
679 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
681 } else if (MO.isDead()) {
682 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
685 assert(LRI->PhysReg && "Register not assigned");
687 LRI->LastOpNum = OpNum;
688 markRegUsedInInstr(LRI->PhysReg);
692 /// Changes operand OpNum in MI the refer the PhysReg, considering subregs. This
693 /// may invalidate any operand pointers. Return true if the operand kills its
695 bool RegAllocFast::setPhysReg(MachineInstr &MI, unsigned OpNum,
697 MachineOperand &MO = MI.getOperand(OpNum);
698 bool Dead = MO.isDead();
699 if (!MO.getSubReg()) {
701 MO.setIsRenamableIfNoExtraRegAllocReq();
702 return MO.isKill() || Dead;
705 // Handle subregister index.
706 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
707 MO.setIsRenamableIfNoExtraRegAllocReq();
710 // A kill flag implies killing the full register. Add corresponding super
713 MI.addRegisterKilled(PhysReg, TRI, true);
717 // A <def,read-undef> of a sub-register requires an implicit def of the full
719 if (MO.isDef() && MO.isUndef())
720 MI.addRegisterDefined(PhysReg, TRI);
725 // Handles special instruction operand like early clobbers and tied ops when
726 // there are additional physreg defines.
727 void RegAllocFast::handleThroughOperands(MachineInstr &MI,
728 SmallVectorImpl<unsigned> &VirtDead) {
729 DEBUG(dbgs() << "Scanning for through registers:");
730 SmallSet<unsigned, 8> ThroughRegs;
731 for (const MachineOperand &MO : MI.operands()) {
732 if (!MO.isReg()) continue;
733 unsigned Reg = MO.getReg();
734 if (!TargetRegisterInfo::isVirtualRegister(Reg))
736 if (MO.isEarlyClobber() || (MO.isUse() && MO.isTied()) ||
737 (MO.getSubReg() && MI.readsVirtualRegister(Reg))) {
738 if (ThroughRegs.insert(Reg).second)
739 DEBUG(dbgs() << ' ' << printReg(Reg));
743 // If any physreg defines collide with preallocated through registers,
744 // we must spill and reallocate.
745 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
746 for (const MachineOperand &MO : MI.operands()) {
747 if (!MO.isReg() || !MO.isDef()) continue;
748 unsigned Reg = MO.getReg();
749 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
750 markRegUsedInInstr(Reg);
751 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
752 if (ThroughRegs.count(PhysRegState[*AI]))
753 definePhysReg(MI, *AI, regFree);
757 SmallVector<unsigned, 8> PartialDefs;
758 DEBUG(dbgs() << "Allocating tied uses.\n");
759 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
760 const MachineOperand &MO = MI.getOperand(I);
761 if (!MO.isReg()) continue;
762 unsigned Reg = MO.getReg();
763 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
765 if (!MO.isTied()) continue;
766 DEBUG(dbgs() << "Operand " << I << "("<< MO << ") is tied to operand "
767 << MI.findTiedOperandIdx(I) << ".\n");
768 LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0);
769 MCPhysReg PhysReg = LRI->PhysReg;
770 setPhysReg(MI, I, PhysReg);
771 // Note: we don't update the def operand yet. That would cause the normal
772 // def-scan to attempt spilling.
773 } else if (MO.getSubReg() && MI.readsVirtualRegister(Reg)) {
774 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
775 // Reload the register, but don't assign to the operand just yet.
776 // That would confuse the later phys-def processing pass.
777 LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, 0);
778 PartialDefs.push_back(LRI->PhysReg);
782 DEBUG(dbgs() << "Allocating early clobbers.\n");
783 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) {
784 const MachineOperand &MO = MI.getOperand(I);
785 if (!MO.isReg()) continue;
786 unsigned Reg = MO.getReg();
787 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
788 if (!MO.isEarlyClobber())
790 // Note: defineVirtReg may invalidate MO.
791 LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, 0);
792 MCPhysReg PhysReg = LRI->PhysReg;
793 if (setPhysReg(MI, I, PhysReg))
794 VirtDead.push_back(Reg);
797 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
799 for (const MachineOperand &MO : MI.operands()) {
800 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
801 unsigned Reg = MO.getReg();
802 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
803 DEBUG(dbgs() << "\tSetting " << printReg(Reg, TRI)
804 << " as used in instr\n");
805 markRegUsedInInstr(Reg);
808 // Also mark PartialDefs as used to avoid reallocation.
809 for (unsigned PartialDef : PartialDefs)
810 markRegUsedInInstr(PartialDef);
814 void RegAllocFast::dumpState() {
815 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
816 if (PhysRegState[Reg] == regDisabled) continue;
817 dbgs() << " " << printReg(Reg, TRI);
818 switch(PhysRegState[Reg]) {
825 dbgs() << '=' << printReg(PhysRegState[Reg]);
826 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
827 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
830 assert(I->PhysReg == Reg && "Bad inverse map");
836 // Check that LiveVirtRegs is the inverse.
837 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
838 e = LiveVirtRegs.end(); i != e; ++i) {
839 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
841 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
843 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
848 void RegAllocFast::allocateBasicBlock(MachineBasicBlock &MBB) {
850 DEBUG(dbgs() << "\nAllocating " << MBB);
852 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
853 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
855 MachineBasicBlock::iterator MII = MBB.begin();
857 // Add live-in registers as live.
858 for (const MachineBasicBlock::RegisterMaskPair LI : MBB.liveins())
859 if (MRI->isAllocatable(LI.PhysReg))
860 definePhysReg(*MII, LI.PhysReg, regReserved);
865 // Otherwise, sequentially allocate each instruction in the MBB.
866 for (MachineInstr &MI : MBB) {
867 const MCInstrDesc &MCID = MI.getDesc();
869 dbgs() << "\n>> " << MI << "Regs:";
873 // Debug values are not allowed to change codegen in any way.
874 if (MI.isDebugValue()) {
875 MachineInstr *DebugMI = &MI;
876 MachineOperand &MO = DebugMI->getOperand(0);
878 // Ignore DBG_VALUEs that aren't based on virtual registers. These are
879 // mostly constants and frame indices.
882 unsigned Reg = MO.getReg();
883 if (!TargetRegisterInfo::isVirtualRegister(Reg))
886 // See if this virtual register has already been allocated to a physical
887 // register or spilled to a stack slot.
888 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
889 if (LRI != LiveVirtRegs.end())
890 setPhysReg(*DebugMI, 0, LRI->PhysReg);
892 int SS = StackSlotForVirtReg[Reg];
894 // Modify DBG_VALUE now that the value is in a spill slot.
895 updateDbgValueForSpill(*DebugMI, SS);
896 DEBUG(dbgs() << "Modifying debug info due to spill:"
897 << "\t" << *DebugMI);
901 // We can't allocate a physreg for a DebugValue, sorry!
902 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
906 // If Reg hasn't been spilled, put this DBG_VALUE in LiveDbgValueMap so
907 // that future spills of Reg will have DBG_VALUEs.
908 LiveDbgValueMap[Reg].push_back(DebugMI);
912 // If this is a copy, we may be able to coalesce.
913 unsigned CopySrcReg = 0;
914 unsigned CopyDstReg = 0;
915 unsigned CopySrcSub = 0;
916 unsigned CopyDstSub = 0;
918 CopyDstReg = MI.getOperand(0).getReg();
919 CopySrcReg = MI.getOperand(1).getReg();
920 CopyDstSub = MI.getOperand(0).getSubReg();
921 CopySrcSub = MI.getOperand(1).getSubReg();
924 // Track registers used by instruction.
928 // Mark physreg uses and early clobbers as used.
929 // Find the end of the virtreg operands
930 unsigned VirtOpEnd = 0;
931 bool hasTiedOps = false;
932 bool hasEarlyClobbers = false;
933 bool hasPartialRedefs = false;
934 bool hasPhysDefs = false;
935 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
936 MachineOperand &MO = MI.getOperand(i);
937 // Make sure MRI knows about registers clobbered by regmasks.
938 if (MO.isRegMask()) {
939 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
942 if (!MO.isReg()) continue;
943 unsigned Reg = MO.getReg();
945 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
948 hasTiedOps = hasTiedOps ||
949 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
951 if (MO.isEarlyClobber())
952 hasEarlyClobbers = true;
953 if (MO.getSubReg() && MI.readsVirtualRegister(Reg))
954 hasPartialRedefs = true;
958 if (!MRI->isAllocatable(Reg)) continue;
961 } else if (MO.isEarlyClobber()) {
962 definePhysReg(MI, Reg,
963 (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
964 hasEarlyClobbers = true;
969 // The instruction may have virtual register operands that must be allocated
970 // the same register at use-time and def-time: early clobbers and tied
971 // operands. If there are also physical defs, these registers must avoid
972 // both physical defs and uses, making them more constrained than normal
974 // Similarly, if there are multiple defs and tied operands, we must make
975 // sure the same register is allocated to uses and defs.
976 // We didn't detect inline asm tied operands above, so just make this extra
977 // pass for all inline asm.
978 if (MI.isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
979 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
980 handleThroughOperands(MI, VirtDead);
981 // Don't attempt coalescing when we have funny stuff going on.
983 // Pretend we have early clobbers so the use operands get marked below.
984 // This is not necessary for the common case of a single tied use.
985 hasEarlyClobbers = true;
989 // Allocate virtreg uses.
990 for (unsigned I = 0; I != VirtOpEnd; ++I) {
991 const MachineOperand &MO = MI.getOperand(I);
992 if (!MO.isReg()) continue;
993 unsigned Reg = MO.getReg();
994 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
996 LiveRegMap::iterator LRI = reloadVirtReg(MI, I, Reg, CopyDstReg);
997 MCPhysReg PhysReg = LRI->PhysReg;
998 CopySrcReg = (CopySrcReg == Reg || CopySrcReg == PhysReg) ? PhysReg : 0;
999 if (setPhysReg(MI, I, PhysReg))
1004 // Track registers defined by instruction - early clobbers and tied uses at
1006 UsedInInstr.clear();
1007 if (hasEarlyClobbers) {
1008 for (const MachineOperand &MO : MI.operands()) {
1009 if (!MO.isReg()) continue;
1010 unsigned Reg = MO.getReg();
1011 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1012 // Look for physreg defs and tied uses.
1013 if (!MO.isDef() && !MO.isTied()) continue;
1014 markRegUsedInInstr(Reg);
1018 unsigned DefOpEnd = MI.getNumOperands();
1020 // Spill all virtregs before a call. This serves one purpose: If an
1021 // exception is thrown, the landing pad is going to expect to find
1022 // registers in their spill slots.
1023 // Note: although this is appealing to just consider all definitions
1024 // as call-clobbered, this is not correct because some of those
1025 // definitions may be used later on and we do not want to reuse
1026 // those for virtual registers in between.
1027 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1032 // Allocate defs and collect dead defs.
1033 for (unsigned I = 0; I != DefOpEnd; ++I) {
1034 const MachineOperand &MO = MI.getOperand(I);
1035 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1037 unsigned Reg = MO.getReg();
1039 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1040 if (!MRI->isAllocatable(Reg)) continue;
1041 definePhysReg(MI, Reg, MO.isDead() ? regFree : regReserved);
1044 LiveRegMap::iterator LRI = defineVirtReg(MI, I, Reg, CopySrcReg);
1045 MCPhysReg PhysReg = LRI->PhysReg;
1046 if (setPhysReg(MI, I, PhysReg)) {
1047 VirtDead.push_back(Reg);
1048 CopyDstReg = 0; // cancel coalescing;
1050 CopyDstReg = (CopyDstReg == Reg || CopyDstReg == PhysReg) ? PhysReg : 0;
1053 // Kill dead defs after the scan to ensure that multiple defs of the same
1054 // register are allocated identically. We didn't need to do this for uses
1055 // because we are crerating our own kill flags, and they are always at the
1057 for (unsigned VirtReg : VirtDead)
1058 killVirtReg(VirtReg);
1061 if (CopyDstReg && CopyDstReg == CopySrcReg && CopyDstSub == CopySrcSub) {
1062 DEBUG(dbgs() << "-- coalescing: " << MI);
1063 Coalesced.push_back(&MI);
1065 DEBUG(dbgs() << "<< " << MI);
1069 // Spill all physical registers holding virtual registers now.
1070 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1071 spillAll(MBB.getFirstTerminator());
1073 // Erase all the coalesced copies. We are delaying it until now because
1074 // LiveVirtRegs might refer to the instrs.
1075 for (MachineInstr *MI : Coalesced)
1077 NumCopies += Coalesced.size();
1082 /// Allocates registers for a function.
1083 bool RegAllocFast::runOnMachineFunction(MachineFunction &MF) {
1084 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1085 << "********** Function: " << MF.getName() << '\n');
1086 MRI = &MF.getRegInfo();
1087 const TargetSubtargetInfo &STI = MF.getSubtarget();
1088 TRI = STI.getRegisterInfo();
1089 TII = STI.getInstrInfo();
1090 MFI = &MF.getFrameInfo();
1091 MRI->freezeReservedRegs(MF);
1092 RegClassInfo.runOnMachineFunction(MF);
1093 UsedInInstr.clear();
1094 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1096 // initialize the virtual->physical register map to have a 'null'
1097 // mapping for all virtual registers
1098 unsigned NumVirtRegs = MRI->getNumVirtRegs();
1099 StackSlotForVirtReg.resize(NumVirtRegs);
1100 LiveVirtRegs.setUniverse(NumVirtRegs);
1102 // Loop over all of the basic blocks, eliminating virtual register references
1103 for (MachineBasicBlock &MBB : MF)
1104 allocateBasicBlock(MBB);
1106 // All machine operands and other references to virtual registers have been
1107 // replaced. Remove the virtual registers.
1108 MRI->clearVirtRegs();
1110 StackSlotForVirtReg.clear();
1111 LiveDbgValueMap.clear();
1115 FunctionPass *llvm::createFastRegisterAllocator() {
1116 return new RegAllocFast();