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/CodeGen/Passes.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/IndexedMap.h"
18 #include "llvm/ADT/STLExtras.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/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/RegisterClassInfo.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
40 #define DEBUG_TYPE "regalloc"
42 STATISTIC(NumStores, "Number of stores added");
43 STATISTIC(NumLoads , "Number of loads added");
44 STATISTIC(NumCopies, "Number of copies coalesced");
46 static RegisterRegAlloc
47 fastRegAlloc("fast", "fast register allocator", createFastRegisterAllocator);
50 class RAFast : public MachineFunctionPass {
53 RAFast() : MachineFunctionPass(ID), StackSlotForVirtReg(-1),
54 isBulkSpilling(false) {}
56 const TargetMachine *TM;
58 MachineRegisterInfo *MRI;
59 const TargetRegisterInfo *TRI;
60 const TargetInstrInfo *TII;
61 RegisterClassInfo RegClassInfo;
63 // Basic block currently being allocated.
64 MachineBasicBlock *MBB;
66 // StackSlotForVirtReg - Maps virtual regs to the frame index where these
67 // values are spilled.
68 IndexedMap<int, VirtReg2IndexFunctor> StackSlotForVirtReg;
70 // Everything we know about a live virtual register.
72 MachineInstr *LastUse; // Last instr to use reg.
73 unsigned VirtReg; // Virtual register number.
74 unsigned PhysReg; // Currently held here.
75 unsigned short LastOpNum; // OpNum on LastUse.
76 bool Dirty; // Register needs spill.
78 explicit LiveReg(unsigned v)
79 : LastUse(nullptr), VirtReg(v), PhysReg(0), LastOpNum(0), Dirty(false){}
81 unsigned getSparseSetIndex() const {
82 return TargetRegisterInfo::virtReg2Index(VirtReg);
86 typedef SparseSet<LiveReg> LiveRegMap;
88 // LiveVirtRegs - This map contains entries for each virtual register
89 // that is currently available in a physical register.
90 LiveRegMap LiveVirtRegs;
92 DenseMap<unsigned, SmallVector<MachineInstr *, 4> > LiveDbgValueMap;
94 // RegState - Track the state of a physical register.
96 // A disabled register is not available for allocation, but an alias may
97 // be in use. A register can only be moved out of the disabled state if
98 // all aliases are disabled.
101 // A free register is not currently in use and can be allocated
102 // immediately without checking aliases.
105 // A reserved register has been assigned explicitly (e.g., setting up a
106 // call parameter), and it remains reserved until it is used.
109 // A register state may also be a virtual register number, indication that
110 // the physical register is currently allocated to a virtual register. In
111 // that case, LiveVirtRegs contains the inverse mapping.
114 // PhysRegState - One of the RegState enums, or a virtreg.
115 std::vector<unsigned> PhysRegState;
117 // Set of register units.
118 typedef SparseSet<unsigned> UsedInInstrSet;
120 // Set of register units that are used in the current instruction, and so
121 // cannot be allocated.
122 UsedInInstrSet UsedInInstr;
124 // Mark a physreg as used in this instruction.
125 void markRegUsedInInstr(unsigned PhysReg) {
126 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
127 UsedInInstr.insert(*Units);
130 // Check if a physreg or any of its aliases are used in this instruction.
131 bool isRegUsedInInstr(unsigned PhysReg) const {
132 for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
133 if (UsedInInstr.count(*Units))
138 // SkippedInstrs - Descriptors of instructions whose clobber list was
139 // ignored because all registers were spilled. It is still necessary to
140 // mark all the clobbered registers as used by the function.
141 SmallPtrSet<const MCInstrDesc*, 4> SkippedInstrs;
143 // isBulkSpilling - This flag is set when LiveRegMap will be cleared
144 // completely after spilling all live registers. LiveRegMap entries should
151 spillImpossible = ~0u
154 const char *getPassName() const override {
155 return "Fast Register Allocator";
158 void getAnalysisUsage(AnalysisUsage &AU) const override {
159 AU.setPreservesCFG();
160 MachineFunctionPass::getAnalysisUsage(AU);
164 bool runOnMachineFunction(MachineFunction &Fn) override;
165 void AllocateBasicBlock();
166 void handleThroughOperands(MachineInstr *MI,
167 SmallVectorImpl<unsigned> &VirtDead);
168 int getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC);
169 bool isLastUseOfLocalReg(MachineOperand&);
171 void addKillFlag(const LiveReg&);
172 void killVirtReg(LiveRegMap::iterator);
173 void killVirtReg(unsigned VirtReg);
174 void spillVirtReg(MachineBasicBlock::iterator MI, LiveRegMap::iterator);
175 void spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg);
177 void usePhysReg(MachineOperand&);
178 void definePhysReg(MachineInstr *MI, unsigned PhysReg, RegState NewState);
179 unsigned calcSpillCost(unsigned PhysReg) const;
180 void assignVirtToPhysReg(LiveReg&, unsigned PhysReg);
181 LiveRegMap::iterator findLiveVirtReg(unsigned VirtReg) {
182 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
184 LiveRegMap::const_iterator findLiveVirtReg(unsigned VirtReg) const {
185 return LiveVirtRegs.find(TargetRegisterInfo::virtReg2Index(VirtReg));
187 LiveRegMap::iterator assignVirtToPhysReg(unsigned VReg, unsigned PhysReg);
188 LiveRegMap::iterator allocVirtReg(MachineInstr *MI, LiveRegMap::iterator,
190 LiveRegMap::iterator defineVirtReg(MachineInstr *MI, unsigned OpNum,
191 unsigned VirtReg, unsigned Hint);
192 LiveRegMap::iterator reloadVirtReg(MachineInstr *MI, unsigned OpNum,
193 unsigned VirtReg, unsigned Hint);
194 void spillAll(MachineBasicBlock::iterator MI);
195 bool setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg);
200 /// getStackSpaceFor - This allocates space for the specified virtual register
201 /// to be held on the stack.
202 int RAFast::getStackSpaceFor(unsigned VirtReg, const TargetRegisterClass *RC) {
203 // Find the location Reg would belong...
204 int SS = StackSlotForVirtReg[VirtReg];
206 return SS; // Already has space allocated?
208 // Allocate a new stack object for this spill location...
209 int FrameIdx = MF->getFrameInfo()->CreateSpillStackObject(RC->getSize(),
213 StackSlotForVirtReg[VirtReg] = FrameIdx;
217 /// isLastUseOfLocalReg - Return true if MO is the only remaining reference to
218 /// its virtual register, and it is guaranteed to be a block-local register.
220 bool RAFast::isLastUseOfLocalReg(MachineOperand &MO) {
221 // If the register has ever been spilled or reloaded, we conservatively assume
222 // it is a global register used in multiple blocks.
223 if (StackSlotForVirtReg[MO.getReg()] != -1)
226 // Check that the use/def chain has exactly one operand - MO.
227 MachineRegisterInfo::reg_nodbg_iterator I = MRI->reg_nodbg_begin(MO.getReg());
230 return ++I == MRI->reg_nodbg_end();
233 /// addKillFlag - Set kill flags on last use of a virtual register.
234 void RAFast::addKillFlag(const LiveReg &LR) {
235 if (!LR.LastUse) return;
236 MachineOperand &MO = LR.LastUse->getOperand(LR.LastOpNum);
237 if (MO.isUse() && !LR.LastUse->isRegTiedToDefOperand(LR.LastOpNum)) {
238 if (MO.getReg() == LR.PhysReg)
241 LR.LastUse->addRegisterKilled(LR.PhysReg, TRI, true);
245 /// killVirtReg - Mark virtreg as no longer available.
246 void RAFast::killVirtReg(LiveRegMap::iterator LRI) {
248 assert(PhysRegState[LRI->PhysReg] == LRI->VirtReg &&
249 "Broken RegState mapping");
250 PhysRegState[LRI->PhysReg] = regFree;
251 // Erase from LiveVirtRegs unless we're spilling in bulk.
253 LiveVirtRegs.erase(LRI);
256 /// killVirtReg - Mark virtreg as no longer available.
257 void RAFast::killVirtReg(unsigned VirtReg) {
258 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
259 "killVirtReg needs a virtual register");
260 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
261 if (LRI != LiveVirtRegs.end())
265 /// spillVirtReg - This method spills the value specified by VirtReg into the
266 /// corresponding stack slot if needed.
267 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI, unsigned VirtReg) {
268 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
269 "Spilling a physical register is illegal!");
270 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
271 assert(LRI != LiveVirtRegs.end() && "Spilling unmapped virtual register");
272 spillVirtReg(MI, LRI);
275 /// spillVirtReg - Do the actual work of spilling.
276 void RAFast::spillVirtReg(MachineBasicBlock::iterator MI,
277 LiveRegMap::iterator LRI) {
279 assert(PhysRegState[LR.PhysReg] == LRI->VirtReg && "Broken RegState mapping");
282 // If this physreg is used by the instruction, we want to kill it on the
283 // instruction, not on the spill.
284 bool SpillKill = LR.LastUse != MI;
286 DEBUG(dbgs() << "Spilling " << PrintReg(LRI->VirtReg, TRI)
287 << " in " << PrintReg(LR.PhysReg, TRI));
288 const TargetRegisterClass *RC = MRI->getRegClass(LRI->VirtReg);
289 int FI = getStackSpaceFor(LRI->VirtReg, RC);
290 DEBUG(dbgs() << " to stack slot #" << FI << "\n");
291 TII->storeRegToStackSlot(*MBB, MI, LR.PhysReg, SpillKill, FI, RC, TRI);
292 ++NumStores; // Update statistics
294 // If this register is used by DBG_VALUE then insert new DBG_VALUE to
295 // identify spilled location as the place to find corresponding variable's
297 SmallVectorImpl<MachineInstr *> &LRIDbgValues =
298 LiveDbgValueMap[LRI->VirtReg];
299 for (unsigned li = 0, le = LRIDbgValues.size(); li != le; ++li) {
300 MachineInstr *DBG = LRIDbgValues[li];
301 const MDNode *MDPtr = DBG->getOperand(2).getMetadata();
302 bool IsIndirect = DBG->isIndirectDebugValue();
303 uint64_t Offset = IsIndirect ? DBG->getOperand(1).getImm() : 0;
305 if (MI == MBB->end()) {
306 // If MI is at basic block end then use last instruction's location.
307 MachineBasicBlock::iterator EI = MI;
308 DL = (--EI)->getDebugLoc();
310 DL = MI->getDebugLoc();
311 MachineBasicBlock *MBB = DBG->getParent();
312 MachineInstr *NewDV =
313 BuildMI(*MBB, MI, DL, TII->get(TargetOpcode::DBG_VALUE))
314 .addFrameIndex(FI).addImm(Offset).addMetadata(MDPtr);
316 DEBUG(dbgs() << "Inserting debug info due to spill:" << "\n" << *NewDV);
318 // Now this register is spilled there is should not be any DBG_VALUE
319 // pointing to this register because they are all pointing to spilled value
321 LRIDbgValues.clear();
323 LR.LastUse = nullptr; // Don't kill register again
328 /// spillAll - Spill all dirty virtregs without killing them.
329 void RAFast::spillAll(MachineBasicBlock::iterator MI) {
330 if (LiveVirtRegs.empty()) return;
331 isBulkSpilling = true;
332 // The LiveRegMap is keyed by an unsigned (the virtreg number), so the order
333 // of spilling here is deterministic, if arbitrary.
334 for (LiveRegMap::iterator i = LiveVirtRegs.begin(), e = LiveVirtRegs.end();
337 LiveVirtRegs.clear();
338 isBulkSpilling = false;
341 /// usePhysReg - Handle the direct use of a physical register.
342 /// Check that the register is not used by a virtreg.
343 /// Kill the physreg, marking it free.
344 /// This may add implicit kills to MO->getParent() and invalidate MO.
345 void RAFast::usePhysReg(MachineOperand &MO) {
346 unsigned PhysReg = MO.getReg();
347 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) &&
348 "Bad usePhysReg operand");
349 markRegUsedInInstr(PhysReg);
350 switch (PhysRegState[PhysReg]) {
354 PhysRegState[PhysReg] = regFree;
360 // The physreg was allocated to a virtual register. That means the value we
361 // wanted has been clobbered.
362 llvm_unreachable("Instruction uses an allocated register");
365 // Maybe a superregister is reserved?
366 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
367 unsigned Alias = *AI;
368 switch (PhysRegState[Alias]) {
372 assert(TRI->isSuperRegister(PhysReg, Alias) &&
373 "Instruction is not using a subregister of a reserved register");
374 // Leave the superregister in the working set.
375 PhysRegState[Alias] = regFree;
376 MO.getParent()->addRegisterKilled(Alias, TRI, true);
379 if (TRI->isSuperRegister(PhysReg, Alias)) {
380 // Leave the superregister in the working set.
381 MO.getParent()->addRegisterKilled(Alias, TRI, true);
384 // Some other alias was in the working set - clear it.
385 PhysRegState[Alias] = regDisabled;
388 llvm_unreachable("Instruction uses an alias of an allocated register");
392 // All aliases are disabled, bring register into working set.
393 PhysRegState[PhysReg] = regFree;
397 /// definePhysReg - Mark PhysReg as reserved or free after spilling any
398 /// virtregs. This is very similar to defineVirtReg except the physreg is
399 /// reserved instead of allocated.
400 void RAFast::definePhysReg(MachineInstr *MI, unsigned PhysReg,
402 markRegUsedInInstr(PhysReg);
403 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
407 spillVirtReg(MI, VirtReg);
411 PhysRegState[PhysReg] = NewState;
415 // This is a disabled register, disable all aliases.
416 PhysRegState[PhysReg] = NewState;
417 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
418 unsigned Alias = *AI;
419 switch (unsigned VirtReg = PhysRegState[Alias]) {
423 spillVirtReg(MI, VirtReg);
427 PhysRegState[Alias] = regDisabled;
428 if (TRI->isSuperRegister(PhysReg, Alias))
436 // calcSpillCost - Return the cost of spilling clearing out PhysReg and
437 // aliases so it is free for allocation.
438 // Returns 0 when PhysReg is free or disabled with all aliases disabled - it
439 // can be allocated directly.
440 // Returns spillImpossible when PhysReg or an alias can't be spilled.
441 unsigned RAFast::calcSpillCost(unsigned PhysReg) const {
442 if (isRegUsedInInstr(PhysReg)) {
443 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is already used in instr.\n");
444 return spillImpossible;
446 switch (unsigned VirtReg = PhysRegState[PhysReg]) {
452 DEBUG(dbgs() << PrintReg(VirtReg, TRI) << " corresponding "
453 << PrintReg(PhysReg, TRI) << " is reserved already.\n");
454 return spillImpossible;
456 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
457 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
458 return I->Dirty ? spillDirty : spillClean;
462 // This is a disabled register, add up cost of aliases.
463 DEBUG(dbgs() << PrintReg(PhysReg, TRI) << " is disabled.\n");
465 for (MCRegAliasIterator AI(PhysReg, TRI, false); AI.isValid(); ++AI) {
466 unsigned Alias = *AI;
467 switch (unsigned VirtReg = PhysRegState[Alias]) {
474 return spillImpossible;
476 LiveRegMap::const_iterator I = findLiveVirtReg(VirtReg);
477 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
478 Cost += I->Dirty ? spillDirty : spillClean;
487 /// assignVirtToPhysReg - This method updates local state so that we know
488 /// that PhysReg is the proper container for VirtReg now. The physical
489 /// register must not be used for anything else when this is called.
491 void RAFast::assignVirtToPhysReg(LiveReg &LR, unsigned PhysReg) {
492 DEBUG(dbgs() << "Assigning " << PrintReg(LR.VirtReg, TRI) << " to "
493 << PrintReg(PhysReg, TRI) << "\n");
494 PhysRegState[PhysReg] = LR.VirtReg;
495 assert(!LR.PhysReg && "Already assigned a physreg");
496 LR.PhysReg = PhysReg;
499 RAFast::LiveRegMap::iterator
500 RAFast::assignVirtToPhysReg(unsigned VirtReg, unsigned PhysReg) {
501 LiveRegMap::iterator LRI = findLiveVirtReg(VirtReg);
502 assert(LRI != LiveVirtRegs.end() && "VirtReg disappeared");
503 assignVirtToPhysReg(*LRI, PhysReg);
507 /// allocVirtReg - Allocate a physical register for VirtReg.
508 RAFast::LiveRegMap::iterator RAFast::allocVirtReg(MachineInstr *MI,
509 LiveRegMap::iterator LRI,
511 const unsigned VirtReg = LRI->VirtReg;
513 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
514 "Can only allocate virtual registers");
516 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
518 // Ignore invalid hints.
519 if (Hint && (!TargetRegisterInfo::isPhysicalRegister(Hint) ||
520 !RC->contains(Hint) || !MRI->isAllocatable(Hint)))
523 // Take hint when possible.
525 // Ignore the hint if we would have to spill a dirty register.
526 unsigned Cost = calcSpillCost(Hint);
527 if (Cost < spillDirty) {
529 definePhysReg(MI, Hint, regFree);
530 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
531 // That invalidates LRI, so run a new lookup for VirtReg.
532 return assignVirtToPhysReg(VirtReg, Hint);
536 ArrayRef<MCPhysReg> AO = RegClassInfo.getOrder(RC);
538 // First try to find a completely free register.
539 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
540 unsigned PhysReg = *I;
541 if (PhysRegState[PhysReg] == regFree && !isRegUsedInInstr(PhysReg)) {
542 assignVirtToPhysReg(*LRI, PhysReg);
547 DEBUG(dbgs() << "Allocating " << PrintReg(VirtReg) << " from "
548 << RC->getName() << "\n");
550 unsigned BestReg = 0, BestCost = spillImpossible;
551 for (ArrayRef<MCPhysReg>::iterator I = AO.begin(), E = AO.end(); I != E; ++I){
552 unsigned Cost = calcSpillCost(*I);
553 DEBUG(dbgs() << "\tRegister: " << PrintReg(*I, TRI) << "\n");
554 DEBUG(dbgs() << "\tCost: " << Cost << "\n");
555 DEBUG(dbgs() << "\tBestCost: " << BestCost << "\n");
556 // Cost is 0 when all aliases are already disabled.
558 assignVirtToPhysReg(*LRI, *I);
562 BestReg = *I, BestCost = Cost;
566 definePhysReg(MI, BestReg, regFree);
567 // definePhysReg may kill virtual registers and modify LiveVirtRegs.
568 // That invalidates LRI, so run a new lookup for VirtReg.
569 return assignVirtToPhysReg(VirtReg, BestReg);
572 // Nothing we can do. Report an error and keep going with a bad allocation.
573 if (MI->isInlineAsm())
574 MI->emitError("inline assembly requires more registers than available");
576 MI->emitError("ran out of registers during register allocation");
577 definePhysReg(MI, *AO.begin(), regFree);
578 return assignVirtToPhysReg(VirtReg, *AO.begin());
581 /// defineVirtReg - Allocate a register for VirtReg and mark it as dirty.
582 RAFast::LiveRegMap::iterator
583 RAFast::defineVirtReg(MachineInstr *MI, unsigned OpNum,
584 unsigned VirtReg, unsigned Hint) {
585 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
586 "Not a virtual register");
587 LiveRegMap::iterator LRI;
589 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
591 // If there is no hint, peek at the only use of this register.
592 if ((!Hint || !TargetRegisterInfo::isPhysicalRegister(Hint)) &&
593 MRI->hasOneNonDBGUse(VirtReg)) {
594 const MachineInstr &UseMI = *MRI->use_instr_nodbg_begin(VirtReg);
595 // It's a copy, use the destination register as a hint.
596 if (UseMI.isCopyLike())
597 Hint = UseMI.getOperand(0).getReg();
599 LRI = allocVirtReg(MI, LRI, Hint);
600 } else if (LRI->LastUse) {
601 // Redefining a live register - kill at the last use, unless it is this
602 // instruction defining VirtReg multiple times.
603 if (LRI->LastUse != MI || LRI->LastUse->getOperand(LRI->LastOpNum).isUse())
606 assert(LRI->PhysReg && "Register not assigned");
608 LRI->LastOpNum = OpNum;
610 markRegUsedInInstr(LRI->PhysReg);
614 /// reloadVirtReg - Make sure VirtReg is available in a physreg and return it.
615 RAFast::LiveRegMap::iterator
616 RAFast::reloadVirtReg(MachineInstr *MI, unsigned OpNum,
617 unsigned VirtReg, unsigned Hint) {
618 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
619 "Not a virtual register");
620 LiveRegMap::iterator LRI;
622 std::tie(LRI, New) = LiveVirtRegs.insert(LiveReg(VirtReg));
623 MachineOperand &MO = MI->getOperand(OpNum);
625 LRI = allocVirtReg(MI, LRI, Hint);
626 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
627 int FrameIndex = getStackSpaceFor(VirtReg, RC);
628 DEBUG(dbgs() << "Reloading " << PrintReg(VirtReg, TRI) << " into "
629 << PrintReg(LRI->PhysReg, TRI) << "\n");
630 TII->loadRegFromStackSlot(*MBB, MI, LRI->PhysReg, FrameIndex, RC, TRI);
632 } else if (LRI->Dirty) {
633 if (isLastUseOfLocalReg(MO)) {
634 DEBUG(dbgs() << "Killing last use: " << MO << "\n");
639 } else if (MO.isKill()) {
640 DEBUG(dbgs() << "Clearing dubious kill: " << MO << "\n");
642 } else if (MO.isDead()) {
643 DEBUG(dbgs() << "Clearing dubious dead: " << MO << "\n");
646 } else if (MO.isKill()) {
647 // We must remove kill flags from uses of reloaded registers because the
648 // register would be killed immediately, and there might be a second use:
649 // %foo = OR %x<kill>, %x
650 // This would cause a second reload of %x into a different register.
651 DEBUG(dbgs() << "Clearing clean kill: " << MO << "\n");
653 } else if (MO.isDead()) {
654 DEBUG(dbgs() << "Clearing clean dead: " << MO << "\n");
657 assert(LRI->PhysReg && "Register not assigned");
659 LRI->LastOpNum = OpNum;
660 markRegUsedInInstr(LRI->PhysReg);
664 // setPhysReg - Change operand OpNum in MI the refer the PhysReg, considering
665 // subregs. This may invalidate any operand pointers.
666 // Return true if the operand kills its register.
667 bool RAFast::setPhysReg(MachineInstr *MI, unsigned OpNum, unsigned PhysReg) {
668 MachineOperand &MO = MI->getOperand(OpNum);
669 bool Dead = MO.isDead();
670 if (!MO.getSubReg()) {
672 return MO.isKill() || Dead;
675 // Handle subregister index.
676 MO.setReg(PhysReg ? TRI->getSubReg(PhysReg, MO.getSubReg()) : 0);
679 // A kill flag implies killing the full register. Add corresponding super
682 MI->addRegisterKilled(PhysReg, TRI, true);
686 // A <def,read-undef> of a sub-register requires an implicit def of the full
688 if (MO.isDef() && MO.isUndef())
689 MI->addRegisterDefined(PhysReg, TRI);
694 // Handle special instruction operand like early clobbers and tied ops when
695 // there are additional physreg defines.
696 void RAFast::handleThroughOperands(MachineInstr *MI,
697 SmallVectorImpl<unsigned> &VirtDead) {
698 DEBUG(dbgs() << "Scanning for through registers:");
699 SmallSet<unsigned, 8> ThroughRegs;
700 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
701 MachineOperand &MO = MI->getOperand(i);
702 if (!MO.isReg()) continue;
703 unsigned Reg = MO.getReg();
704 if (!TargetRegisterInfo::isVirtualRegister(Reg))
706 if (MO.isEarlyClobber() || MI->isRegTiedToDefOperand(i) ||
707 (MO.getSubReg() && MI->readsVirtualRegister(Reg))) {
708 if (ThroughRegs.insert(Reg))
709 DEBUG(dbgs() << ' ' << PrintReg(Reg));
713 // If any physreg defines collide with preallocated through registers,
714 // we must spill and reallocate.
715 DEBUG(dbgs() << "\nChecking for physdef collisions.\n");
716 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
717 MachineOperand &MO = MI->getOperand(i);
718 if (!MO.isReg() || !MO.isDef()) continue;
719 unsigned Reg = MO.getReg();
720 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
721 markRegUsedInInstr(Reg);
722 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
723 if (ThroughRegs.count(PhysRegState[*AI]))
724 definePhysReg(MI, *AI, regFree);
728 SmallVector<unsigned, 8> PartialDefs;
729 DEBUG(dbgs() << "Allocating tied uses.\n");
730 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
731 MachineOperand &MO = MI->getOperand(i);
732 if (!MO.isReg()) continue;
733 unsigned Reg = MO.getReg();
734 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
737 if (!MI->isRegTiedToDefOperand(i, &DefIdx)) continue;
738 DEBUG(dbgs() << "Operand " << i << "("<< MO << ") is tied to operand "
740 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
741 unsigned PhysReg = LRI->PhysReg;
742 setPhysReg(MI, i, PhysReg);
743 // Note: we don't update the def operand yet. That would cause the normal
744 // def-scan to attempt spilling.
745 } else if (MO.getSubReg() && MI->readsVirtualRegister(Reg)) {
746 DEBUG(dbgs() << "Partial redefine: " << MO << "\n");
747 // Reload the register, but don't assign to the operand just yet.
748 // That would confuse the later phys-def processing pass.
749 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, 0);
750 PartialDefs.push_back(LRI->PhysReg);
754 DEBUG(dbgs() << "Allocating early clobbers.\n");
755 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
756 MachineOperand &MO = MI->getOperand(i);
757 if (!MO.isReg()) continue;
758 unsigned Reg = MO.getReg();
759 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
760 if (!MO.isEarlyClobber())
762 // Note: defineVirtReg may invalidate MO.
763 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, 0);
764 unsigned PhysReg = LRI->PhysReg;
765 if (setPhysReg(MI, i, PhysReg))
766 VirtDead.push_back(Reg);
769 // Restore UsedInInstr to a state usable for allocating normal virtual uses.
771 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
772 MachineOperand &MO = MI->getOperand(i);
773 if (!MO.isReg() || (MO.isDef() && !MO.isEarlyClobber())) continue;
774 unsigned Reg = MO.getReg();
775 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
776 DEBUG(dbgs() << "\tSetting " << PrintReg(Reg, TRI)
777 << " as used in instr\n");
778 markRegUsedInInstr(Reg);
781 // Also mark PartialDefs as used to avoid reallocation.
782 for (unsigned i = 0, e = PartialDefs.size(); i != e; ++i)
783 markRegUsedInInstr(PartialDefs[i]);
786 void RAFast::AllocateBasicBlock() {
787 DEBUG(dbgs() << "\nAllocating " << *MBB);
789 PhysRegState.assign(TRI->getNumRegs(), regDisabled);
790 assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
792 MachineBasicBlock::iterator MII = MBB->begin();
794 // Add live-in registers as live.
795 for (MachineBasicBlock::livein_iterator I = MBB->livein_begin(),
796 E = MBB->livein_end(); I != E; ++I)
797 if (MRI->isAllocatable(*I))
798 definePhysReg(MII, *I, regReserved);
800 SmallVector<unsigned, 8> VirtDead;
801 SmallVector<MachineInstr*, 32> Coalesced;
803 // Otherwise, sequentially allocate each instruction in the MBB.
804 while (MII != MBB->end()) {
805 MachineInstr *MI = MII++;
806 const MCInstrDesc &MCID = MI->getDesc();
808 dbgs() << "\n>> " << *MI << "Regs:";
809 for (unsigned Reg = 1, E = TRI->getNumRegs(); Reg != E; ++Reg) {
810 if (PhysRegState[Reg] == regDisabled) continue;
811 dbgs() << " " << TRI->getName(Reg);
812 switch(PhysRegState[Reg]) {
819 dbgs() << '=' << PrintReg(PhysRegState[Reg]);
820 LiveRegMap::iterator I = findLiveVirtReg(PhysRegState[Reg]);
821 assert(I != LiveVirtRegs.end() && "Missing VirtReg entry");
824 assert(I->PhysReg == Reg && "Bad inverse map");
830 // Check that LiveVirtRegs is the inverse.
831 for (LiveRegMap::iterator i = LiveVirtRegs.begin(),
832 e = LiveVirtRegs.end(); i != e; ++i) {
833 assert(TargetRegisterInfo::isVirtualRegister(i->VirtReg) &&
835 assert(TargetRegisterInfo::isPhysicalRegister(i->PhysReg) &&
837 assert(PhysRegState[i->PhysReg] == i->VirtReg && "Bad inverse map");
841 // Debug values are not allowed to change codegen in any way.
842 if (MI->isDebugValue()) {
843 bool ScanDbgValue = true;
844 while (ScanDbgValue) {
845 ScanDbgValue = false;
846 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
847 MachineOperand &MO = MI->getOperand(i);
848 if (!MO.isReg()) continue;
849 unsigned Reg = MO.getReg();
850 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
851 LiveRegMap::iterator LRI = findLiveVirtReg(Reg);
852 if (LRI != LiveVirtRegs.end())
853 setPhysReg(MI, i, LRI->PhysReg);
855 int SS = StackSlotForVirtReg[Reg];
857 // We can't allocate a physreg for a DebugValue, sorry!
858 DEBUG(dbgs() << "Unable to allocate vreg used by DBG_VALUE");
862 // Modify DBG_VALUE now that the value is in a spill slot.
863 bool IsIndirect = MI->isIndirectDebugValue();
864 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
865 const MDNode *MDPtr =
866 MI->getOperand(MI->getNumOperands()-1).getMetadata();
867 DebugLoc DL = MI->getDebugLoc();
868 MachineBasicBlock *MBB = MI->getParent();
869 MachineInstr *NewDV = BuildMI(*MBB, MBB->erase(MI), DL,
870 TII->get(TargetOpcode::DBG_VALUE))
871 .addFrameIndex(SS).addImm(Offset).addMetadata(MDPtr);
872 DEBUG(dbgs() << "Modifying debug info due to spill:"
874 // Scan NewDV operands from the beginning.
880 LiveDbgValueMap[Reg].push_back(MI);
887 // If this is a copy, we may be able to coalesce.
888 unsigned CopySrc = 0, CopyDst = 0, CopySrcSub = 0, CopyDstSub = 0;
890 CopyDst = MI->getOperand(0).getReg();
891 CopySrc = MI->getOperand(1).getReg();
892 CopyDstSub = MI->getOperand(0).getSubReg();
893 CopySrcSub = MI->getOperand(1).getSubReg();
896 // Track registers used by instruction.
900 // Mark physreg uses and early clobbers as used.
901 // Find the end of the virtreg operands
902 unsigned VirtOpEnd = 0;
903 bool hasTiedOps = false;
904 bool hasEarlyClobbers = false;
905 bool hasPartialRedefs = false;
906 bool hasPhysDefs = false;
907 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
908 MachineOperand &MO = MI->getOperand(i);
909 // Make sure MRI knows about registers clobbered by regmasks.
910 if (MO.isRegMask()) {
911 MRI->addPhysRegsUsedFromRegMask(MO.getRegMask());
914 if (!MO.isReg()) continue;
915 unsigned Reg = MO.getReg();
917 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
920 hasTiedOps = hasTiedOps ||
921 MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1;
923 if (MO.isEarlyClobber())
924 hasEarlyClobbers = true;
925 if (MO.getSubReg() && MI->readsVirtualRegister(Reg))
926 hasPartialRedefs = true;
930 if (!MRI->isAllocatable(Reg)) continue;
933 } else if (MO.isEarlyClobber()) {
934 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
935 regFree : regReserved);
936 hasEarlyClobbers = true;
941 // The instruction may have virtual register operands that must be allocated
942 // the same register at use-time and def-time: early clobbers and tied
943 // operands. If there are also physical defs, these registers must avoid
944 // both physical defs and uses, making them more constrained than normal
946 // Similarly, if there are multiple defs and tied operands, we must make
947 // sure the same register is allocated to uses and defs.
948 // We didn't detect inline asm tied operands above, so just make this extra
949 // pass for all inline asm.
950 if (MI->isInlineAsm() || hasEarlyClobbers || hasPartialRedefs ||
951 (hasTiedOps && (hasPhysDefs || MCID.getNumDefs() > 1))) {
952 handleThroughOperands(MI, VirtDead);
953 // Don't attempt coalescing when we have funny stuff going on.
955 // Pretend we have early clobbers so the use operands get marked below.
956 // This is not necessary for the common case of a single tied use.
957 hasEarlyClobbers = true;
961 // Allocate virtreg uses.
962 for (unsigned i = 0; i != VirtOpEnd; ++i) {
963 MachineOperand &MO = MI->getOperand(i);
964 if (!MO.isReg()) continue;
965 unsigned Reg = MO.getReg();
966 if (!TargetRegisterInfo::isVirtualRegister(Reg)) continue;
968 LiveRegMap::iterator LRI = reloadVirtReg(MI, i, Reg, CopyDst);
969 unsigned PhysReg = LRI->PhysReg;
970 CopySrc = (CopySrc == Reg || CopySrc == PhysReg) ? PhysReg : 0;
971 if (setPhysReg(MI, i, PhysReg))
976 for (UsedInInstrSet::iterator
977 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
978 MRI->setRegUnitUsed(*I);
980 // Track registers defined by instruction - early clobbers and tied uses at
983 if (hasEarlyClobbers) {
984 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
985 MachineOperand &MO = MI->getOperand(i);
986 if (!MO.isReg()) continue;
987 unsigned Reg = MO.getReg();
988 if (!Reg || !TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
989 // Look for physreg defs and tied uses.
990 if (!MO.isDef() && !MI->isRegTiedToDefOperand(i)) continue;
991 markRegUsedInInstr(Reg);
995 unsigned DefOpEnd = MI->getNumOperands();
997 // Spill all virtregs before a call. This serves two purposes: 1. If an
998 // exception is thrown, the landing pad is going to expect to find
999 // registers in their spill slots, and 2. we don't have to wade through
1000 // all the <imp-def> operands on the call instruction.
1001 DefOpEnd = VirtOpEnd;
1002 DEBUG(dbgs() << " Spilling remaining registers before call.\n");
1005 // The imp-defs are skipped below, but we still need to mark those
1006 // registers as used by the function.
1007 SkippedInstrs.insert(&MCID);
1011 // Allocate defs and collect dead defs.
1012 for (unsigned i = 0; i != DefOpEnd; ++i) {
1013 MachineOperand &MO = MI->getOperand(i);
1014 if (!MO.isReg() || !MO.isDef() || !MO.getReg() || MO.isEarlyClobber())
1016 unsigned Reg = MO.getReg();
1018 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1019 if (!MRI->isAllocatable(Reg)) continue;
1020 definePhysReg(MI, Reg, (MO.isImplicit() || MO.isDead()) ?
1021 regFree : regReserved);
1024 LiveRegMap::iterator LRI = defineVirtReg(MI, i, Reg, CopySrc);
1025 unsigned PhysReg = LRI->PhysReg;
1026 if (setPhysReg(MI, i, PhysReg)) {
1027 VirtDead.push_back(Reg);
1028 CopyDst = 0; // cancel coalescing;
1030 CopyDst = (CopyDst == Reg || CopyDst == PhysReg) ? PhysReg : 0;
1033 // Kill dead defs after the scan to ensure that multiple defs of the same
1034 // register are allocated identically. We didn't need to do this for uses
1035 // because we are crerating our own kill flags, and they are always at the
1037 for (unsigned i = 0, e = VirtDead.size(); i != e; ++i)
1038 killVirtReg(VirtDead[i]);
1041 for (UsedInInstrSet::iterator
1042 I = UsedInInstr.begin(), E = UsedInInstr.end(); I != E; ++I)
1043 MRI->setRegUnitUsed(*I);
1045 if (CopyDst && CopyDst == CopySrc && CopyDstSub == CopySrcSub) {
1046 DEBUG(dbgs() << "-- coalescing: " << *MI);
1047 Coalesced.push_back(MI);
1049 DEBUG(dbgs() << "<< " << *MI);
1053 // Spill all physical registers holding virtual registers now.
1054 DEBUG(dbgs() << "Spilling live registers at end of block.\n");
1055 spillAll(MBB->getFirstTerminator());
1057 // Erase all the coalesced copies. We are delaying it until now because
1058 // LiveVirtRegs might refer to the instrs.
1059 for (unsigned i = 0, e = Coalesced.size(); i != e; ++i)
1060 MBB->erase(Coalesced[i]);
1061 NumCopies += Coalesced.size();
1066 /// runOnMachineFunction - Register allocate the whole function
1068 bool RAFast::runOnMachineFunction(MachineFunction &Fn) {
1069 DEBUG(dbgs() << "********** FAST REGISTER ALLOCATION **********\n"
1070 << "********** Function: " << Fn.getName() << '\n');
1072 MRI = &MF->getRegInfo();
1073 TM = &Fn.getTarget();
1074 TRI = TM->getRegisterInfo();
1075 TII = TM->getInstrInfo();
1076 MRI->freezeReservedRegs(Fn);
1077 RegClassInfo.runOnMachineFunction(Fn);
1078 UsedInInstr.clear();
1079 UsedInInstr.setUniverse(TRI->getNumRegUnits());
1081 assert(!MRI->isSSA() && "regalloc requires leaving SSA");
1083 // initialize the virtual->physical register map to have a 'null'
1084 // mapping for all virtual registers
1085 StackSlotForVirtReg.resize(MRI->getNumVirtRegs());
1086 LiveVirtRegs.setUniverse(MRI->getNumVirtRegs());
1088 // Loop over all of the basic blocks, eliminating virtual register references
1089 for (MachineFunction::iterator MBBi = Fn.begin(), MBBe = Fn.end();
1090 MBBi != MBBe; ++MBBi) {
1092 AllocateBasicBlock();
1095 // Add the clobber lists for all the instructions we skipped earlier.
1096 for (SmallPtrSet<const MCInstrDesc*, 4>::const_iterator
1097 I = SkippedInstrs.begin(), E = SkippedInstrs.end(); I != E; ++I)
1098 if (const uint16_t *Defs = (*I)->getImplicitDefs())
1100 MRI->setPhysRegUsed(*Defs++);
1102 // All machine operands and other references to virtual registers have been
1103 // replaced. Remove the virtual registers.
1104 MRI->clearVirtRegs();
1106 SkippedInstrs.clear();
1107 StackSlotForVirtReg.clear();
1108 LiveDbgValueMap.clear();
1112 FunctionPass *llvm::createFastRegisterAllocator() {
1113 return new RAFast();