1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the VirtRegMap class.
12 // It also contains implementations of the the Spiller interface, which, given a
13 // virtual register map and a machine function, eliminates all virtual
14 // references by replacing them with physical register references - adding spill
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "spiller"
20 #include "VirtRegMap.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/SSARegMap.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
34 Statistic<> NumSpills("spiller", "Number of register spills");
35 Statistic<> NumStores("spiller", "Number of stores added");
36 Statistic<> NumLoads ("spiller", "Number of loads added");
37 Statistic<> NumReused("spiller", "Number of values reused");
38 Statistic<> NumDSE ("spiller", "Number of dead stores elided");
40 enum SpillerName { simple, local };
44 cl::desc("Spiller to use: (default: local)"),
46 cl::values(clEnumVal(simple, " simple spiller"),
47 clEnumVal(local, " local spiller"),
52 //===----------------------------------------------------------------------===//
53 // VirtRegMap implementation
54 //===----------------------------------------------------------------------===//
56 void VirtRegMap::grow() {
57 Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
58 Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
61 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
62 assert(MRegisterInfo::isVirtualRegister(virtReg));
63 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
64 "attempt to assign stack slot to already spilled register");
65 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
66 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
68 Virt2StackSlotMap[virtReg] = frameIndex;
73 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
74 assert(MRegisterInfo::isVirtualRegister(virtReg));
75 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
76 "attempt to assign stack slot to already spilled register");
77 Virt2StackSlotMap[virtReg] = frameIndex;
80 void VirtRegMap::virtFolded(unsigned virtReg,
82 MachineInstr* newMI) {
83 // move previous memory references folded to new instruction
84 std::vector<MI2VirtMapTy::mapped_type> regs;
85 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(oldMI),
86 E = MI2VirtMap.end(); I != E && I->first == oldMI; ) {
87 regs.push_back(I->second);
88 MI2VirtMap.erase(I++);
91 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(newMI);
92 for (unsigned i = 0, e = regs.size(); i != e; ++i)
93 MI2VirtMap.insert(IP, std::make_pair(newMI, regs[i]));
95 // add new memory reference
96 MI2VirtMap.insert(IP, std::make_pair(newMI, virtReg));
99 void VirtRegMap::print(std::ostream &OS) const {
100 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
102 OS << "********** REGISTER MAP **********\n";
103 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
104 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
105 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
106 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
110 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
111 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
112 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
113 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
117 void VirtRegMap::dump() const { print(std::cerr); }
120 //===----------------------------------------------------------------------===//
121 // Simple Spiller Implementation
122 //===----------------------------------------------------------------------===//
124 Spiller::~Spiller() {}
127 struct SimpleSpiller : public Spiller {
128 bool runOnMachineFunction(MachineFunction& mf, const VirtRegMap &VRM);
132 bool SimpleSpiller::runOnMachineFunction(MachineFunction& MF,
133 const VirtRegMap& VRM) {
134 DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
135 DEBUG(std::cerr << "********** Function: "
136 << MF.getFunction()->getName() << '\n');
137 const TargetMachine& TM = MF.getTarget();
138 const MRegisterInfo& MRI = *TM.getRegisterInfo();
140 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
141 // each vreg once (in the case where a spilled vreg is used by multiple
142 // operands). This is always smaller than the number of operands to the
143 // current machine instr, so it should be small.
144 std::vector<unsigned> LoadedRegs;
146 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
148 DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
149 MachineBasicBlock &MBB = *MBBI;
150 for (MachineBasicBlock::iterator MII = MBB.begin(),
151 E = MBB.end(); MII != E; ++MII) {
152 MachineInstr &MI = *MII;
153 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
154 MachineOperand &MO = MI.getOperand(i);
155 if (MO.isRegister() && MO.getReg() &&
156 MRegisterInfo::isVirtualRegister(MO.getReg())) {
157 unsigned VirtReg = MO.getReg();
158 unsigned PhysReg = VRM.getPhys(VirtReg);
159 if (VRM.hasStackSlot(VirtReg)) {
160 int StackSlot = VRM.getStackSlot(VirtReg);
163 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
164 == LoadedRegs.end()) {
165 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot);
166 LoadedRegs.push_back(VirtReg);
168 DEBUG(std::cerr << '\t' << *prior(MII));
172 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot);
176 MI.SetMachineOperandReg(i, PhysReg);
179 DEBUG(std::cerr << '\t' << MI);
186 //===----------------------------------------------------------------------===//
187 // Local Spiller Implementation
188 //===----------------------------------------------------------------------===//
191 /// LocalSpiller - This spiller does a simple pass over the machine basic
192 /// block to attempt to keep spills in registers as much as possible for
193 /// blocks that have low register pressure (the vreg may be spilled due to
194 /// register pressure in other blocks).
195 class LocalSpiller : public Spiller {
196 const MRegisterInfo *MRI;
197 const TargetInstrInfo *TII;
199 bool runOnMachineFunction(MachineFunction &MF, const VirtRegMap &VRM) {
200 MRI = MF.getTarget().getRegisterInfo();
201 TII = MF.getTarget().getInstrInfo();
202 DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
203 << MF.getFunction()->getName() << "':\n");
205 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
207 RewriteMBB(*MBB, VRM);
211 void RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM);
212 void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
213 std::map<unsigned, int> &PhysRegs);
214 void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
215 std::map<unsigned, int> &PhysRegs);
219 void LocalSpiller::ClobberPhysRegOnly(unsigned PhysReg,
220 std::map<int, unsigned> &SpillSlots,
221 std::map<unsigned, int> &PhysRegs) {
222 std::map<unsigned, int>::iterator I = PhysRegs.find(PhysReg);
223 if (I != PhysRegs.end()) {
224 int Slot = I->second;
226 assert(SpillSlots[Slot] == PhysReg && "Bidirectional map mismatch!");
227 SpillSlots.erase(Slot);
228 DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
229 << " clobbered, invalidating SS#" << Slot << "\n");
234 void LocalSpiller::ClobberPhysReg(unsigned PhysReg,
235 std::map<int, unsigned> &SpillSlots,
236 std::map<unsigned, int> &PhysRegs) {
237 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
238 ClobberPhysRegOnly(*AS, SpillSlots, PhysRegs);
239 ClobberPhysRegOnly(PhysReg, SpillSlots, PhysRegs);
243 // ReusedOp - For each reused operand, we keep track of a bit of information, in
244 // case we need to rollback upon processing a new operand. See comments below.
247 // The MachineInstr operand that reused an available value.
250 // StackSlot - The spill slot of the value being reused.
253 // PhysRegReused - The physical register the value was available in.
254 unsigned PhysRegReused;
256 // AssignedPhysReg - The physreg that was assigned for use by the reload.
257 unsigned AssignedPhysReg;
259 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr)
260 : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr) {}
265 /// rewriteMBB - Keep track of which spills are available even after the
266 /// register allocator is done with them. If possible, avoid reloading vregs.
267 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
269 // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
270 // register values that are still available, due to being loaded to stored to,
271 // but not invalidated yet.
272 std::map<int, unsigned> SpillSlotsAvailable;
274 // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
275 // which physregs are in use holding a stack slot value.
276 std::map<unsigned, int> PhysRegsAvailable;
278 DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
280 std::vector<ReusedOp> ReusedOperands;
282 // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
283 // of it. ".first" is the machine operand index (should always be 0 for now),
284 // and ".second" is the virtual register that is spilled.
285 std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
287 // MaybeDeadStores - When we need to write a value back into a stack slot,
288 // keep track of the inserted store. If the stack slot value is never read
289 // (because the value was used from some available register, for example), and
290 // subsequently stored to, the original store is dead. This map keeps track
291 // of inserted stores that are not used. If we see a subsequent store to the
292 // same stack slot, the original store is deleted.
293 std::map<int, MachineInstr*> MaybeDeadStores;
295 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
297 MachineInstr &MI = *MII;
298 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
300 ReusedOperands.clear();
301 DefAndUseVReg.clear();
303 // Process all of the spilled uses and all non spilled reg references.
304 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
305 MachineOperand &MO = MI.getOperand(i);
306 if (MO.isRegister() && MO.getReg() &&
307 MRegisterInfo::isVirtualRegister(MO.getReg())) {
308 unsigned VirtReg = MO.getReg();
310 if (!VRM.hasStackSlot(VirtReg)) {
311 // This virtual register was assigned a physreg!
312 MI.SetMachineOperandReg(i, VRM.getPhys(VirtReg));
314 // Is this virtual register a spilled value?
316 int StackSlot = VRM.getStackSlot(VirtReg);
319 // Check to see if this stack slot is available.
320 std::map<int, unsigned>::iterator SSI =
321 SpillSlotsAvailable.find(StackSlot);
322 if (SSI != SpillSlotsAvailable.end()) {
323 // If this stack slot value is already available, reuse it!
324 PhysReg = SSI->second;
325 MI.SetMachineOperandReg(i, PhysReg);
326 DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
327 << MRI->getName(SSI->second) << "\n");
329 // The only technical detail we have is that we don't know that
330 // PhysReg won't be clobbered by a reloaded stack slot that occurs
331 // later in the instruction. In particular, consider 'op V1, V2'.
332 // If V1 is available in physreg R0, we would choose to reuse it
333 // here, instead of reloading it into the register the allocator
334 // indicated (say R1). However, V2 might have to be reloaded
335 // later, and it might indicate that it needs to live in R0. When
336 // this occurs, we need to have information available that
337 // indicates it is safe to use R1 for the reload instead of R0.
339 // To further complicate matters, we might conflict with an alias,
340 // or R0 and R1 might not be compatible with each other. In this
341 // case, we actually insert a reload for V1 in R1, ensuring that
342 // we can get at R0 or its alias.
343 ReusedOperands.push_back(ReusedOp(i, StackSlot, PhysReg,
344 VRM.getPhys(VirtReg)));
347 // Otherwise, reload it and remember that we have it.
348 PhysReg = VRM.getPhys(VirtReg);
350 // Note that, if we reused a register for a previous operand, the
351 // register we want to reload into might not actually be
352 // available. If this occurs, use the register indicated by the
354 if (!ReusedOperands.empty()) // This is most often empty.
355 for (unsigned ro = 0, e = ReusedOperands.size(); ro != e; ++ro)
356 if (ReusedOperands[ro].PhysRegReused == PhysReg) {
357 // Yup, use the reload register that we didn't use before.
358 PhysReg = ReusedOperands[ro].AssignedPhysReg;
361 ReusedOp &Op = ReusedOperands[ro];
362 unsigned PRRU = Op.PhysRegReused;
363 for (const unsigned *AS = MRI->getAliasSet(PRRU); *AS; ++AS)
364 if (*AS == PhysReg) {
365 // Okay, we found out that an alias of a reused register
366 // was used. This isn't good because it means we have
367 // to undo a previous reuse.
368 MRI->loadRegFromStackSlot(MBB, &MI, Op.AssignedPhysReg,
370 ClobberPhysReg(Op.AssignedPhysReg, SpillSlotsAvailable,
373 // Any stores to this stack slot are not dead anymore.
374 MaybeDeadStores.erase(Op.StackSlot);
376 MI.SetMachineOperandReg(Op.Operand, Op.AssignedPhysReg);
377 PhysRegsAvailable[Op.AssignedPhysReg] = Op.StackSlot;
378 SpillSlotsAvailable[Op.StackSlot] = Op.AssignedPhysReg;
379 PhysRegsAvailable.erase(Op.PhysRegReused);
380 DEBUG(std::cerr << "Remembering SS#" << Op.StackSlot
382 << MRI->getName(Op.AssignedPhysReg) << "\n");
384 DEBUG(std::cerr << '\t' << *prior(MII));
386 DEBUG(std::cerr << "Reuse undone!\n");
387 ReusedOperands.erase(ReusedOperands.begin()+ro);
394 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot);
395 // This invalidates PhysReg.
396 ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
398 // Any stores to this stack slot are not dead anymore.
399 MaybeDeadStores.erase(StackSlot);
401 MI.SetMachineOperandReg(i, PhysReg);
402 PhysRegsAvailable[PhysReg] = StackSlot;
403 SpillSlotsAvailable[StackSlot] = PhysReg;
404 DEBUG(std::cerr << "Remembering SS#" << StackSlot <<" in physreg "
405 << MRI->getName(PhysReg) << "\n");
407 DEBUG(std::cerr << '\t' << *prior(MII));
410 // If this is both a def and a use, we need to emit a store to the
411 // stack slot after the instruction. Keep track of D&U operands
412 // because we already changed it to a physreg here.
414 // Remember that this was a def-and-use operand, and that the
415 // stack slot is live after this instruction executes.
416 DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
423 // Loop over all of the implicit defs, clearing them from our available
425 const TargetInstrDescriptor &InstrDesc = TII->get(MI.getOpcode());
426 for (const unsigned* ImpDef = InstrDesc.ImplicitDefs; *ImpDef; ++ImpDef)
427 ClobberPhysReg(*ImpDef, SpillSlotsAvailable, PhysRegsAvailable);
429 DEBUG(std::cerr << '\t' << MI);
431 // If we have folded references to memory operands, make sure we clear all
432 // physical registers that may contain the value of the spilled virtual
434 VirtRegMap::MI2VirtMapTy::const_iterator I, E;
435 for (tie(I, E) = VRM.getFoldedVirts(&MI); I != E; ++I) {
436 DEBUG(std::cerr << "Folded vreg: " << I->second);
437 if (VRM.hasStackSlot(I->second)) {
438 int SS = VRM.getStackSlot(I->second);
439 DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
441 // Any stores to this stack slot are not dead anymore.
442 MaybeDeadStores.erase(SS);
444 std::map<int, unsigned>::iterator I = SpillSlotsAvailable.find(SS);
445 if (I != SpillSlotsAvailable.end()) {
446 PhysRegsAvailable.erase(I->second);
447 SpillSlotsAvailable.erase(I);
450 DEBUG(std::cerr << ": No stack slot!\n");
454 // Process all of the spilled defs.
455 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
456 MachineOperand &MO = MI.getOperand(i);
457 if (MO.isRegister() && MO.getReg() && MO.isDef()) {
458 unsigned VirtReg = MO.getReg();
460 bool TakenCareOf = false;
461 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
462 // Check to see if this is a def-and-use vreg operand that we do need
463 // to insert a store for.
464 bool OpTakenCareOf = false;
465 if (MO.isUse() && !DefAndUseVReg.empty()) {
466 for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
467 if (DefAndUseVReg[dau].first == i) {
468 VirtReg = DefAndUseVReg[dau].second;
469 OpTakenCareOf = true;
474 if (!OpTakenCareOf) {
475 ClobberPhysReg(VirtReg, SpillSlotsAvailable, PhysRegsAvailable);
481 // The only vregs left are stack slot definitions.
482 int StackSlot = VRM.getStackSlot(VirtReg);
485 // If this is a def&use operand, and we used a different physreg for
486 // it than the one assigned, make sure to execute the store from the
487 // correct physical register.
488 if (MO.getReg() == VirtReg)
489 PhysReg = VRM.getPhys(VirtReg);
491 PhysReg = MO.getReg();
493 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot);
494 DEBUG(std::cerr << "Store:\t" << *next(MII));
495 MI.SetMachineOperandReg(i, PhysReg);
497 // If there is a dead store to this stack slot, nuke it now.
498 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
501 MBB.erase(LastStore);
503 LastStore = next(MII);
505 // If the stack slot value was previously available in some other
506 // register, change it now. Otherwise, make the register available,
508 std::map<int, unsigned>::iterator SSA =
509 SpillSlotsAvailable.find(StackSlot);
510 if (SSA != SpillSlotsAvailable.end()) {
511 // Remove the record for physreg.
512 PhysRegsAvailable.erase(SSA->second);
513 SpillSlotsAvailable.erase(SSA);
515 ClobberPhysReg(PhysReg, SpillSlotsAvailable, PhysRegsAvailable);
517 PhysRegsAvailable[PhysReg] = StackSlot;
518 SpillSlotsAvailable[StackSlot] = PhysReg;
519 DEBUG(std::cerr << "Updating SS#" << StackSlot <<" in physreg "
520 << MRI->getName(PhysReg) << "\n");
533 llvm::Spiller* llvm::createSpiller() {
534 switch (SpillerOpt) {
535 default: assert(0 && "Unreachable!");
537 return new LocalSpiller();
539 return new SimpleSpiller();