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/Support/Compiler.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallSet.h"
37 STATISTIC(NumSpills, "Number of register spills");
38 STATISTIC(NumReMats, "Number of re-materialization");
39 STATISTIC(NumStores, "Number of stores added");
40 STATISTIC(NumLoads , "Number of loads added");
41 STATISTIC(NumReused, "Number of values reused");
42 STATISTIC(NumDSE , "Number of dead stores elided");
43 STATISTIC(NumDCE , "Number of copies elided");
46 enum SpillerName { simple, local };
48 static cl::opt<SpillerName>
50 cl::desc("Spiller to use: (default: local)"),
52 cl::values(clEnumVal(simple, " simple spiller"),
53 clEnumVal(local, " local spiller"),
58 //===----------------------------------------------------------------------===//
59 // VirtRegMap implementation
60 //===----------------------------------------------------------------------===//
62 VirtRegMap::VirtRegMap(MachineFunction &mf)
63 : TII(*mf.getTarget().getInstrInfo()), MF(mf),
64 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
65 ReMatId(MAX_STACK_SLOT+1) {
69 void VirtRegMap::grow() {
70 Virt2PhysMap.grow(MF.getSSARegMap()->getLastVirtReg());
71 Virt2StackSlotMap.grow(MF.getSSARegMap()->getLastVirtReg());
74 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
75 assert(MRegisterInfo::isVirtualRegister(virtReg));
76 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
77 "attempt to assign stack slot to already spilled register");
78 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(virtReg);
79 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
81 Virt2StackSlotMap[virtReg] = frameIndex;
86 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
87 assert(MRegisterInfo::isVirtualRegister(virtReg));
88 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
89 "attempt to assign stack slot to already spilled register");
90 assert((frameIndex >= 0 ||
91 (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
92 "illegal fixed frame index");
93 Virt2StackSlotMap[virtReg] = frameIndex;
96 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
97 assert(MRegisterInfo::isVirtualRegister(virtReg));
98 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
99 "attempt to assign re-mat id to already spilled register");
100 const MachineInstr *DefMI = getReMaterializedMI(virtReg);
102 if (TII.isLoadFromStackSlot((MachineInstr*)DefMI, FrameIdx)) {
103 // Load from stack slot is re-materialize as reload from the stack slot!
104 Virt2StackSlotMap[virtReg] = FrameIdx;
107 Virt2StackSlotMap[virtReg] = ReMatId;
111 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
112 unsigned OpNo, MachineInstr *NewMI) {
113 // Move previous memory references folded to new instruction.
114 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
115 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
116 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
117 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
118 MI2VirtMap.erase(I++);
122 const TargetInstrDescriptor *TID = OldMI->getInstrDescriptor();
123 if (TID->getOperandConstraint(OpNo, TOI::TIED_TO) != -1 ||
124 TID->findTiedToSrcOperand(OpNo) != -1) {
125 // Folded a two-address operand.
127 } else if (OldMI->getOperand(OpNo).isDef()) {
133 // add new memory reference
134 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
137 void VirtRegMap::print(std::ostream &OS) const {
138 const MRegisterInfo* MRI = MF.getTarget().getRegisterInfo();
140 OS << "********** REGISTER MAP **********\n";
141 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
142 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i) {
143 if (Virt2PhysMap[i] != (unsigned)VirtRegMap::NO_PHYS_REG)
144 OS << "[reg" << i << " -> " << MRI->getName(Virt2PhysMap[i]) << "]\n";
148 for (unsigned i = MRegisterInfo::FirstVirtualRegister,
149 e = MF.getSSARegMap()->getLastVirtReg(); i <= e; ++i)
150 if (Virt2StackSlotMap[i] != VirtRegMap::NO_STACK_SLOT)
151 OS << "[reg" << i << " -> fi#" << Virt2StackSlotMap[i] << "]\n";
155 void VirtRegMap::dump() const {
160 //===----------------------------------------------------------------------===//
161 // Simple Spiller Implementation
162 //===----------------------------------------------------------------------===//
164 Spiller::~Spiller() {}
167 struct VISIBILITY_HIDDEN SimpleSpiller : public Spiller {
168 bool runOnMachineFunction(MachineFunction& mf, VirtRegMap &VRM);
172 bool SimpleSpiller::runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
173 DOUT << "********** REWRITE MACHINE CODE **********\n";
174 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
175 const TargetMachine &TM = MF.getTarget();
176 const MRegisterInfo &MRI = *TM.getRegisterInfo();
178 // LoadedRegs - Keep track of which vregs are loaded, so that we only load
179 // each vreg once (in the case where a spilled vreg is used by multiple
180 // operands). This is always smaller than the number of operands to the
181 // current machine instr, so it should be small.
182 std::vector<unsigned> LoadedRegs;
184 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
186 DOUT << MBBI->getBasicBlock()->getName() << ":\n";
187 MachineBasicBlock &MBB = *MBBI;
188 for (MachineBasicBlock::iterator MII = MBB.begin(),
189 E = MBB.end(); MII != E; ++MII) {
190 MachineInstr &MI = *MII;
191 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
192 MachineOperand &MO = MI.getOperand(i);
193 if (MO.isRegister() && MO.getReg())
194 if (MRegisterInfo::isVirtualRegister(MO.getReg())) {
195 unsigned VirtReg = MO.getReg();
196 unsigned PhysReg = VRM.getPhys(VirtReg);
197 if (VRM.hasStackSlot(VirtReg)) {
198 int StackSlot = VRM.getStackSlot(VirtReg);
199 const TargetRegisterClass* RC =
200 MF.getSSARegMap()->getRegClass(VirtReg);
203 std::find(LoadedRegs.begin(), LoadedRegs.end(), VirtReg)
204 == LoadedRegs.end()) {
205 MRI.loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
206 LoadedRegs.push_back(VirtReg);
208 DOUT << '\t' << *prior(MII);
212 MRI.storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
216 MF.setPhysRegUsed(PhysReg);
217 MI.getOperand(i).setReg(PhysReg);
219 MF.setPhysRegUsed(MO.getReg());
230 //===----------------------------------------------------------------------===//
231 // Local Spiller Implementation
232 //===----------------------------------------------------------------------===//
235 /// LocalSpiller - This spiller does a simple pass over the machine basic
236 /// block to attempt to keep spills in registers as much as possible for
237 /// blocks that have low register pressure (the vreg may be spilled due to
238 /// register pressure in other blocks).
239 class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
240 const MRegisterInfo *MRI;
241 const TargetInstrInfo *TII;
243 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
244 MRI = MF.getTarget().getRegisterInfo();
245 TII = MF.getTarget().getInstrInfo();
246 DOUT << "\n**** Local spiller rewriting function '"
247 << MF.getFunction()->getName() << "':\n";
249 std::vector<MachineInstr *> ReMatedMIs;
250 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
252 RewriteMBB(*MBB, VRM, ReMatedMIs);
253 for (unsigned i = 0, e = ReMatedMIs.size(); i != e; ++i)
254 delete ReMatedMIs[i];
258 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
259 std::vector<MachineInstr*> &ReMatedMIs);
263 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
264 /// top down, keep track of which spills slots are available in each register.
266 /// Note that not all physregs are created equal here. In particular, some
267 /// physregs are reloads that we are allowed to clobber or ignore at any time.
268 /// Other physregs are values that the register allocated program is using that
269 /// we cannot CHANGE, but we can read if we like. We keep track of this on a
270 /// per-stack-slot basis as the low bit in the value of the SpillSlotsAvailable
271 /// entries. The predicate 'canClobberPhysReg()' checks this bit and
272 /// addAvailable sets it if.
274 class VISIBILITY_HIDDEN AvailableSpills {
275 const MRegisterInfo *MRI;
276 const TargetInstrInfo *TII;
278 // SpillSlotsAvailable - This map keeps track of all of the spilled virtual
279 // register values that are still available, due to being loaded or stored to,
280 // but not invalidated yet. It also tracks the instructions that defined
281 // or used the register.
282 typedef std::pair<unsigned, std::vector<MachineInstr*> > SSInfo;
283 std::map<int, SSInfo> SpillSlotsAvailable;
285 // PhysRegsAvailable - This is the inverse of SpillSlotsAvailable, indicating
286 // which stack slot values are currently held by a physreg. This is used to
287 // invalidate entries in SpillSlotsAvailable when a physreg is modified.
288 std::multimap<unsigned, int> PhysRegsAvailable;
290 void disallowClobberPhysRegOnly(unsigned PhysReg);
292 void ClobberPhysRegOnly(unsigned PhysReg);
294 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
295 : MRI(mri), TII(tii) {
298 const MRegisterInfo *getRegInfo() const { return MRI; }
300 /// getSpillSlotPhysReg - If the specified stack slot is available in a
301 /// physical register, return that PhysReg, otherwise return 0. It also
302 /// returns by reference the instruction that either defines or last uses
304 unsigned getSpillSlotPhysReg(int Slot, MachineInstr *&SSMI) const {
305 std::map<int, SSInfo>::const_iterator I = SpillSlotsAvailable.find(Slot);
306 if (I != SpillSlotsAvailable.end()) {
307 if (!I->second.second.empty())
308 SSMI = I->second.second.back();
309 return I->second.first >> 1; // Remove the CanClobber bit.
314 /// addLastUse - Add the last use information of all stack slots whose
315 /// values are available in the specific register.
316 void addLastUse(unsigned PhysReg, MachineInstr *Use) {
317 std::multimap<unsigned, int>::iterator I =
318 PhysRegsAvailable.lower_bound(PhysReg);
319 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
320 int Slot = I->second;
323 std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
324 assert(II != SpillSlotsAvailable.end() && "Slot not available!");
325 unsigned Val = II->second.first;
326 assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
327 // This can be true if there are multiple uses of the same register.
328 if (II->second.second.back() != Use)
329 II->second.second.push_back(Use);
333 /// removeLastUse - Remove the last use information of all stack slots whose
334 /// values are available in the specific register.
335 void removeLastUse(unsigned PhysReg, MachineInstr *Use) {
336 std::multimap<unsigned, int>::iterator I =
337 PhysRegsAvailable.lower_bound(PhysReg);
338 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
339 int Slot = I->second;
342 std::map<int, SSInfo>::iterator II = SpillSlotsAvailable.find(Slot);
343 assert(II != SpillSlotsAvailable.end() && "Slot not available!");
344 unsigned Val = II->second.first;
345 assert((Val >> 1) == PhysReg && "Bidirectional map mismatch!");
346 if (II->second.second.back() == Use)
347 II->second.second.pop_back();
351 /// addAvailable - Mark that the specified stack slot is available in the
352 /// specified physreg. If CanClobber is true, the physreg can be modified at
353 /// any time without changing the semantics of the program.
354 void addAvailable(int Slot, MachineInstr *MI, unsigned Reg,
355 bool CanClobber = true) {
356 // If this stack slot is thought to be available in some other physreg,
357 // remove its record.
358 ModifyStackSlot(Slot);
360 PhysRegsAvailable.insert(std::make_pair(Reg, Slot));
361 std::vector<MachineInstr*> DefUses;
362 DefUses.push_back(MI);
363 SpillSlotsAvailable[Slot] =
364 std::make_pair((Reg << 1) | (unsigned)CanClobber, DefUses);
366 if (Slot > VirtRegMap::MAX_STACK_SLOT)
367 DOUT << "Remembering RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1;
369 DOUT << "Remembering SS#" << Slot;
370 DOUT << " in physreg " << MRI->getName(Reg) << "\n";
373 /// canClobberPhysReg - Return true if the spiller is allowed to change the
374 /// value of the specified stackslot register if it desires. The specified
375 /// stack slot must be available in a physreg for this query to make sense.
376 bool canClobberPhysReg(int Slot) const {
377 assert(SpillSlotsAvailable.count(Slot) && "Slot not available!");
378 return SpillSlotsAvailable.find(Slot)->second.first & 1;
381 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
382 /// stackslot register. The register is still available but is no longer
383 /// allowed to be modifed.
384 void disallowClobberPhysReg(unsigned PhysReg);
386 /// ClobberPhysReg - This is called when the specified physreg changes
387 /// value. We use this to invalidate any info about stuff we thing lives in
388 /// it and any of its aliases.
389 void ClobberPhysReg(unsigned PhysReg);
391 /// ModifyStackSlot - This method is called when the value in a stack slot
392 /// changes. This removes information about which register the previous value
393 /// for this slot lives in (as the previous value is dead now).
394 void ModifyStackSlot(int Slot);
398 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
399 /// stackslot register. The register is still available but is no longer
400 /// allowed to be modifed.
401 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
402 std::multimap<unsigned, int>::iterator I =
403 PhysRegsAvailable.lower_bound(PhysReg);
404 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
405 int Slot = I->second;
407 assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
408 "Bidirectional map mismatch!");
409 SpillSlotsAvailable[Slot].first &= ~1;
410 DOUT << "PhysReg " << MRI->getName(PhysReg)
411 << " copied, it is available for use but can no longer be modified\n";
415 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
416 /// stackslot register and its aliases. The register and its aliases may
417 /// still available but is no longer allowed to be modifed.
418 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
419 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
420 disallowClobberPhysRegOnly(*AS);
421 disallowClobberPhysRegOnly(PhysReg);
424 /// ClobberPhysRegOnly - This is called when the specified physreg changes
425 /// value. We use this to invalidate any info about stuff we thing lives in it.
426 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
427 std::multimap<unsigned, int>::iterator I =
428 PhysRegsAvailable.lower_bound(PhysReg);
429 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
430 int Slot = I->second;
431 PhysRegsAvailable.erase(I++);
432 assert((SpillSlotsAvailable[Slot].first >> 1) == PhysReg &&
433 "Bidirectional map mismatch!");
434 SpillSlotsAvailable.erase(Slot);
435 DOUT << "PhysReg " << MRI->getName(PhysReg)
436 << " clobbered, invalidating ";
437 if (Slot > VirtRegMap::MAX_STACK_SLOT)
438 DOUT << "RM#" << Slot-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
440 DOUT << "SS#" << Slot << "\n";
444 /// ClobberPhysReg - This is called when the specified physreg changes
445 /// value. We use this to invalidate any info about stuff we thing lives in
446 /// it and any of its aliases.
447 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
448 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
449 ClobberPhysRegOnly(*AS);
450 ClobberPhysRegOnly(PhysReg);
453 /// ModifyStackSlot - This method is called when the value in a stack slot
454 /// changes. This removes information about which register the previous value
455 /// for this slot lives in (as the previous value is dead now).
456 void AvailableSpills::ModifyStackSlot(int Slot) {
457 std::map<int, SSInfo>::iterator It = SpillSlotsAvailable.find(Slot);
458 if (It == SpillSlotsAvailable.end()) return;
459 unsigned Reg = It->second.first >> 1;
460 SpillSlotsAvailable.erase(It);
462 // This register may hold the value of multiple stack slots, only remove this
463 // stack slot from the set of values the register contains.
464 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
466 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
467 "Map inverse broken!");
468 if (I->second == Slot) break;
470 PhysRegsAvailable.erase(I);
475 // ReusedOp - For each reused operand, we keep track of a bit of information, in
476 // case we need to rollback upon processing a new operand. See comments below.
479 // The MachineInstr operand that reused an available value.
482 // StackSlot - The spill slot of the value being reused.
485 // PhysRegReused - The physical register the value was available in.
486 unsigned PhysRegReused;
488 // AssignedPhysReg - The physreg that was assigned for use by the reload.
489 unsigned AssignedPhysReg;
491 // VirtReg - The virtual register itself.
494 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
496 : Operand(o), StackSlot(ss), PhysRegReused(prr), AssignedPhysReg(apr),
500 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
501 /// is reused instead of reloaded.
502 class VISIBILITY_HIDDEN ReuseInfo {
504 std::vector<ReusedOp> Reuses;
505 BitVector PhysRegsClobbered;
507 ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
508 PhysRegsClobbered.resize(mri->getNumRegs());
511 bool hasReuses() const {
512 return !Reuses.empty();
515 /// addReuse - If we choose to reuse a virtual register that is already
516 /// available instead of reloading it, remember that we did so.
517 void addReuse(unsigned OpNo, unsigned StackSlot,
518 unsigned PhysRegReused, unsigned AssignedPhysReg,
520 // If the reload is to the assigned register anyway, no undo will be
522 if (PhysRegReused == AssignedPhysReg) return;
524 // Otherwise, remember this.
525 Reuses.push_back(ReusedOp(OpNo, StackSlot, PhysRegReused,
526 AssignedPhysReg, VirtReg));
529 void markClobbered(unsigned PhysReg) {
530 PhysRegsClobbered.set(PhysReg);
533 bool isClobbered(unsigned PhysReg) const {
534 return PhysRegsClobbered.test(PhysReg);
537 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
538 /// is some other operand that is using the specified register, either pick
539 /// a new register to use, or evict the previous reload and use this reg.
540 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
541 AvailableSpills &Spills,
542 std::map<int, MachineInstr*> &MaybeDeadStores,
543 SmallSet<unsigned, 8> &Rejected) {
544 if (Reuses.empty()) return PhysReg; // This is most often empty.
546 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
547 ReusedOp &Op = Reuses[ro];
548 // If we find some other reuse that was supposed to use this register
549 // exactly for its reload, we can change this reload to use ITS reload
550 // register. That is, unless its reload register has already been
551 // considered and subsequently rejected because it has also been reused
552 // by another operand.
553 if (Op.PhysRegReused == PhysReg &&
554 Rejected.count(Op.AssignedPhysReg) == 0) {
555 // Yup, use the reload register that we didn't use before.
556 unsigned NewReg = Op.AssignedPhysReg;
557 Rejected.insert(PhysReg);
558 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected);
560 // Otherwise, we might also have a problem if a previously reused
561 // value aliases the new register. If so, codegen the previous reload
563 unsigned PRRU = Op.PhysRegReused;
564 const MRegisterInfo *MRI = Spills.getRegInfo();
565 if (MRI->areAliases(PRRU, PhysReg)) {
566 // Okay, we found out that an alias of a reused register
567 // was used. This isn't good because it means we have
568 // to undo a previous reuse.
569 MachineBasicBlock *MBB = MI->getParent();
570 const TargetRegisterClass *AliasRC =
571 MBB->getParent()->getSSARegMap()->getRegClass(Op.VirtReg);
573 // Copy Op out of the vector and remove it, we're going to insert an
574 // explicit load for it.
576 Reuses.erase(Reuses.begin()+ro);
578 // Ok, we're going to try to reload the assigned physreg into the
579 // slot that we were supposed to in the first place. However, that
580 // register could hold a reuse. Check to see if it conflicts or
581 // would prefer us to use a different register.
582 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
583 MI, Spills, MaybeDeadStores, Rejected);
585 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
586 NewOp.StackSlot, AliasRC);
587 Spills.ClobberPhysReg(NewPhysReg);
588 Spills.ClobberPhysReg(NewOp.PhysRegReused);
590 // Any stores to this stack slot are not dead anymore.
591 MaybeDeadStores.erase(NewOp.StackSlot);
593 MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
595 Spills.addAvailable(NewOp.StackSlot, MI, NewPhysReg);
597 DEBUG(MachineBasicBlock::iterator MII = MI;
598 DOUT << '\t' << *prior(MII));
600 DOUT << "Reuse undone!\n";
603 // Finally, PhysReg is now available, go ahead and use it.
611 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
612 /// 'Rejected' set to remember which registers have been considered and
613 /// rejected for the reload. This avoids infinite looping in case like
616 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
617 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
619 /// sees r1 is taken by t2, tries t2's reload register r0
620 /// sees r0 is taken by t3, tries t3's reload register r1
621 /// sees r1 is taken by t2, tries t2's reload register r0 ...
622 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
623 AvailableSpills &Spills,
624 std::map<int, MachineInstr*> &MaybeDeadStores) {
625 SmallSet<unsigned, 8> Rejected;
626 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected);
632 /// InvalidateKills - MI is going to be deleted. If any of its operands are
633 /// marked kill, then invalidate the information.
634 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
635 std::vector<MachineOperand*> &KillOps) {
636 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
637 MachineOperand &MO = MI.getOperand(i);
638 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
640 unsigned Reg = MO.getReg();
641 if (KillOps[Reg] == &MO) {
648 /// UpdateKills - Track and update kill info. If a MI reads a register that is
649 /// marked kill, then it must be due to register reuse. Transfer the kill info
651 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
652 std::vector<MachineOperand*> &KillOps) {
653 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
654 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
655 MachineOperand &MO = MI.getOperand(i);
656 if (!MO.isReg() || !MO.isUse())
658 unsigned Reg = MO.getReg();
663 // That can't be right. Register is killed but not re-defined and it's
664 // being reused. Let's fix that.
665 KillOps[Reg]->unsetIsKill();
666 if (i < TID->numOperands &&
667 TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
668 // Unless it's a two-address operand, this is the new kill.
678 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
679 const MachineOperand &MO = MI.getOperand(i);
680 if (!MO.isReg() || !MO.isDef())
682 unsigned Reg = MO.getReg();
689 /// rewriteMBB - Keep track of which spills are available even after the
690 /// register allocator is done with them. If possible, avoid reloading vregs.
691 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
692 std::vector<MachineInstr*> &ReMatedMIs) {
693 DOUT << MBB.getBasicBlock()->getName() << ":\n";
695 // Spills - Keep track of which spilled values are available in physregs so
696 // that we can choose to reuse the physregs instead of emitting reloads.
697 AvailableSpills Spills(MRI, TII);
699 // MaybeDeadStores - When we need to write a value back into a stack slot,
700 // keep track of the inserted store. If the stack slot value is never read
701 // (because the value was used from some available register, for example), and
702 // subsequently stored to, the original store is dead. This map keeps track
703 // of inserted stores that are not used. If we see a subsequent store to the
704 // same stack slot, the original store is deleted.
705 std::map<int, MachineInstr*> MaybeDeadStores;
707 // Keep track of kill information.
708 BitVector RegKills(MRI->getNumRegs());
709 std::vector<MachineOperand*> KillOps;
710 KillOps.resize(MRI->getNumRegs(), NULL);
712 MachineFunction &MF = *MBB.getParent();
713 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
715 MachineInstr &MI = *MII;
716 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
717 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
720 bool BackTracked = false;
722 /// ReusedOperands - Keep track of operand reuse in case we need to undo
724 ReuseInfo ReusedOperands(MI, MRI);
726 // Loop over all of the implicit defs, clearing them from our available
728 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
730 // If this instruction is being rematerialized, just remove it!
732 if (TII->isTriviallyReMaterializable(&MI) ||
733 TII->isLoadFromStackSlot(&MI, FrameIdx)) {
735 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
736 MachineOperand &MO = MI.getOperand(i);
737 if (!MO.isRegister() || MO.getReg() == 0)
738 continue; // Ignore non-register operands.
739 if (MO.isDef() && !VRM.isReMaterialized(MO.getReg())) {
745 VRM.RemoveFromFoldedVirtMap(&MI);
746 ReMatedMIs.push_back(MI.removeFromParent());
747 goto ProcessNextInst;
751 if (TID->ImplicitDefs) {
752 const unsigned *ImpDef = TID->ImplicitDefs;
753 for ( ; *ImpDef; ++ImpDef) {
754 MF.setPhysRegUsed(*ImpDef);
755 ReusedOperands.markClobbered(*ImpDef);
756 Spills.ClobberPhysReg(*ImpDef);
760 // Process all of the spilled uses and all non spilled reg references.
761 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
762 MachineOperand &MO = MI.getOperand(i);
763 if (!MO.isRegister() || MO.getReg() == 0)
764 continue; // Ignore non-register operands.
766 if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
767 // Ignore physregs for spilling, but remember that it is used by this
769 MF.setPhysRegUsed(MO.getReg());
770 ReusedOperands.markClobbered(MO.getReg());
774 assert(MRegisterInfo::isVirtualRegister(MO.getReg()) &&
775 "Not a virtual or a physical register?");
777 unsigned VirtReg = MO.getReg();
778 if (!VRM.hasStackSlot(VirtReg)) {
779 // This virtual register was assigned a physreg!
780 unsigned Phys = VRM.getPhys(VirtReg);
781 MF.setPhysRegUsed(Phys);
783 ReusedOperands.markClobbered(Phys);
784 MI.getOperand(i).setReg(Phys);
788 // This virtual register is now known to be a spilled value.
790 continue; // Handle defs in the loop below (handle use&def here though)
792 bool doReMat = VRM.isReMaterialized(VirtReg);
793 int StackSlot = VRM.getStackSlot(VirtReg);
796 // Check to see if this stack slot is available.
797 MachineInstr *SSMI = NULL;
798 if ((PhysReg = Spills.getSpillSlotPhysReg(StackSlot, SSMI))) {
799 // This spilled operand might be part of a two-address operand. If this
800 // is the case, then changing it will necessarily require changing the
801 // def part of the instruction as well. However, in some cases, we
802 // aren't allowed to modify the reused register. If none of these cases
804 bool CanReuse = true;
805 int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
807 MI.getOperand(ti).isReg() &&
808 MI.getOperand(ti).getReg() == VirtReg) {
809 // Okay, we have a two address operand. We can reuse this physreg as
810 // long as we are allowed to clobber the value and there isn't an
811 // earlier def that has already clobbered the physreg.
812 CanReuse = Spills.canClobberPhysReg(StackSlot) &&
813 !ReusedOperands.isClobbered(PhysReg);
817 // If this stack slot value is already available, reuse it!
818 if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
819 DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
821 DOUT << "Reusing SS#" << StackSlot;
822 DOUT << " from physreg "
823 << MRI->getName(PhysReg) << " for vreg"
824 << VirtReg <<" instead of reloading into physreg "
825 << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
826 MI.getOperand(i).setReg(PhysReg);
829 Spills.addLastUse(PhysReg, &MI);
831 // The only technical detail we have is that we don't know that
832 // PhysReg won't be clobbered by a reloaded stack slot that occurs
833 // later in the instruction. In particular, consider 'op V1, V2'.
834 // If V1 is available in physreg R0, we would choose to reuse it
835 // here, instead of reloading it into the register the allocator
836 // indicated (say R1). However, V2 might have to be reloaded
837 // later, and it might indicate that it needs to live in R0. When
838 // this occurs, we need to have information available that
839 // indicates it is safe to use R1 for the reload instead of R0.
841 // To further complicate matters, we might conflict with an alias,
842 // or R0 and R1 might not be compatible with each other. In this
843 // case, we actually insert a reload for V1 in R1, ensuring that
844 // we can get at R0 or its alias.
845 ReusedOperands.addReuse(i, StackSlot, PhysReg,
846 VRM.getPhys(VirtReg), VirtReg);
848 // Only mark it clobbered if this is a use&def operand.
849 ReusedOperands.markClobbered(PhysReg);
854 // Otherwise we have a situation where we have a two-address instruction
855 // whose mod/ref operand needs to be reloaded. This reload is already
856 // available in some register "PhysReg", but if we used PhysReg as the
857 // operand to our 2-addr instruction, the instruction would modify
858 // PhysReg. This isn't cool if something later uses PhysReg and expects
859 // to get its initial value.
861 // To avoid this problem, and to avoid doing a load right after a store,
862 // we emit a copy from PhysReg into the designated register for this
864 unsigned DesignatedReg = VRM.getPhys(VirtReg);
865 assert(DesignatedReg && "Must map virtreg to physreg!");
867 // Note that, if we reused a register for a previous operand, the
868 // register we want to reload into might not actually be
869 // available. If this occurs, use the register indicated by the
871 if (ReusedOperands.hasReuses())
872 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
873 Spills, MaybeDeadStores);
875 // If the mapped designated register is actually the physreg we have
876 // incoming, we don't need to inserted a dead copy.
877 if (DesignatedReg == PhysReg) {
878 // If this stack slot value is already available, reuse it!
879 if (StackSlot > VirtRegMap::MAX_STACK_SLOT)
880 DOUT << "Reusing RM#" << StackSlot-VirtRegMap::MAX_STACK_SLOT-1;
882 DOUT << "Reusing SS#" << StackSlot;
883 DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
885 << " instead of reloading into same physreg.\n";
886 MI.getOperand(i).setReg(PhysReg);
887 ReusedOperands.markClobbered(PhysReg);
892 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(VirtReg);
893 MF.setPhysRegUsed(DesignatedReg);
894 ReusedOperands.markClobbered(DesignatedReg);
895 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC);
897 // Extend the live range of the MI that last kill the register if
899 MachineInstr *CopyMI = prior(MII);
900 UpdateKills(*CopyMI, RegKills, KillOps);
901 Spills.addLastUse(PhysReg, CopyMI);
903 // This invalidates DesignatedReg.
904 Spills.ClobberPhysReg(DesignatedReg);
906 Spills.addAvailable(StackSlot, &MI, DesignatedReg);
907 MI.getOperand(i).setReg(DesignatedReg);
908 DOUT << '\t' << *prior(MII);
913 // Otherwise, reload it and remember that we have it.
914 PhysReg = VRM.getPhys(VirtReg);
915 assert(PhysReg && "Must map virtreg to physreg!");
916 const TargetRegisterClass* RC = MF.getSSARegMap()->getRegClass(VirtReg);
918 // Note that, if we reused a register for a previous operand, the
919 // register we want to reload into might not actually be
920 // available. If this occurs, use the register indicated by the
922 if (ReusedOperands.hasReuses())
923 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
924 Spills, MaybeDeadStores);
926 MF.setPhysRegUsed(PhysReg);
927 ReusedOperands.markClobbered(PhysReg);
929 MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
932 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, StackSlot, RC);
935 // This invalidates PhysReg.
936 Spills.ClobberPhysReg(PhysReg);
938 // Any stores to this stack slot are not dead anymore.
940 MaybeDeadStores.erase(StackSlot);
941 Spills.addAvailable(StackSlot, &MI, PhysReg);
942 // Assumes this is the last use. IsKill will be unset if reg is reused
943 // unless it's a two-address operand.
944 if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
945 MI.getOperand(i).setIsKill();
946 MI.getOperand(i).setReg(PhysReg);
947 UpdateKills(*prior(MII), RegKills, KillOps);
948 DOUT << '\t' << *prior(MII);
953 // If we have folded references to memory operands, make sure we clear all
954 // physical registers that may contain the value of the spilled virtual
956 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
957 DOUT << "Folded vreg: " << I->second.first << " MR: "
959 unsigned VirtReg = I->second.first;
960 VirtRegMap::ModRef MR = I->second.second;
961 if (!VRM.hasStackSlot(VirtReg)) {
962 DOUT << ": No stack slot!\n";
965 int SS = VRM.getStackSlot(VirtReg);
966 DOUT << " - StackSlot: " << SS << "\n";
968 // If this folded instruction is just a use, check to see if it's a
969 // straight load from the virt reg slot.
970 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
972 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
973 if (FrameIdx == SS) {
974 // If this spill slot is available, turn it into a copy (or nothing)
975 // instead of leaving it as a load!
976 MachineInstr *SSMI = NULL;
977 if (unsigned InReg = Spills.getSpillSlotPhysReg(SS, SSMI)) {
978 DOUT << "Promoted Load To Copy: " << MI;
979 if (DestReg != InReg) {
980 MRI->copyRegToReg(MBB, &MI, DestReg, InReg,
981 MF.getSSARegMap()->getRegClass(VirtReg));
982 // Revisit the copy so we make sure to notice the effects of the
983 // operation on the destreg (either needing to RA it if it's
984 // virtual or needing to clobber any values if it's physical).
986 --NextMII; // backtrack to the copy.
989 DOUT << "Removing now-noop copy: " << MI;
991 if (NextMII != MBB.end()) {
992 // If NextMII uses InReg and the use is not a two address
993 // operand, mark it killed.
994 int UIdx = NextMII->findRegisterUseOperandIdx(InReg);
996 Spills.addLastUse(InReg, &(*NextMII));
999 VRM.RemoveFromFoldedVirtMap(&MI);
1002 goto ProcessNextInst;
1008 // If this reference is not a use, any previous store is now dead.
1009 // Otherwise, the store to this stack slot is not dead anymore.
1010 std::map<int, MachineInstr*>::iterator MDSI = MaybeDeadStores.find(SS);
1011 if (MDSI != MaybeDeadStores.end()) {
1012 if (MR & VirtRegMap::isRef) // Previous store is not dead.
1013 MaybeDeadStores.erase(MDSI);
1015 // If we get here, the store is dead, nuke it now.
1016 assert(VirtRegMap::isMod && "Can't be modref!");
1017 DOUT << "Removed dead store:\t" << *MDSI->second;
1018 InvalidateKills(*MDSI->second, RegKills, KillOps);
1019 MBB.erase(MDSI->second);
1020 VRM.RemoveFromFoldedVirtMap(MDSI->second);
1021 MaybeDeadStores.erase(MDSI);
1026 // If the spill slot value is available, and this is a new definition of
1027 // the value, the value is not available anymore.
1028 if (MR & VirtRegMap::isMod) {
1029 // Notice that the value in this stack slot has been modified.
1030 Spills.ModifyStackSlot(SS);
1032 // If this is *just* a mod of the value, check to see if this is just a
1033 // store to the spill slot (i.e. the spill got merged into the copy). If
1034 // so, realize that the vreg is available now, and add the store to the
1035 // MaybeDeadStore info.
1037 if (!(MR & VirtRegMap::isRef)) {
1038 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1039 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1040 "Src hasn't been allocated yet?");
1041 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
1042 // this as a potentially dead store in case there is a subsequent
1043 // store into the stack slot without a read from it.
1044 MaybeDeadStores[StackSlot] = &MI;
1046 // If the stack slot value was previously available in some other
1047 // register, change it now. Otherwise, make the register available,
1049 Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1055 // Process all of the spilled defs.
1056 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1057 MachineOperand &MO = MI.getOperand(i);
1058 if (MO.isRegister() && MO.getReg() && MO.isDef()) {
1059 unsigned VirtReg = MO.getReg();
1061 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1062 // Check to see if this is a noop copy. If so, eliminate the
1063 // instruction before considering the dest reg to be changed.
1065 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1067 DOUT << "Removing now-noop copy: " << MI;
1068 Spills.removeLastUse(Src, &MI);
1071 VRM.RemoveFromFoldedVirtMap(&MI);
1072 Spills.disallowClobberPhysReg(VirtReg);
1073 goto ProcessNextInst;
1076 // If it's not a no-op copy, it clobbers the value in the destreg.
1077 Spills.ClobberPhysReg(VirtReg);
1078 ReusedOperands.markClobbered(VirtReg);
1080 // Check to see if this instruction is a load from a stack slot into
1081 // a register. If so, this provides the stack slot value in the reg.
1083 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1084 assert(DestReg == VirtReg && "Unknown load situation!");
1086 // Otherwise, if it wasn't available, remember that it is now!
1087 Spills.addAvailable(FrameIdx, &MI, DestReg);
1088 goto ProcessNextInst;
1094 // The only vregs left are stack slot definitions.
1095 int StackSlot = VRM.getStackSlot(VirtReg);
1096 const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(VirtReg);
1098 // If this def is part of a two-address operand, make sure to execute
1099 // the store from the correct physical register.
1101 int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
1103 PhysReg = MI.getOperand(TiedOp).getReg();
1105 PhysReg = VRM.getPhys(VirtReg);
1106 if (ReusedOperands.isClobbered(PhysReg)) {
1107 // Another def has taken the assigned physreg. It must have been a
1108 // use&def which got it due to reuse. Undo the reuse!
1109 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1110 Spills, MaybeDeadStores);
1114 MF.setPhysRegUsed(PhysReg);
1115 ReusedOperands.markClobbered(PhysReg);
1116 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, StackSlot, RC);
1117 DOUT << "Store:\t" << *next(MII);
1118 MI.getOperand(i).setReg(PhysReg);
1120 // If there is a dead store to this stack slot, nuke it now.
1121 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1123 DOUT << "Removed dead store:\t" << *LastStore;
1125 InvalidateKills(*LastStore, RegKills, KillOps);
1126 MBB.erase(LastStore);
1127 VRM.RemoveFromFoldedVirtMap(LastStore);
1129 LastStore = next(MII);
1131 // If the stack slot value was previously available in some other
1132 // register, change it now. Otherwise, make the register available,
1134 Spills.ModifyStackSlot(StackSlot);
1135 Spills.ClobberPhysReg(PhysReg);
1136 Spills.addAvailable(StackSlot, LastStore, PhysReg);
1139 // Check to see if this is a noop copy. If so, eliminate the
1140 // instruction before considering the dest reg to be changed.
1143 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1145 DOUT << "Removing now-noop copy: " << MI;
1146 Spills.removeLastUse(Src, &MI);
1149 VRM.RemoveFromFoldedVirtMap(&MI);
1150 goto ProcessNextInst;
1156 if (!Erased && !BackTracked)
1157 for (MachineBasicBlock::iterator II = MI; II != NextMII; ++II)
1158 UpdateKills(*II, RegKills, KillOps);
1164 llvm::Spiller* llvm::createSpiller() {
1165 switch (SpillerOpt) {
1166 default: assert(0 && "Unreachable!");
1168 return new LocalSpiller();
1170 return new SimpleSpiller();