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 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/IndexedMap.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/SparseSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 #define DEBUG_TYPE "regalloc"
40 STATISTIC(NumStores, "Number of stores added");
41 STATISTIC(NumLoads , "Number of loads added");
42 STATISTIC(NumCopies, "Number of copies coalesced");
44 static RegisterRegAlloc
45 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
48 class RAFast : public MachineFunctionPass {
51 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
52 isBulkSpilling(false) {}
56 MachineRegisterInfo *MRI;
57 const TargetRegisterInfo *TRI;
58 const TargetInstrInfo *TII;
59 RegisterClassInfo RegClassInfo;
61 // Basic block currently being allocated.
62 MachineBasicBlock *MBB;
64 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
65 // values are spilled.
66 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
68 // Everything we know about a live virtual register.
70 MachineInstr *LastUse; // Last instr to use reg.
71 unsigned VirtReg; // Virtual register number.
72 unsigned PhysReg; // Currently held here.
73 unsigned short LastOpNum; // OpNum on LastUse.
74 bool Dirty; // Register needs spill.
76 explicit LiveReg(unsigned v)
77 : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
79 unsigned getSparseSetIndex() const {
80 return TargetRegisterInfo::virtReg2Index(VirtReg);
84 typedef SparseSet<LiveReg> LiveRegMap;
86 // LiveVirtRegs - This map contains entries for each virtual register
87 // that is currently available in a physical register.
88 LiveRegMap LiveVirtRegs;
90 DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
92 // RegState - Track the state of a physical register.
94 // A disabled register is not available for allocation, but an alias may
95 // be in use. A register can only be moved out of the disabled state if
96 // all aliases are disabled.
99 // A free register is not currently in use and can be allocated
100 // immediately without checking aliases.
103 // A reserved register has been assigned explicitly (e.g., setting up a
104 // call parameter), and it remains reserved until it is used.
107 // A register state may also be a virtual register number, indication that
108 // the physical register is currently allocated to a virtual register. In
109 // that case, LiveVirtRegs contains the inverse mapping.
112 // PhysRegState - One of the RegState enums, or a virtreg.
113 std::vector<unsigned> PhysRegState;
115 // Set of register units.
116 typedef SparseSet<unsigned> UsedInInstrSet;
118 // Set of register units that are used in the current instruction, and so
119 // cannot be allocated.
120 UsedInInstrSet UsedInInstr;
122 // Mark a physreg as used in this instruction.
123 void markRegUsedInInstr(unsigned PhysReg) {
124 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
125 UsedInInstr.insert(*Units);
128 // Check if a physreg or any of its aliases are used in this instruction.
129 bool isRegUsedInInstr(unsigned PhysReg) const {
130 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
131 if (UsedInInstr.count(*Units))
136 // SkippedInstrs - Descriptors of instructions whose clobber list was
137 // ignored because all registers were spilled. It is still necessary to
138 // mark all the clobbered registers as used by the function.
139 SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
141 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
142 // completely after spilling all live registers. LiveRegMap entries should
149 spillImpossible = ~0u
152 StringRef getPassName() const override { return "Fast Register Allocator"; }
154 void getAnalysisUsage(AnalysisUsage &AU) const override {
155 AU.setPreservesCFG();
156 MachineFunctionPass::getAnalysisUsage(AU);
159 MachineFunctionProperties getRequiredProperties() const override {
160 return MachineFunctionProperties().set(
161 MachineFunctionProperties::Property::NoPHIs);
164 MachineFunctionProperties getSetProperties() const override {
165 return MachineFunctionProperties().set(
166 MachineFunctionProperties::Property::NoVRegs);
170 bool runOnMachineFunction(MachineFunction &Fn) override;
171 void AllocateBasicBlock();
172 void handleThroughOperands(MachineInstr *MI,
173 SmallVectorImpl<unsigned> &VirtDead);
174 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
175 bool isLastUseOfLocalReg(MachineOperand&);
177 void addKillFlag(const LiveReg&);
178 void killVirtReg(LiveRegMap::iterator);
179 void killVirtReg(unsigned VirtReg);
180 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
181 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
183 void usePhysReg(MachineOperand&);
184 void definePhysReg(MachineInstr &MI, unsigned PhysReg, RegState NewState);
185 unsigned calcSpillCost(unsigned PhysReg) const;
186 void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
187 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
188 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
190 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
191 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
193 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
194 LiveRegMap::iterator allocVirtReg(MachineInstr &MI, LiveRegMap::iterator,
196 LiveRegMap::iterator defineVirtReg(MachineInstr &MI, unsigned OpNum,
197 unsigned VirtReg, unsigned Hint);
198 LiveRegMap::iterator reloadVirtReg(MachineInstr &MI, unsigned OpNum,
199 unsigned VirtReg, unsigned Hint);
200 void spillAll(MachineBasicBlock::iterator MI);
201 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
206 /// getStackSpaceFor - This allocates space for the specified virtual register
207 /// to be held on the stack.
208 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
209 // Find the location Reg would belong...
210 int SS = StackSlotForVirtReg[VirtReg];
212 return SS; // Already has space allocated?
214 // Allocate a new stack object for this spill location...
215 int FrameIdx = MF->getFrameInfo().CreateSpillStackObject(RC->getSize(),
219 StackSlotForVirtReg[VirtReg] = FrameIdx;
223 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
224 /// its virtual register, and it is guaranteed to be a block-local register.
226 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
227 // If the register has ever been spilled or reloaded, we conservatively assume
228 // it is a global register used in multiple blocks.
229 if (StackSlotForVirtReg[MO.getReg()] != -1)
232 // Check that the use/def chain has exactly one operand - MO.
233 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
236 return ++I == MRI->reg_nodbg_end();
239 /// addKillFlag - Set kill flags on last use of a virtual register.
240 void RAFast::addKillFlag(const LiveReg &LR) {
241 if (!LR.LastUse) return;
242 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
243 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
244 if (MO.getReg() == LR.PhysReg)
247 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
251 /// killVirtReg - Mark virtreg as no longer available.
252 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
254 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
255 "Broken RegState mapping");
256 PhysRegState[LRI->PhysReg] = regFree;
257 // Erase from LiveVirtRegs unless we're spilling in bulk.
259 LiveVirtRegs.erase(LRI);
262 /// killVirtReg - Mark virtreg as no longer available.
263 void RAFast::killVirtReg(unsigned VirtReg) {
264 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
265 "killVirtReg needs a virtual register");
266 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
267 if (LRI != LiveVirtRegs.end())
271 /// spillVirtReg - This method spills the value specified by VirtReg into the
272 /// corresponding stack slot if needed.
273 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
274 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
275 "Spilling a physical register is illegal!");
276 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
277 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
278 spillVirtReg(MI, LRI);
281 /// spillVirtReg - Do the actual work of spilling.
282 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
283 LiveRegMap::iterator LRI) {
285 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
288 // If this physreg is used by the instruction, we want to kill it on the
289 // instruction, not on the spill.
290 bool SpillKill = MachineBasicBlock::iterator(LR.LastUse) != MI;
292 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
293 << " in " << PrintReg(LR.PhysReg, TRI));
294 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
295 int FI = getStackSpaceFor(LRI->VirtReg, RC);
296 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
297 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
298 ++NumStores; // Update statistics
300 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
301 // identify spilled location as the place to find corresponding variable's
303 SmallVectorImpl<MachineInstr *> &LRIDbgValues =
304 LiveDbgValueMap[LRI->VirtReg];
305 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
306 MachineInstr *DBG = LRIDbgValues[li];
307 const MDNode *Var = DBG->getDebugVariable();
308 const MDNode *Expr = DBG->getDebugExpression();
309 bool IsIndirect = DBG->isIndirectDebugValue();
310 uint64_t Offset = IsIndirect ? DBG->getOperand(1).getImm() : 0;
311 DebugLoc DL = DBG->getDebugLoc();
312 assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
313 "Expected inlined-at fields to agree");
314 MachineInstr *NewDV =
315 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
320 assert(NewDV->getParent() == MBB && "dangling parent pointer");
322 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
324 // Now this register is spilled there is should not be any DBG_VALUE
325 // pointing to this register because they are all pointing to spilled value
327 LRIDbgValues.clear();
329 LR.LastUse = nullptr; // Don't kill register again
334 /// spillAll - Spill all dirty virtregs without killing them.
335 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
336 if (LiveVirtRegs.empty()) return;
337 isBulkSpilling = true;
338 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
339 // of spilling here is deterministic, if arbitrary.
340 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
343 LiveVirtRegs.clear();
344 isBulkSpilling = false;
347 /// usePhysReg - Handle the direct use of a physical register.
348 /// Check that the register is not used by a virtreg.
349 /// Kill the physreg, marking it free.
350 /// This may add implicit kills to MO->getParent() and invalidate MO.
351 void RAFast::usePhysReg(MachineOperand &MO) {
352 unsigned PhysReg = MO.getReg();
353 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
354 "Bad usePhysReg operand");
356 // Ignore undef uses.
360 markRegUsedInInstr(PhysReg);
361 switch (PhysRegState[PhysReg]) {
365 PhysRegState[PhysReg] = regFree;
371 // The physreg was allocated to a virtual register. That means the value we
372 // wanted has been clobbered.
373 llvm_unreachable("Instruction uses an allocated register");
376 // Maybe a superregister is reserved?
377 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
378 unsigned Alias = *AI;
379 switch (PhysRegState[Alias]) {
383 // Either PhysReg is a subregister of Alias and we mark the
384 // whole register as free, or PhysReg is the superregister of
385 // Alias and we mark all the aliases as disabled before freeing
387 // In the latter case, since PhysReg was disabled, this means that
388 // its value is defined only by physical sub-registers. This check
389 // is performed by the assert of the default case in this loop.
390 // Note: The value of the superregister may only be partial
391 // defined, that is why regDisabled is a valid state for aliases.
392 assert((TRI->isSuperRegister(PhysReg, Alias) ||
393 TRI->isSuperRegister(Alias, PhysReg)) &&
394 "Instruction is not using a subregister of a reserved register");
397 if (TRI->isSuperRegister(PhysReg, Alias)) {
398 // Leave the superregister in the working set.
399 PhysRegState[Alias] = regFree;
400 MO.getParent()->addRegisterKilled(Alias, TRI, true);
403 // Some other alias was in the working set - clear it.
404 PhysRegState[Alias] = regDisabled;
407 llvm_unreachable("Instruction uses an alias of an allocated register");
411 // All aliases are disabled, bring register into working set.
412 PhysRegState[PhysReg] = regFree;
416 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
417 /// virtregs. This is very similar to defineVirtReg except the physreg is
418 /// reserved instead of allocated.
419 void RAFast::definePhysReg(MachineInstr &MI, unsigned PhysReg,
421 markRegUsedInInstr(PhysReg);
422 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
426 spillVirtReg(MI, VirtReg);
430 PhysRegState[PhysReg] = NewState;
434 // This is a disabled register, disable all aliases.
435 PhysRegState[PhysReg] = NewState;
436 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
437 unsigned Alias = *AI;
438 switch (unsigned VirtReg = PhysRegState[Alias]) {
442 spillVirtReg(MI, VirtReg);
446 PhysRegState[Alias] = regDisabled;
447 if (TRI->isSuperRegister(PhysReg, Alias))
455 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
456 // aliases so it is free for allocation.
457 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
458 // can be allocated directly.
459 // Returns spillImpossible when PhysReg or an alias can't be spilled.
460 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
461 if (isRegUsedInInstr(PhysReg)) {
462 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
463 return spillImpossible;
465 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
471 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
472 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
473 return spillImpossible;
475 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
476 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
477 return I->Dirty ? spillDirty : spillClean;
481 // This is a disabled register, add up cost of aliases.
482 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
484 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
485 unsigned Alias = *AI;
486 switch (unsigned VirtReg = PhysRegState[Alias]) {
493 return spillImpossible;
495 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
496 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
497 Cost += I->Dirty ? spillDirty : spillClean;
506 /// assignVirtToPhysReg - This method updates local state so that we know
507 /// that PhysReg is the proper container for VirtReg now. The physical
508 /// register must not be used for anything else when this is called.
510 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
511 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
512 << PrintReg(PhysReg, TRI) << "\n");
513 PhysRegState[PhysReg] = LR.VirtReg;
514 assert(!LR.PhysReg && "Already assigned a physreg");
515 LR.PhysReg = PhysReg;
518 RAFast::LiveRegMap::iterator
519 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
520 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
521 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
522 assignVirtToPhysReg(*LRI, PhysReg);
526 /// allocVirtReg - Allocate a physical register for VirtReg.
527 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr &MI,
528 LiveRegMap::iterator LRI,
530 const unsigned VirtReg = LRI->VirtReg;
532 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
533 "Can only allocate virtual registers");
535 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
537 // Ignore invalid hints.
538 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
539 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
542 // Take hint when possible.
544 // Ignore the hint if we would have to spill a dirty register.
545 unsigned Cost = calcSpillCost(Hint);
546 if (Cost < spillDirty) {
548 definePhysReg(MI, Hint, regFree);
549 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
550 // That invalidates LRI, so run a new lookup for VirtReg.
551 return assignVirtToPhysReg(VirtReg, Hint);
555 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
557 // First try to find a completely free register.
558 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
559 unsigned PhysReg = *I;
560 if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
561 assignVirtToPhysReg(*LRI, PhysReg);
566 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
567 << TRI->getRegClassName(RC) << "\n");
569 unsigned BestReg = 0, BestCost = spillImpossible;
570 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
571 unsigned Cost = calcSpillCost(*I);
572 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
573 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
574 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
575 // Cost is 0 when all aliases are already disabled.
577 assignVirtToPhysReg(*LRI, *I);
581 BestReg = *I, BestCost = Cost;
585 definePhysReg(MI, BestReg, regFree);
586 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
587 // That invalidates LRI, so run a new lookup for VirtReg.
588 return assignVirtToPhysReg(VirtReg, BestReg);
591 // Nothing we can do. Report an error and keep going with a bad allocation.
592 if (MI.isInlineAsm())
593 MI.emitError("inline assembly requires more registers than available");
595 MI.emitError("ran out of registers during register allocation");
596 definePhysReg(MI, *AO.begin(), regFree);
597 return assignVirtToPhysReg(VirtReg, *AO.begin());
600 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
601 RAFast::LiveRegMap::iterator RAFast::defineVirtReg(MachineInstr &MI,
605 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
606 "Not a virtual register");
607 LiveRegMap::iterator LRI;
609 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
611 // If there is no hint, peek at the only use of this register.
612 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
613 MRI->hasOneNonDBGUse(VirtReg)) {
614 const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
615 // It's a copy, use the destination register as a hint.
616 if (UseMI.isCopyLike())
617 Hint = UseMI.getOperand(0).getReg();
619 LRI = allocVirtReg(MI, LRI, Hint);
620 } else if (LRI->LastUse) {
621 // Redefining a live register - kill at the last use, unless it is this
622 // instruction defining VirtReg multiple times.
623 if (LRI->LastUse != &MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
626 assert(LRI->PhysReg && "Register not assigned");
628 LRI->LastOpNum = OpNum;
630 markRegUsedInInstr(LRI->PhysReg);
634 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
635 RAFast::LiveRegMap::iterator RAFast::reloadVirtReg(MachineInstr &MI,
639 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
640 "Not a virtual register");
641 LiveRegMap::iterator LRI;
643 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
644 MachineOperand &MO = MI.getOperand(OpNum);
646 LRI = allocVirtReg(MI, LRI, Hint);
647 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
648 int FrameIndex = getStackSpaceFor(VirtReg, RC);
649 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
650 << PrintReg(LRI->PhysReg, TRI) << "\n");
651 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
653 } else if (LRI->Dirty) {
654 if (isLastUseOfLocalReg(MO)) {
655 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
660 } else if (MO.isKill()) {
661 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
663 } else if (MO.isDead()) {
664 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
667 } else if (MO.isKill()) {
668 // We must remove kill flags from uses of reloaded registers because the
669 // register would be killed immediately, and there might be a second use:
670 // %foo = OR %x<kill>, %x
671 // This would cause a second reload of %x into a different register.
672 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
674 } else if (MO.isDead()) {
675 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
678 assert(LRI->PhysReg && "Register not assigned");
680 LRI->LastOpNum = OpNum;
681 markRegUsedInInstr(LRI->PhysReg);
685 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
686 // subregs. This may invalidate any operand pointers.
687 // Return true if the operand kills its register.
688 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
689 MachineOperand &MO = MI->getOperand(OpNum);
690 bool Dead = MO.isDead();
691 if (!MO.getSubReg()) {
693 return MO.isKill() || Dead;
696 // Handle subregister index.
697 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
700 // A kill flag implies killing the full register. Add corresponding super
703 MI->addRegisterKilled(PhysReg, TRI, true);
707 // A <def,read-undef> of a sub-register requires an implicit def of the full
709 if (MO.isDef() && MO.isUndef())
710 MI->addRegisterDefined(PhysReg, TRI);
715 // Handle special instruction operand like early clobbers and tied ops when
716 // there are additional physreg defines.
717 void RAFast::handleThroughOperands(MachineInstr *MI,
718 SmallVectorImpl<unsigned> &VirtDead) {
719 DEBUG(dbgs() << "Scanning for through registers:");
720 SmallSet<unsigned, 8> ThroughRegs;
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))
727 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
728 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
729 if (ThroughRegs.insert(Reg).second)
730 DEBUG(dbgs() << ' ' << PrintReg(Reg));
734 // If any physreg defines collide with preallocated through registers,
735 // we must spill and reallocate.
736 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
737 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
738 MachineOperand &MO = MI->getOperand(i);
739 if (!MO.isReg() || !MO.isDef()) continue;
740 unsigned Reg = MO.getReg();
741 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
742 markRegUsedInInstr(Reg);
743 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
744 if (ThroughRegs.count(PhysRegState[*AI]))
745 definePhysReg(*MI, *AI, regFree);
749 SmallVector<unsigned, 8> PartialDefs;
750 DEBUG(dbgs() << "Allocating tied uses.\n");
751 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
752 MachineOperand &MO = MI->getOperand(i);
753 if (!MO.isReg()) continue;
754 unsigned Reg = MO.getReg();
755 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
758 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
759 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
761 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, 0);
762 unsigned PhysReg = LRI->PhysReg;
763 setPhysReg(MI, i, PhysReg);
764 // Note: we don't update the def operand yet. That would cause the normal
765 // def-scan to attempt spilling.
766 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
767 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
768 // Reload the register, but don't assign to the operand just yet.
769 // That would confuse the later phys-def processing pass.
770 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, 0);
771 PartialDefs.push_back(LRI->PhysReg);
775 DEBUG(dbgs() << "Allocating early clobbers.\n");
776 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
777 MachineOperand &MO = MI->getOperand(i);
778 if (!MO.isReg()) continue;
779 unsigned Reg = MO.getReg();
780 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
781 if (!MO.isEarlyClobber())
783 // Note: defineVirtReg may invalidate MO.
784 LiveRegMap::iterator LRI = defineVirtReg(*MI, i, Reg, 0);
785 unsigned PhysReg = LRI->PhysReg;
786 if (setPhysReg(MI, i, PhysReg))
787 VirtDead.push_back(Reg);
790 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
792 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
793 MachineOperand &MO = MI->getOperand(i);
794 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
795 unsigned Reg = MO.getReg();
796 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
797 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
798 << " as used in instr\n");
799 markRegUsedInInstr(Reg);
802 // Also mark PartialDefs as used to avoid reallocation.
803 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
804 markRegUsedInInstr(PartialDefs[i]);
807 void RAFast::AllocateBasicBlock() {
808 DEBUG(dbgs() << "\nAllocating " << *MBB);
810 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
811 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
813 MachineBasicBlock::iterator MII = MBB->begin();
815 // Add live-in registers as live.
816 for (const auto &LI : MBB->liveins())
817 if (MRI->isAllocatable(LI.PhysReg))
818 definePhysReg(*MII, LI.PhysReg, regReserved);
820 SmallVector<unsigned, 8> VirtDead;
821 SmallVector<MachineInstr*, 32> Coalesced;
823 // Otherwise, sequentially allocate each instruction in the MBB.
824 while (MII != MBB->end()) {
825 MachineInstr *MI = &*MII++;
826 const MCInstrDesc &MCID = MI->getDesc();
828 dbgs() << "\n>> " << *MI << "Regs:";
829 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
830 if (PhysRegState[Reg] == regDisabled) continue;
831 dbgs() << " " << TRI->getName(Reg);
832 switch(PhysRegState[Reg]) {
839 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
840 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
841 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
844 assert(I->PhysReg == Reg && "Bad inverse map");
850 // Check that LiveVirtRegs is the inverse.
851 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
852 e = LiveVirtRegs.end(); i != e; ++i) {
853 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
855 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
857 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
861 // Debug values are not allowed to change codegen in any way.
862 if (MI->isDebugValue()) {
863 bool ScanDbgValue = true;
864 while (ScanDbgValue) {
865 ScanDbgValue = false;
866 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
867 MachineOperand &MO = MI->getOperand(i);
868 if (!MO.isReg()) continue;
869 unsigned Reg = MO.getReg();
870 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
871 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
872 if (LRI != LiveVirtRegs.end())
873 setPhysReg(MI, i, LRI->PhysReg);
875 int SS = StackSlotForVirtReg[Reg];
877 // We can't allocate a physreg for a DebugValue, sorry!
878 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
882 // Modify DBG_VALUE now that the value is in a spill slot.
883 bool IsIndirect = MI->isIndirectDebugValue();
884 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
885 const MDNode *Var = MI->getDebugVariable();
886 const MDNode *Expr = MI->getDebugExpression();
887 DebugLoc DL = MI->getDebugLoc();
888 MachineBasicBlock *MBB = MI->getParent();
890 cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
891 "Expected inlined-at fields to agree");
892 MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
893 TII->get(TargetOpcode::DBG_VALUE))
898 DEBUG(dbgs() << "Modifying debug info due to spill:"
900 // Scan NewDV operands from the beginning.
906 LiveDbgValueMap[Reg].push_back(MI);
913 // If this is a copy, we may be able to coalesce.
914 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
916 CopyDst = MI->getOperand(0).getReg();
917 CopySrc = MI->getOperand(1).getReg();
918 CopyDstSub = MI->getOperand(0).getSubReg();
919 CopySrcSub = MI->getOperand(1).getSubReg();
922 // Track registers used by instruction.
926 // Mark physreg uses and early clobbers as used.
927 // Find the end of the virtreg operands
928 unsigned VirtOpEnd = 0;
929 bool hasTiedOps = false;
930 bool hasEarlyClobbers = false;
931 bool hasPartialRedefs = false;
932 bool hasPhysDefs = false;
933 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
934 MachineOperand &MO = MI->getOperand(i);
935 // Make sure MRI knows about registers clobbered by regmasks.
936 if (MO.isRegMask()) {
937 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
940 if (!MO.isReg()) continue;
941 unsigned Reg = MO.getReg();
943 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
946 hasTiedOps = hasTiedOps ||
947 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
949 if (MO.isEarlyClobber())
950 hasEarlyClobbers = true;
951 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
952 hasPartialRedefs = true;
956 if (!MRI->isAllocatable(Reg)) continue;
959 } else if (MO.isEarlyClobber()) {
960 definePhysReg(*MI, Reg,
961 (MO.isImplicit() || MO.isDead()) ? regFree : regReserved);
962 hasEarlyClobbers = true;
967 // The instruction may have virtual register operands that must be allocated
968 // the same register at use-time and def-time: early clobbers and tied
969 // operands. If there are also physical defs, these registers must avoid
970 // both physical defs and uses, making them more constrained than normal
972 // Similarly, if there are multiple defs and tied operands, we must make
973 // sure the same register is allocated to uses and defs.
974 // We didn't detect inline asm tied operands above, so just make this extra
975 // pass for all inline asm.
976 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
977 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
978 handleThroughOperands(MI, VirtDead);
979 // Don't attempt coalescing when we have funny stuff going on.
981 // Pretend we have early clobbers so the use operands get marked below.
982 // This is not necessary for the common case of a single tied use.
983 hasEarlyClobbers = true;
987 // Allocate virtreg uses.
988 for (unsigned i = 0; i != VirtOpEnd; ++i) {
989 MachineOperand &MO = MI->getOperand(i);
990 if (!MO.isReg()) continue;
991 unsigned Reg = MO.getReg();
992 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
994 LiveRegMap::iterator LRI = reloadVirtReg(*MI, i, Reg, CopyDst);
995 unsigned PhysReg = LRI->PhysReg;
996 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
997 if (setPhysReg(MI, i, PhysReg))
1002 // Track registers defined by instruction - early clobbers and tied uses at
1004 UsedInInstr.clear();
1005 if (hasEarlyClobbers) {
1006 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1007 MachineOperand &MO = MI->getOperand(i);
1008 if (!MO.isReg()) continue;
1009 unsigned Reg = MO.getReg();
1010 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
1011 // Look for physreg defs and tied uses.
1012 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
1013 markRegUsedInInstr(Reg);
1017 unsigned DefOpEnd = MI->getNumOperands();
1019 // Spill all virtregs before a call. This serves one purpose: If an
1020 // exception is thrown, the landing pad is going to expect to find
1021 // registers in their spill slots.
1022 // Note: although this is appealing to just consider all definitions
1023 // as call-clobbered, this is not correct because some of those
1024 // definitions may be used later on and we do not want to reuse
1025 // those for virtual registers in between.
1026 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1029 // The imp-defs are skipped below, but we still need to mark those
1030 // registers as used by the function.
1031 SkippedInstrs.insert(&MCID);
1035 // Allocate defs and collect dead defs.
1036 for (unsigned i = 0; i != DefOpEnd; ++i) {
1037 MachineOperand &MO = MI->getOperand(i);
1038 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1040 unsigned Reg = MO.getReg();
1042 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1043 if (!MRI->isAllocatable(Reg)) continue;
1044 definePhysReg(*MI, Reg, MO.isDead() ? regFree : regReserved);
1047 LiveRegMap::iterator LRI = defineVirtReg(*MI, i, Reg, CopySrc);
1048 unsigned PhysReg = LRI->PhysReg;
1049 if (setPhysReg(MI, i, PhysReg)) {
1050 VirtDead.push_back(Reg);
1051 CopyDst = 0; // cancel coalescing;
1053 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1056 // Kill dead defs after the scan to ensure that multiple defs of the same
1057 // register are allocated identically. We didn't need to do this for uses
1058 // because we are crerating our own kill flags, and they are always at the
1060 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1061 killVirtReg(VirtDead[i]);
1064 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1065 DEBUG(dbgs() << "-- coalescing: " << *MI);
1066 Coalesced.push_back(MI);
1068 DEBUG(dbgs() << "<< " << *MI);
1072 // Spill all physical registers holding virtual registers now.
1073 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1074 spillAll(MBB->getFirstTerminator());
1076 // Erase all the coalesced copies. We are delaying it until now because
1077 // LiveVirtRegs might refer to the instrs.
1078 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1079 MBB->erase(Coalesced[i]);
1080 NumCopies += Coalesced.size();
1085 /// runOnMachineFunction - Register allocate the whole function
1087 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1088 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1089 << "********** Function: " << Fn.getName() << '\n');
1091 MRI = &MF->getRegInfo();
1092 TRI = MF->getSubtarget().getRegisterInfo();
1093 TII = MF->getSubtarget().getInstrInfo();
1094 MRI->freezeReservedRegs(Fn);
1095 RegClassInfo.runOnMachineFunction(Fn);
1096 UsedInInstr.clear();
1097 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1099 // initialize the virtual->physical register map to have a 'null'
1100 // mapping for all virtual registers
1101 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1102 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1104 // Loop over all of the basic blocks, eliminating virtual register references
1105 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1106 MBBi != MBBe; ++MBBi) {
1108 AllocateBasicBlock();
1111 // All machine operands and other references to virtual registers have been
1112 // replaced. Remove the virtual registers.
1113 MRI->clearVirtRegs();
1115 SkippedInstrs.clear();
1116 StackSlotForVirtReg.clear();
1117 LiveDbgValueMap.clear();
1121 FunctionPass *llvm::createFastRegisterAllocator() {
1122 return new RAFast();