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"
36 Statistic<> NumSpills("spiller", "Number of register spills");
37 Statistic<> NumStores("spiller", "Number of stores added");
38 Statistic<> NumLoads ("spiller", "Number of loads added");
39 Statistic<> NumReused("spiller", "Number of values reused");
40 Statistic<> NumDSE ("spiller", "Number of dead stores elided");
41 Statistic<> NumDCE ("spiller", "Number of copies elided");
43 enum SpillerName { simple, local };
47 cl::desc("Spiller to use: (default: local)"),
49 cl::values(clEnumVal(simple, " simple spiller"),
50 clEnumVal(local, " local spiller"),
55 //===----------------------------------------------------------------------===//
56 // VirtRegMap implementation
57 //===----------------------------------------------------------------------===//
59 void VirtRegMap::grow() {
60 Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
61 Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
64 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
65 assert(MRegisterInfo::isVirtualRegister(virtReg));
66 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
67 "attempt to assign stack slot to already spilled register");
68 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
69 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
71 Virt2StackSlotMap[virtReg] = frameIndex;
76 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
77 assert(MRegisterInfo::isVirtualRegister(virtReg));
78 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
79 "attempt to assign stack slot to already spilled register");
80 Virt2StackSlotMap[virtReg] = frameIndex;
83 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
84 unsigned OpNo, MachineInstr *NewMI,
86 // Move previous memory references folded to new instruction.
87 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
88 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
89 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
90 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
91 MI2VirtMap.erase(I++);
95 if (!OldMI->getOperand(OpNo).isDef()) {
96 assert(OldMI->getOperand(OpNo).isUse() && "Operand is not use or def?");
99 MRInfo = OldMI->getOperand(OpNo).isUse() ? isModRef : isMod;
100 if (LiveOut) MRInfo = (ModRef)(MRInfo | isLiveOut);
103 // add new memory reference
104 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
107 void VirtRegMap::print(std::ostream &OS) const {
108 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
110 OS << "********** REGISTER MAP **********\n";
111 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
112 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
113 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
114 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
118 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
119 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
120 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
121 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
125 void VirtRegMap::dump() const { print(std::cerr); }
128 //===----------------------------------------------------------------------===//
129 // Simple Spiller Implementation
130 //===----------------------------------------------------------------------===//
132 Spiller::~Spiller() {}
135 struct SimpleSpiller : public Spiller {
136 bool runOnMachineFunction(MachineFunction& mf, const VirtRegMap &VRM);
140 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF,
141 const VirtRegMap &VRM) {
142 DEBUG(std::cerr << "********** REWRITE MACHINE CODE **********\n");
143 DEBUG(std::cerr << "********** Function: "
144 << MF.getFunction()->getName() << '\n');
145 const TargetMachine &TM = MF.getTarget();
146 const MRegisterInfo &MRI = *TM.getRegisterInfo();
147 bool *PhysRegsUsed = MF.getUsedPhysregs();
149 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
150 // each vreg once (in the case where a spilled vreg is used by multiple
151 // operands). This is always smaller than the number of operands to the
152 // current machine instr, so it should be small.
153 std::vector<unsigned> LoadedRegs;
155 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
157 DEBUG(std::cerr << MBBI->getBasicBlock()->getName() << ":\n");
158 MachineBasicBlock &MBB = *MBBI;
159 for (MachineBasicBlock::iterator MII = MBB.begin(),
160 E = MBB.end(); MII != E; ++MII) {
161 MachineInstr &MI = *MII;
162 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
163 MachineOperand &MO = MI.getOperand(i);
164 if (MO.isRegister() && MO.getReg())
165 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
166 unsigned VirtReg = MO.getReg();
167 unsigned PhysReg = VRM.getPhys(VirtReg);
168 if (VRM.hasStackSlot(VirtReg)) {
169 int StackSlot = VRM.getStackSlot(VirtReg);
170 const TargetRegisterClass* RC =
171 MF.getSSARegMap()->getRegClass(VirtReg);
174 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
175 == LoadedRegs.end()) {
176 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
177 LoadedRegs.push_back(VirtReg);
179 DEBUG(std::cerr << '\t' << *prior(MII));
183 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
187 PhysRegsUsed[PhysReg] = true;
188 MI.SetMachineOperandReg(i, PhysReg);
190 PhysRegsUsed[MO.getReg()] = true;
194 DEBUG(std::cerr << '\t' << MI);
201 //===----------------------------------------------------------------------===//
202 // Local Spiller Implementation
203 //===----------------------------------------------------------------------===//
206 /// LocalSpiller - This spiller does a simple pass over the machine basic
207 /// block to attempt to keep spills in registers as much as possible for
208 /// blocks that have low register pressure (the vreg may be spilled due to
209 /// register pressure in other blocks).
210 class LocalSpiller : public Spiller {
211 const MRegisterInfo *MRI;
212 const TargetInstrInfo *TII;
214 bool runOnMachineFunction(MachineFunction &MF, const VirtRegMap &VRM) {
215 MRI = MF.getTarget().getRegisterInfo();
216 TII = MF.getTarget().getInstrInfo();
217 DEBUG(std::cerr << "\n**** Local spiller rewriting function '"
218 << MF.getFunction()->getName() << "':\n");
220 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
222 RewriteMBB(*MBB, VRM);
226 void RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM);
227 void ClobberPhysReg(unsigned PR, std::map<int, unsigned> &SpillSlots,
228 std::multimap<unsigned, int> &PhysRegs);
229 void ClobberPhysRegOnly(unsigned PR, std::map<int, unsigned> &SpillSlots,
230 std::multimap<unsigned, int> &PhysRegs);
231 void ModifyStackSlot(int Slot, std::map<int, unsigned> &SpillSlots,
232 std::multimap<unsigned, int> &PhysRegs);
236 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
237 /// top down, keep track of which spills slots are available in each register.
239 /// Note that not all physregs are created equal here. In particular, some
240 /// physregs are reloads that we are allowed to clobber or ignore at any time.
241 /// Other physregs are values that the register allocated program is using that
242 /// we cannot CHANGE, but we can read if we like. We keep track of this on a
243 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
244 /// entries. The predicate 'canClobberPhysReg()' checks this bit and
245 /// addAvailable sets it if.
246 class AvailableSpills {
247 const MRegisterInfo *MRI;
248 const TargetInstrInfo *TII;
250 // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
251 // register values that are still available, due to being loaded or stored to,
252 // but not invalidated yet.
253 std::map<int, unsigned> SpillSlotsAvailable;
255 // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
256 // which stack slot values are currently held by a physreg. This is used to
257 // invalidate entries in SpillSlotsAvailable when a physreg is modified.
258 std::multimap<unsigned, int> PhysRegsAvailable;
260 void ClobberPhysRegOnly(unsigned PhysReg);
262 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
263 : MRI(mri), TII(tii) {
266 /// getSpillSlotPhysReg - If the specified stack slot is available in a
267 /// physical register, return that PhysReg, otherwise return 0.
268 unsigned getSpillSlotPhysReg(int Slot) const {
269 std::map<int, unsigned>::const_iterator I = SpillSlotsAvailable.find(Slot);
270 if (I != SpillSlotsAvailable.end())
271 return I->second >> 1; // Remove the CanClobber bit.
275 const MRegisterInfo *getRegInfo() const { return MRI; }
277 /// addAvailable - Mark that the specified stack slot is available in the
278 /// specified physreg. If CanClobber is true, the physreg can be modified at
279 /// any time without changing the semantics of the program.
280 void addAvailable(int Slot, unsigned Reg, bool CanClobber = true) {
281 // If this stack slot is thought to be available in some other physreg,
282 // remove its record.
283 ModifyStackSlot(Slot);
285 PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
286 SpillSlotsAvailable[Slot] = (Reg << 1) | (unsigned)CanClobber;
288 DEBUG(std::cerr << "Remembering SS#" << Slot << " in physreg "
289 << MRI->getName(Reg) << "\n");
292 /// canClobberPhysReg - Return true if the spiller is allowed to change the
293 /// value of the specified stackslot register if it desires. The specified
294 /// stack slot must be available in a physreg for this query to make sense.
295 bool canClobberPhysReg(int Slot) const {
296 assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
297 return SpillSlotsAvailable.find(Slot)->second & 1;
300 /// ClobberPhysReg - This is called when the specified physreg changes
301 /// value. We use this to invalidate any info about stuff we thing lives in
302 /// it and any of its aliases.
303 void ClobberPhysReg(unsigned PhysReg);
305 /// ModifyStackSlot - This method is called when the value in a stack slot
306 /// changes. This removes information about which register the previous value
307 /// for this slot lives in (as the previous value is dead now).
308 void ModifyStackSlot(int Slot);
311 /// ClobberPhysRegOnly - This is called when the specified physreg changes
312 /// value. We use this to invalidate any info about stuff we thing lives in it.
313 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
314 std::multimap<unsigned, int>::iterator I =
315 PhysRegsAvailable.lower_bound(PhysReg);
316 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
317 int Slot = I->second;
318 PhysRegsAvailable.erase(I++);
319 assert((SpillSlotsAvailable[Slot] >> 1) == PhysReg &&
320 "Bidirectional map mismatch!");
321 SpillSlotsAvailable.erase(Slot);
322 DEBUG(std::cerr << "PhysReg " << MRI->getName(PhysReg)
323 << " clobbered, invalidating SS#" << Slot << "\n");
327 /// ClobberPhysReg - This is called when the specified physreg changes
328 /// value. We use this to invalidate any info about stuff we thing lives in
329 /// it and any of its aliases.
330 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
331 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
332 ClobberPhysRegOnly(*AS);
333 ClobberPhysRegOnly(PhysReg);
336 /// ModifyStackSlot - This method is called when the value in a stack slot
337 /// changes. This removes information about which register the previous value
338 /// for this slot lives in (as the previous value is dead now).
339 void AvailableSpills::ModifyStackSlot(int Slot) {
340 std::map<int, unsigned>::iterator It = SpillSlotsAvailable.find(Slot);
341 if (It == SpillSlotsAvailable.end()) return;
342 unsigned Reg = It->second >> 1;
343 SpillSlotsAvailable.erase(It);
345 // This register may hold the value of multiple stack slots, only remove this
346 // stack slot from the set of values the register contains.
347 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
349 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
350 "Map inverse broken!");
351 if (I->second == Slot) break;
353 PhysRegsAvailable.erase(I);
358 // ReusedOp - For each reused operand, we keep track of a bit of information, in
359 // case we need to rollback upon processing a new operand. See comments below.
362 // The MachineInstr operand that reused an available value.
365 // StackSlot - The spill slot of the value being reused.
368 // PhysRegReused - The physical register the value was available in.
369 unsigned PhysRegReused;
371 // AssignedPhysReg - The physreg that was assigned for use by the reload.
372 unsigned AssignedPhysReg;
374 // VirtReg - The virtual register itself.
377 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
379 : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
383 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
384 /// is reused instead of reloaded.
387 std::vector<ReusedOp> Reuses;
389 ReuseInfo(MachineInstr &mi) : MI(mi) {}
391 bool hasReuses() const {
392 return !Reuses.empty();
395 /// addReuse - If we choose to reuse a virtual register that is already
396 /// available instead of reloading it, remember that we did so.
397 void addReuse(unsigned OpNo, unsigned StackSlot,
398 unsigned PhysRegReused, unsigned AssignedPhysReg,
400 // If the reload is to the assigned register anyway, no undo will be
402 if (PhysRegReused == AssignedPhysReg) return;
404 // Otherwise, remember this.
405 Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused,
406 AssignedPhysReg, VirtReg));
409 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
410 /// is some other operand that is using the specified register, either pick
411 /// a new register to use, or evict the previous reload and use this reg.
412 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
413 AvailableSpills &Spills,
414 std::map<int, MachineInstr*> &MaybeDeadStores) {
415 if (Reuses.empty()) return PhysReg; // This is most often empty.
417 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
418 ReusedOp &Op = Reuses[ro];
419 // If we find some other reuse that was supposed to use this register
420 // exactly for its reload, we can change this reload to use ITS reload
422 if (Op.PhysRegReused == PhysReg) {
423 // Yup, use the reload register that we didn't use before.
424 unsigned NewReg = Op.AssignedPhysReg;
426 // Remove the record for the previous reuse. We know it can never be
428 Reuses.erase(Reuses.begin()+ro);
429 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores);
431 // Otherwise, we might also have a problem if a previously reused
432 // value aliases the new register. If so, codegen the previous reload
434 unsigned PRRU = Op.PhysRegReused;
435 const MRegisterInfo *MRI = Spills.getRegInfo();
436 if (MRI->areAliases(PRRU, PhysReg)) {
437 // Okay, we found out that an alias of a reused register
438 // was used. This isn't good because it means we have
439 // to undo a previous reuse.
440 MachineBasicBlock *MBB = MI->getParent();
441 const TargetRegisterClass *AliasRC =
442 MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
444 // Copy Op out of the vector and remove it, we're going to insert an
445 // explicit load for it.
447 Reuses.erase(Reuses.begin()+ro);
449 // Ok, we're going to try to reload the assigned physreg into the
450 // slot that we were supposed to in the first place. However, that
451 // register could hold a reuse. Check to see if it conflicts or
452 // would prefer us to use a different register.
453 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
454 MI, Spills, MaybeDeadStores);
456 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
457 NewOp.StackSlot, AliasRC);
458 Spills.ClobberPhysReg(NewPhysReg);
459 Spills.ClobberPhysReg(NewOp.PhysRegReused);
461 // Any stores to this stack slot are not dead anymore.
462 MaybeDeadStores.erase(NewOp.StackSlot);
464 MI->SetMachineOperandReg(NewOp.Operand, NewPhysReg);
466 Spills.addAvailable(NewOp.StackSlot, NewPhysReg);
468 DEBUG(MachineBasicBlock::iterator MII = MI;
469 std::cerr << '\t' << *prior(MII));
471 DEBUG(std::cerr << "Reuse undone!\n");
474 // Finally, PhysReg is now available, go ahead and use it.
485 /// rewriteMBB - Keep track of which spills are available even after the
486 /// register allocator is done with them. If possible, avoid reloading vregs.
487 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, const VirtRegMap &VRM) {
489 DEBUG(std::cerr << MBB.getBasicBlock()->getName() << ":\n");
491 // Spills - Keep track of which spilled values are available in physregs so
492 // that we can choose to reuse the physregs instead of emitting reloads.
493 AvailableSpills Spills(MRI, TII);
495 // DefAndUseVReg - When we see a def&use operand that is spilled, keep track
496 // of it. ".first" is the machine operand index (should always be 0 for now),
497 // and ".second" is the virtual register that is spilled.
498 std::vector<std::pair<unsigned, unsigned> > DefAndUseVReg;
500 // MaybeDeadStores - When we need to write a value back into a stack slot,
501 // keep track of the inserted store. If the stack slot value is never read
502 // (because the value was used from some available register, for example), and
503 // subsequently stored to, the original store is dead. This map keeps track
504 // of inserted stores that are not used. If we see a subsequent store to the
505 // same stack slot, the original store is deleted.
506 std::map<int, MachineInstr*> MaybeDeadStores;
508 bool *PhysRegsUsed = MBB.getParent()->getUsedPhysregs();
510 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
512 MachineInstr &MI = *MII;
513 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
515 /// ReusedOperands - Keep track of operand reuse in case we need to undo
517 ReuseInfo ReusedOperands(MI);
519 DefAndUseVReg.clear();
521 // Process all of the spilled uses and all non spilled reg references.
522 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
523 MachineOperand &MO = MI.getOperand(i);
524 if (!MO.isRegister() || MO.getReg() == 0)
525 continue; // Ignore non-register operands.
527 if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
528 // Ignore physregs for spilling, but remember that it is used by this
530 PhysRegsUsed[MO.getReg()] = true;
534 assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
535 "Not a virtual or a physical register?");
537 unsigned VirtReg = MO.getReg();
538 if (!VRM.hasStackSlot(VirtReg)) {
539 // This virtual register was assigned a physreg!
540 unsigned Phys = VRM.getPhys(VirtReg);
541 PhysRegsUsed[Phys] = true;
542 MI.SetMachineOperandReg(i, Phys);
546 // This virtual register is now known to be a spilled value.
548 continue; // Handle defs in the loop below (handle use&def here though)
550 // If this is both a def and a use, we need to emit a store to the
551 // stack slot after the instruction. Keep track of D&U operands
552 // because we are about to change it to a physreg here.
554 // Remember that this was a def-and-use operand, and that the
555 // stack slot is live after this instruction executes.
556 DefAndUseVReg.push_back(std::make_pair(i, VirtReg));
559 int StackSlot = VRM.getStackSlot(VirtReg);
562 // Check to see if this stack slot is available.
563 if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot))) {
565 // Don't reuse it for a def&use operand if we aren't allowed to change
567 if (!MO.isDef() || Spills.canClobberPhysReg(StackSlot)) {
568 // If this stack slot value is already available, reuse it!
569 DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
570 << MRI->getName(PhysReg) << " for vreg"
571 << VirtReg <<" instead of reloading into physreg "
572 << MRI->getName(VRM.getPhys(VirtReg)) << "\n");
573 MI.SetMachineOperandReg(i, PhysReg);
575 // The only technical detail we have is that we don't know that
576 // PhysReg won't be clobbered by a reloaded stack slot that occurs
577 // later in the instruction. In particular, consider 'op V1, V2'.
578 // If V1 is available in physreg R0, we would choose to reuse it
579 // here, instead of reloading it into the register the allocator
580 // indicated (say R1). However, V2 might have to be reloaded
581 // later, and it might indicate that it needs to live in R0. When
582 // this occurs, we need to have information available that
583 // indicates it is safe to use R1 for the reload instead of R0.
585 // To further complicate matters, we might conflict with an alias,
586 // or R0 and R1 might not be compatible with each other. In this
587 // case, we actually insert a reload for V1 in R1, ensuring that
588 // we can get at R0 or its alias.
589 ReusedOperands.addReuse(i, StackSlot, PhysReg,
590 VRM.getPhys(VirtReg), VirtReg);
595 // Otherwise we have a situation where we have a two-address instruction
596 // whose mod/ref operand needs to be reloaded. This reload is already
597 // available in some register "PhysReg", but if we used PhysReg as the
598 // operand to our 2-addr instruction, the instruction would modify
599 // PhysReg. This isn't cool if something later uses PhysReg and expects
600 // to get its initial value.
602 // To avoid this problem, and to avoid doing a load right after a store,
603 // we emit a copy from PhysReg into the designated register for this
605 unsigned DesignatedReg = VRM.getPhys(VirtReg);
606 assert(DesignatedReg && "Must map virtreg to physreg!");
608 // Note that, if we reused a register for a previous operand, the
609 // register we want to reload into might not actually be
610 // available. If this occurs, use the register indicated by the
612 if (ReusedOperands.hasReuses())
613 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
614 Spills, MaybeDeadStores);
616 // If the mapped designated register is actually the physreg we have
617 // incoming, we don't need to inserted a dead copy.
618 if (DesignatedReg == PhysReg) {
619 // If this stack slot value is already available, reuse it!
620 DEBUG(std::cerr << "Reusing SS#" << StackSlot << " from physreg "
621 << MRI->getName(PhysReg) << " for vreg"
623 << " instead of reloading into same physreg.\n");
624 MI.SetMachineOperandReg(i, PhysReg);
629 const TargetRegisterClass* RC =
630 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
632 PhysRegsUsed[DesignatedReg] = true;
633 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
635 // This invalidates DesignatedReg.
636 Spills.ClobberPhysReg(DesignatedReg);
638 Spills.addAvailable(StackSlot, DesignatedReg);
639 MI.SetMachineOperandReg(i, DesignatedReg);
640 DEBUG(std::cerr << '\t' << *prior(MII));
645 // Otherwise, reload it and remember that we have it.
646 PhysReg = VRM.getPhys(VirtReg);
647 assert(PhysReg && "Must map virtreg to physreg!");
648 const TargetRegisterClass* RC =
649 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
651 // Note that, if we reused a register for a previous operand, the
652 // register we want to reload into might not actually be
653 // available. If this occurs, use the register indicated by the
655 if (ReusedOperands.hasReuses())
656 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
657 Spills, MaybeDeadStores);
659 PhysRegsUsed[PhysReg] = true;
660 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
661 // This invalidates PhysReg.
662 Spills.ClobberPhysReg(PhysReg);
664 // Any stores to this stack slot are not dead anymore.
665 MaybeDeadStores.erase(StackSlot);
666 Spills.addAvailable(StackSlot, PhysReg);
668 MI.SetMachineOperandReg(i, PhysReg);
669 DEBUG(std::cerr << '\t' << *prior(MII));
672 // Loop over all of the implicit defs, clearing them from our available
674 for (const unsigned *ImpDef = TII->getImplicitDefs(MI.getOpcode());
676 PhysRegsUsed[*ImpDef] = true;
677 Spills.ClobberPhysReg(*ImpDef);
680 DEBUG(std::cerr << '\t' << MI);
682 // If we have folded references to memory operands, make sure we clear all
683 // physical registers that may contain the value of the spilled virtual
685 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
686 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
687 DEBUG(std::cerr << "Folded vreg: " << I->second.first << " MR: "
688 << I->second.second);
689 unsigned VirtReg = I->second.first;
690 VirtRegMap::ModRef MR = I->second.second;
691 if (!VRM.hasStackSlot(VirtReg)) {
692 DEBUG(std::cerr << ": No stack slot!\n");
695 int SS = VRM.getStackSlot(VirtReg);
696 DEBUG(std::cerr << " - StackSlot: " << SS << "\n");
698 // If this folded instruction is just a use, check to see if it's a
699 // straight load from the virt reg slot.
700 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
702 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
703 // If this spill slot is available, turn it into a copy (or nothing)
704 // instead of leaving it as a load!
706 if (FrameIdx == SS && (InReg = Spills.getSpillSlotPhysReg(SS))) {
707 DEBUG(std::cerr << "Promoted Load To Copy: " << MI);
708 MachineFunction &MF = *MBB.getParent();
709 if (DestReg != InReg) {
710 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
711 MF.getSSARegMap()->getRegClass(VirtReg));
712 // Revisit the copy so we make sure to notice the effects of the
713 // operation on the destreg (either needing to RA it if it's
714 // virtual or needing to clobber any values if it's physical).
716 --NextMII; // backtrack to the copy.
719 goto ProcessNextInst;
724 // If this reference is not a use, any previous store is now dead.
725 // Otherwise, the store to this stack slot is not dead anymore.
726 std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
727 if (MDSI != MaybeDeadStores.end()) {
728 if (MR & VirtRegMap::isRef) // Previous store is not dead.
729 MaybeDeadStores.erase(MDSI);
731 // If we get here, the store is dead, nuke it now.
732 assert(!(MR & VirtRegMap::isRef) && "Can't be modref!");
733 // Don't nuke it if the value is needed in another block.
734 if (!(MR & VirtRegMap::isLiveOut)) {
735 DEBUG(std::cerr << " Killed store:\t" << *MDSI->second);
736 MBB.erase(MDSI->second);
737 MaybeDeadStores.erase(MDSI);
743 // If the spill slot value is available, and this is a new definition of
744 // the value, the value is not available anymore.
745 if (MR & VirtRegMap::isMod) {
746 // Notice that the value in this stack slot has been modified.
747 Spills.ModifyStackSlot(SS);
749 // If this is *just* a mod of the value, check to see if this is just a
750 // store to the spill slot (i.e. the spill got merged into the copy). If
751 // so, realize that the vreg is available now, and add the store to the
752 // MaybeDeadStore info.
754 if (!(MR & VirtRegMap::isRef)) {
755 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
756 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
757 "Src hasn't been allocated yet?");
758 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
759 // this as a potentially dead store in case there is a subsequent
760 // store into the stack slot without a read from it.
761 MaybeDeadStores[StackSlot] = &MI;
763 // If the stack slot value was previously available in some other
764 // register, change it now. Otherwise, make the register available,
766 Spills.addAvailable(StackSlot, SrcReg, false /*don't clobber*/);
772 // Process all of the spilled defs.
773 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
774 MachineOperand &MO = MI.getOperand(i);
775 if (MO.isRegister() && MO.getReg() && MO.isDef()) {
776 unsigned VirtReg = MO.getReg();
778 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
779 // Check to see if this is a def-and-use vreg operand that we do need
780 // to insert a store for.
781 bool OpTakenCareOf = false;
782 if (MO.isUse() && !DefAndUseVReg.empty()) {
783 for (unsigned dau = 0, e = DefAndUseVReg.size(); dau != e; ++dau)
784 if (DefAndUseVReg[dau].first == i) {
785 VirtReg = DefAndUseVReg[dau].second;
786 OpTakenCareOf = true;
791 if (!OpTakenCareOf) {
792 // Check to see if this is a noop copy. If so, eliminate the
793 // instruction before considering the dest reg to be changed.
795 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
797 DEBUG(std::cerr << "Removing now-noop copy: " << MI);
799 goto ProcessNextInst;
801 Spills.ClobberPhysReg(VirtReg);
806 // The only vregs left are stack slot definitions.
807 int StackSlot = VRM.getStackSlot(VirtReg);
808 const TargetRegisterClass *RC =
809 MBB.getParent()->getSSARegMap()->getRegClass(VirtReg);
812 // If this is a def&use operand, and we used a different physreg for
813 // it than the one assigned, make sure to execute the store from the
814 // correct physical register.
815 if (MO.getReg() == VirtReg)
816 PhysReg = VRM.getPhys(VirtReg);
818 PhysReg = MO.getReg();
820 PhysRegsUsed[PhysReg] = true;
821 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
822 DEBUG(std::cerr << "Store:\t" << *next(MII));
823 MI.SetMachineOperandReg(i, PhysReg);
825 // Check to see if this is a noop copy. If so, eliminate the
826 // instruction before considering the dest reg to be changed.
829 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
831 DEBUG(std::cerr << "Removing now-noop copy: " << MI);
833 goto ProcessNextInst;
837 // If there is a dead store to this stack slot, nuke it now.
838 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
840 DEBUG(std::cerr << " Killed store:\t" << *LastStore);
842 MBB.erase(LastStore);
844 LastStore = next(MII);
846 // If the stack slot value was previously available in some other
847 // register, change it now. Otherwise, make the register available,
849 Spills.ModifyStackSlot(StackSlot);
850 Spills.ClobberPhysReg(PhysReg);
851 Spills.addAvailable(StackSlot, PhysReg);
862 llvm::Spiller* llvm::createSpiller() {
863 switch (SpillerOpt) {
864 default: assert(0 && "Unreachable!");
866 return new LocalSpiller();
868 return new SimpleSpiller();