1 //===-- llvm/CodeGen/VirtRegMap.cpp - Virtual Register Map ----------------===//
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 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/MachineRegisterInfo.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(NumDRM , "Number of re-materializable defs elided");
40 STATISTIC(NumStores, "Number of stores added");
41 STATISTIC(NumLoads , "Number of loads added");
42 STATISTIC(NumReused, "Number of values reused");
43 STATISTIC(NumDSE , "Number of dead stores elided");
44 STATISTIC(NumDCE , "Number of copies elided");
47 enum SpillerName { simple, local };
49 static cl::opt<SpillerName>
51 cl::desc("Spiller to use: (default: local)"),
53 cl::values(clEnumVal(simple, " simple spiller"),
54 clEnumVal(local, " local spiller"),
59 //===----------------------------------------------------------------------===//
60 // VirtRegMap implementation
61 //===----------------------------------------------------------------------===//
63 VirtRegMap::VirtRegMap(MachineFunction &mf)
64 : TII(*mf.getTarget().getInstrInfo()), MF(mf),
65 Virt2PhysMap(NO_PHYS_REG), Virt2StackSlotMap(NO_STACK_SLOT),
66 Virt2ReMatIdMap(NO_STACK_SLOT), Virt2SplitMap(0),
67 Virt2SplitKillMap(0), ReMatMap(NULL), ReMatId(MAX_STACK_SLOT+1) {
71 void VirtRegMap::grow() {
72 unsigned LastVirtReg = MF.getRegInfo().getLastVirtReg();
73 Virt2PhysMap.grow(LastVirtReg);
74 Virt2StackSlotMap.grow(LastVirtReg);
75 Virt2ReMatIdMap.grow(LastVirtReg);
76 Virt2SplitMap.grow(LastVirtReg);
77 Virt2SplitKillMap.grow(LastVirtReg);
78 ReMatMap.grow(LastVirtReg);
81 int VirtRegMap::assignVirt2StackSlot(unsigned virtReg) {
82 assert(MRegisterInfo::isVirtualRegister(virtReg));
83 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
84 "attempt to assign stack slot to already spilled register");
85 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(virtReg);
86 int frameIndex = MF.getFrameInfo()->CreateStackObject(RC->getSize(),
88 Virt2StackSlotMap[virtReg] = frameIndex;
93 void VirtRegMap::assignVirt2StackSlot(unsigned virtReg, int frameIndex) {
94 assert(MRegisterInfo::isVirtualRegister(virtReg));
95 assert(Virt2StackSlotMap[virtReg] == NO_STACK_SLOT &&
96 "attempt to assign stack slot to already spilled register");
97 assert((frameIndex >= 0 ||
98 (frameIndex >= MF.getFrameInfo()->getObjectIndexBegin())) &&
99 "illegal fixed frame index");
100 Virt2StackSlotMap[virtReg] = frameIndex;
103 int VirtRegMap::assignVirtReMatId(unsigned virtReg) {
104 assert(MRegisterInfo::isVirtualRegister(virtReg));
105 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
106 "attempt to assign re-mat id to already spilled register");
107 Virt2ReMatIdMap[virtReg] = ReMatId;
111 void VirtRegMap::assignVirtReMatId(unsigned virtReg, int id) {
112 assert(MRegisterInfo::isVirtualRegister(virtReg));
113 assert(Virt2ReMatIdMap[virtReg] == NO_STACK_SLOT &&
114 "attempt to assign re-mat id to already spilled register");
115 Virt2ReMatIdMap[virtReg] = id;
118 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *OldMI,
119 MachineInstr *NewMI, ModRef MRInfo) {
120 // Move previous memory references folded to new instruction.
121 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(NewMI);
122 for (MI2VirtMapTy::iterator I = MI2VirtMap.lower_bound(OldMI),
123 E = MI2VirtMap.end(); I != E && I->first == OldMI; ) {
124 MI2VirtMap.insert(IP, std::make_pair(NewMI, I->second));
125 MI2VirtMap.erase(I++);
128 // add new memory reference
129 MI2VirtMap.insert(IP, std::make_pair(NewMI, std::make_pair(VirtReg, MRInfo)));
132 void VirtRegMap::virtFolded(unsigned VirtReg, MachineInstr *MI, ModRef MRInfo) {
133 MI2VirtMapTy::iterator IP = MI2VirtMap.lower_bound(MI);
134 MI2VirtMap.insert(IP, std::make_pair(MI, 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.getRegInfo().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.getRegInfo().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.isAssignedReg(VirtReg)) {
198 int StackSlot = VRM.getStackSlot(VirtReg);
199 const TargetRegisterClass* RC =
200 MF.getRegInfo().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, true,
217 MF.getRegInfo().setPhysRegUsed(PhysReg);
218 MI.getOperand(i).setReg(PhysReg);
220 MF.getRegInfo().setPhysRegUsed(MO.getReg());
231 //===----------------------------------------------------------------------===//
232 // Local Spiller Implementation
233 //===----------------------------------------------------------------------===//
236 class AvailableSpills;
238 /// LocalSpiller - This spiller does a simple pass over the machine basic
239 /// block to attempt to keep spills in registers as much as possible for
240 /// blocks that have low register pressure (the vreg may be spilled due to
241 /// register pressure in other blocks).
242 class VISIBILITY_HIDDEN LocalSpiller : public Spiller {
243 MachineRegisterInfo *RegInfo;
244 const MRegisterInfo *MRI;
245 const TargetInstrInfo *TII;
247 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM) {
248 RegInfo = &MF.getRegInfo();
249 MRI = MF.getTarget().getRegisterInfo();
250 TII = MF.getTarget().getInstrInfo();
251 DOUT << "\n**** Local spiller rewriting function '"
252 << MF.getFunction()->getName() << "':\n";
253 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
257 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
259 RewriteMBB(*MBB, VRM);
261 DOUT << "**** Post Machine Instrs ****\n";
267 bool PrepForUnfoldOpti(MachineBasicBlock &MBB,
268 MachineBasicBlock::iterator &MII,
269 std::vector<MachineInstr*> &MaybeDeadStores,
270 AvailableSpills &Spills, BitVector &RegKills,
271 std::vector<MachineOperand*> &KillOps,
273 void SpillRegToStackSlot(MachineBasicBlock &MBB,
274 MachineBasicBlock::iterator &MII,
275 int Idx, unsigned PhysReg, int StackSlot,
276 const TargetRegisterClass *RC,
277 bool isAvailable, MachineInstr *&LastStore,
278 AvailableSpills &Spills,
279 SmallSet<MachineInstr*, 4> &ReMatDefs,
281 std::vector<MachineOperand*> &KillOps,
283 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM);
287 /// AvailableSpills - As the local spiller is scanning and rewriting an MBB from
288 /// top down, keep track of which spills slots or remat are available in each
291 /// Note that not all physregs are created equal here. In particular, some
292 /// physregs are reloads that we are allowed to clobber or ignore at any time.
293 /// Other physregs are values that the register allocated program is using that
294 /// we cannot CHANGE, but we can read if we like. We keep track of this on a
295 /// per-stack-slot / remat id basis as the low bit in the value of the
296 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
297 /// this bit and addAvailable sets it if.
299 class VISIBILITY_HIDDEN AvailableSpills {
300 const MRegisterInfo *MRI;
301 const TargetInstrInfo *TII;
303 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
304 // or remat'ed virtual register values that are still available, due to being
305 // loaded or stored to, but not invalidated yet.
306 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
308 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
309 // indicating which stack slot values are currently held by a physreg. This
310 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
311 // physreg is modified.
312 std::multimap<unsigned, int> PhysRegsAvailable;
314 void disallowClobberPhysRegOnly(unsigned PhysReg);
316 void ClobberPhysRegOnly(unsigned PhysReg);
318 AvailableSpills(const MRegisterInfo *mri, const TargetInstrInfo *tii)
319 : MRI(mri), TII(tii) {
322 const MRegisterInfo *getRegInfo() const { return MRI; }
324 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
325 /// available in a physical register, return that PhysReg, otherwise
327 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
328 std::map<int, unsigned>::const_iterator I =
329 SpillSlotsOrReMatsAvailable.find(Slot);
330 if (I != SpillSlotsOrReMatsAvailable.end()) {
331 return I->second >> 1; // Remove the CanClobber bit.
336 /// addAvailable - Mark that the specified stack slot / remat is available in
337 /// the specified physreg. If CanClobber is true, the physreg can be modified
338 /// at any time without changing the semantics of the program.
339 void addAvailable(int SlotOrReMat, MachineInstr *MI, unsigned Reg,
340 bool CanClobber = true) {
341 // If this stack slot is thought to be available in some other physreg,
342 // remove its record.
343 ModifyStackSlotOrReMat(SlotOrReMat);
345 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
346 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) | (unsigned)CanClobber;
348 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
349 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
351 DOUT << "Remembering SS#" << SlotOrReMat;
352 DOUT << " in physreg " << MRI->getName(Reg) << "\n";
355 /// canClobberPhysReg - Return true if the spiller is allowed to change the
356 /// value of the specified stackslot register if it desires. The specified
357 /// stack slot must be available in a physreg for this query to make sense.
358 bool canClobberPhysReg(int SlotOrReMat) const {
359 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
360 "Value not available!");
361 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
364 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
365 /// stackslot register. The register is still available but is no longer
366 /// allowed to be modifed.
367 void disallowClobberPhysReg(unsigned PhysReg);
369 /// ClobberPhysReg - This is called when the specified physreg changes
370 /// value. We use this to invalidate any info about stuff that lives in
371 /// it and any of its aliases.
372 void ClobberPhysReg(unsigned PhysReg);
374 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
375 /// slot changes. This removes information about which register the previous
376 /// value for this slot lives in (as the previous value is dead now).
377 void ModifyStackSlotOrReMat(int SlotOrReMat);
381 /// disallowClobberPhysRegOnly - 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 AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
385 std::multimap<unsigned, int>::iterator I =
386 PhysRegsAvailable.lower_bound(PhysReg);
387 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
388 int SlotOrReMat = I->second;
390 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
391 "Bidirectional map mismatch!");
392 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
393 DOUT << "PhysReg " << MRI->getName(PhysReg)
394 << " copied, it is available for use but can no longer be modified\n";
398 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
399 /// stackslot register and its aliases. The register and its aliases may
400 /// still available but is no longer allowed to be modifed.
401 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
402 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
403 disallowClobberPhysRegOnly(*AS);
404 disallowClobberPhysRegOnly(PhysReg);
407 /// ClobberPhysRegOnly - This is called when the specified physreg changes
408 /// value. We use this to invalidate any info about stuff we thing lives in it.
409 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
410 std::multimap<unsigned, int>::iterator I =
411 PhysRegsAvailable.lower_bound(PhysReg);
412 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
413 int SlotOrReMat = I->second;
414 PhysRegsAvailable.erase(I++);
415 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
416 "Bidirectional map mismatch!");
417 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
418 DOUT << "PhysReg " << MRI->getName(PhysReg)
419 << " clobbered, invalidating ";
420 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
421 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
423 DOUT << "SS#" << SlotOrReMat << "\n";
427 /// ClobberPhysReg - This is called when the specified physreg changes
428 /// value. We use this to invalidate any info about stuff we thing lives in
429 /// it and any of its aliases.
430 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
431 for (const unsigned *AS = MRI->getAliasSet(PhysReg); *AS; ++AS)
432 ClobberPhysRegOnly(*AS);
433 ClobberPhysRegOnly(PhysReg);
436 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
437 /// slot changes. This removes information about which register the previous
438 /// value for this slot lives in (as the previous value is dead now).
439 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
440 std::map<int, unsigned>::iterator It =
441 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
442 if (It == SpillSlotsOrReMatsAvailable.end()) return;
443 unsigned Reg = It->second >> 1;
444 SpillSlotsOrReMatsAvailable.erase(It);
446 // This register may hold the value of multiple stack slots, only remove this
447 // stack slot from the set of values the register contains.
448 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
450 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
451 "Map inverse broken!");
452 if (I->second == SlotOrReMat) break;
454 PhysRegsAvailable.erase(I);
459 /// InvalidateKills - MI is going to be deleted. If any of its operands are
460 /// marked kill, then invalidate the information.
461 static void InvalidateKills(MachineInstr &MI, BitVector &RegKills,
462 std::vector<MachineOperand*> &KillOps,
463 SmallVector<unsigned, 2> *KillRegs = NULL) {
464 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
465 MachineOperand &MO = MI.getOperand(i);
466 if (!MO.isRegister() || !MO.isUse() || !MO.isKill())
468 unsigned Reg = MO.getReg();
470 KillRegs->push_back(Reg);
471 if (KillOps[Reg] == &MO) {
478 /// InvalidateKill - A MI that defines the specified register is being deleted,
479 /// invalidate the register kill information.
480 static void InvalidateKill(unsigned Reg, BitVector &RegKills,
481 std::vector<MachineOperand*> &KillOps) {
483 KillOps[Reg]->setIsKill(false);
489 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
490 /// (since it's spill instruction is removed), mark it isDead. Also checks if
491 /// the def MI has other definition operands that are not dead. Returns it by
493 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
494 MachineInstr &NewDef, unsigned Reg,
496 // Due to remat, it's possible this reg isn't being reused. That is,
497 // the def of this reg (by prev MI) is now dead.
498 MachineInstr *DefMI = I;
499 MachineOperand *DefOp = NULL;
500 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
501 MachineOperand &MO = DefMI->getOperand(i);
502 if (MO.isRegister() && MO.isDef()) {
503 if (MO.getReg() == Reg)
505 else if (!MO.isDead())
512 bool FoundUse = false, Done = false;
513 MachineBasicBlock::iterator E = NewDef;
515 for (; !Done && I != E; ++I) {
516 MachineInstr *NMI = I;
517 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
518 MachineOperand &MO = NMI->getOperand(j);
519 if (!MO.isRegister() || MO.getReg() != Reg)
523 Done = true; // Stop after scanning all the operands of this MI.
534 /// UpdateKills - Track and update kill info. If a MI reads a register that is
535 /// marked kill, then it must be due to register reuse. Transfer the kill info
537 static void UpdateKills(MachineInstr &MI, BitVector &RegKills,
538 std::vector<MachineOperand*> &KillOps) {
539 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
540 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
541 MachineOperand &MO = MI.getOperand(i);
542 if (!MO.isRegister() || !MO.isUse())
544 unsigned Reg = MO.getReg();
549 // That can't be right. Register is killed but not re-defined and it's
550 // being reused. Let's fix that.
551 KillOps[Reg]->setIsKill(false);
554 if (i < TID->numOperands &&
555 TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
556 // Unless it's a two-address operand, this is the new kill.
565 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
566 const MachineOperand &MO = MI.getOperand(i);
567 if (!MO.isRegister() || !MO.isDef())
569 unsigned Reg = MO.getReg();
576 // ReusedOp - For each reused operand, we keep track of a bit of information, in
577 // case we need to rollback upon processing a new operand. See comments below.
580 // The MachineInstr operand that reused an available value.
583 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
584 unsigned StackSlotOrReMat;
586 // PhysRegReused - The physical register the value was available in.
587 unsigned PhysRegReused;
589 // AssignedPhysReg - The physreg that was assigned for use by the reload.
590 unsigned AssignedPhysReg;
592 // VirtReg - The virtual register itself.
595 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
597 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
598 AssignedPhysReg(apr), VirtReg(vreg) {}
601 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
602 /// is reused instead of reloaded.
603 class VISIBILITY_HIDDEN ReuseInfo {
605 std::vector<ReusedOp> Reuses;
606 BitVector PhysRegsClobbered;
608 ReuseInfo(MachineInstr &mi, const MRegisterInfo *mri) : MI(mi) {
609 PhysRegsClobbered.resize(mri->getNumRegs());
612 bool hasReuses() const {
613 return !Reuses.empty();
616 /// addReuse - If we choose to reuse a virtual register that is already
617 /// available instead of reloading it, remember that we did so.
618 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
619 unsigned PhysRegReused, unsigned AssignedPhysReg,
621 // If the reload is to the assigned register anyway, no undo will be
623 if (PhysRegReused == AssignedPhysReg) return;
625 // Otherwise, remember this.
626 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
627 AssignedPhysReg, VirtReg));
630 void markClobbered(unsigned PhysReg) {
631 PhysRegsClobbered.set(PhysReg);
634 bool isClobbered(unsigned PhysReg) const {
635 return PhysRegsClobbered.test(PhysReg);
638 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
639 /// is some other operand that is using the specified register, either pick
640 /// a new register to use, or evict the previous reload and use this reg.
641 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
642 AvailableSpills &Spills,
643 std::vector<MachineInstr*> &MaybeDeadStores,
644 SmallSet<unsigned, 8> &Rejected,
646 std::vector<MachineOperand*> &KillOps,
648 if (Reuses.empty()) return PhysReg; // This is most often empty.
650 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
651 ReusedOp &Op = Reuses[ro];
652 // If we find some other reuse that was supposed to use this register
653 // exactly for its reload, we can change this reload to use ITS reload
654 // register. That is, unless its reload register has already been
655 // considered and subsequently rejected because it has also been reused
656 // by another operand.
657 if (Op.PhysRegReused == PhysReg &&
658 Rejected.count(Op.AssignedPhysReg) == 0) {
659 // Yup, use the reload register that we didn't use before.
660 unsigned NewReg = Op.AssignedPhysReg;
661 Rejected.insert(PhysReg);
662 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
663 RegKills, KillOps, VRM);
665 // Otherwise, we might also have a problem if a previously reused
666 // value aliases the new register. If so, codegen the previous reload
668 unsigned PRRU = Op.PhysRegReused;
669 const MRegisterInfo *MRI = Spills.getRegInfo();
670 if (MRI->areAliases(PRRU, PhysReg)) {
671 // Okay, we found out that an alias of a reused register
672 // was used. This isn't good because it means we have
673 // to undo a previous reuse.
674 MachineBasicBlock *MBB = MI->getParent();
675 const TargetRegisterClass *AliasRC =
676 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
678 // Copy Op out of the vector and remove it, we're going to insert an
679 // explicit load for it.
681 Reuses.erase(Reuses.begin()+ro);
683 // Ok, we're going to try to reload the assigned physreg into the
684 // slot that we were supposed to in the first place. However, that
685 // register could hold a reuse. Check to see if it conflicts or
686 // would prefer us to use a different register.
687 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
688 MI, Spills, MaybeDeadStores,
689 Rejected, RegKills, KillOps, VRM);
691 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
692 MRI->reMaterialize(*MBB, MI, NewPhysReg,
693 VRM.getReMaterializedMI(NewOp.VirtReg));
696 MRI->loadRegFromStackSlot(*MBB, MI, NewPhysReg,
697 NewOp.StackSlotOrReMat, AliasRC);
698 // Any stores to this stack slot are not dead anymore.
699 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
702 Spills.ClobberPhysReg(NewPhysReg);
703 Spills.ClobberPhysReg(NewOp.PhysRegReused);
705 MI->getOperand(NewOp.Operand).setReg(NewPhysReg);
707 Spills.addAvailable(NewOp.StackSlotOrReMat, MI, NewPhysReg);
708 MachineBasicBlock::iterator MII = MI;
710 UpdateKills(*MII, RegKills, KillOps);
711 DOUT << '\t' << *MII;
713 DOUT << "Reuse undone!\n";
716 // Finally, PhysReg is now available, go ahead and use it.
724 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
725 /// 'Rejected' set to remember which registers have been considered and
726 /// rejected for the reload. This avoids infinite looping in case like
729 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
730 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
732 /// sees r1 is taken by t2, tries t2's reload register r0
733 /// sees r0 is taken by t3, tries t3's reload register r1
734 /// sees r1 is taken by t2, tries t2's reload register r0 ...
735 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
736 AvailableSpills &Spills,
737 std::vector<MachineInstr*> &MaybeDeadStores,
739 std::vector<MachineOperand*> &KillOps,
741 SmallSet<unsigned, 8> Rejected;
742 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
743 RegKills, KillOps, VRM);
748 /// PrepForUnfoldOpti - Turn a store folding instruction into a load folding
749 /// instruction. e.g.
751 /// movl %eax, -32(%ebp)
752 /// movl -36(%ebp), %eax
753 /// orl %eax, -32(%ebp)
756 /// orl -36(%ebp), %eax
757 /// mov %eax, -32(%ebp)
758 /// This enables unfolding optimization for a subsequent instruction which will
759 /// also eliminate the newly introduced store instruction.
760 bool LocalSpiller::PrepForUnfoldOpti(MachineBasicBlock &MBB,
761 MachineBasicBlock::iterator &MII,
762 std::vector<MachineInstr*> &MaybeDeadStores,
763 AvailableSpills &Spills,
765 std::vector<MachineOperand*> &KillOps,
767 MachineFunction &MF = *MBB.getParent();
768 MachineInstr &MI = *MII;
769 unsigned UnfoldedOpc = 0;
770 unsigned UnfoldPR = 0;
771 unsigned UnfoldVR = 0;
772 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
773 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
774 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
775 // Only transform a MI that folds a single register.
778 UnfoldVR = I->second.first;
779 VirtRegMap::ModRef MR = I->second.second;
780 if (VRM.isAssignedReg(UnfoldVR))
782 // If this reference is not a use, any previous store is now dead.
783 // Otherwise, the store to this stack slot is not dead anymore.
784 FoldedSS = VRM.getStackSlot(UnfoldVR);
785 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
786 if (DeadStore && (MR & VirtRegMap::isModRef)) {
787 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
789 DeadStore->findRegisterUseOperandIdx(PhysReg, true) == -1)
792 UnfoldedOpc = MRI->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
800 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
801 MachineOperand &MO = MI.getOperand(i);
802 if (!MO.isRegister() || MO.getReg() == 0 || !MO.isUse())
804 unsigned VirtReg = MO.getReg();
805 if (MRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
807 if (VRM.isAssignedReg(VirtReg)) {
808 unsigned PhysReg = VRM.getPhys(VirtReg);
809 if (PhysReg && MRI->regsOverlap(PhysReg, UnfoldPR))
811 } else if (VRM.isReMaterialized(VirtReg))
813 int SS = VRM.getStackSlot(VirtReg);
814 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
816 if (MRI->regsOverlap(PhysReg, UnfoldPR))
820 PhysReg = VRM.getPhys(VirtReg);
821 if (!MRI->regsOverlap(PhysReg, UnfoldPR))
824 // Ok, we'll need to reload the value into a register which makes
825 // it impossible to perform the store unfolding optimization later.
826 // Let's see if it is possible to fold the load if the store is
827 // unfolded. This allows us to perform the store unfolding
829 SmallVector<MachineInstr*, 4> NewMIs;
830 if (MRI->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
831 assert(NewMIs.size() == 1);
832 MachineInstr *NewMI = NewMIs.back();
834 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg);
836 SmallVector<unsigned, 2> Ops;
838 MachineInstr *FoldedMI = MRI->foldMemoryOperand(NewMI, Ops, SS);
840 if (!VRM.hasPhys(UnfoldVR))
841 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
842 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
843 MII = MBB.insert(MII, FoldedMI);
844 VRM.RemoveMachineInstrFromMaps(&MI);
854 /// findSuperReg - Find the SubReg's super-register of given register class
855 /// where its SubIdx sub-register is SubReg.
856 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
857 unsigned SubIdx, const MRegisterInfo *MRI) {
858 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
861 if (MRI->getSubReg(Reg, SubIdx) == SubReg)
867 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
868 /// the last store to the same slot is now dead. If so, remove the last store.
869 void LocalSpiller::SpillRegToStackSlot(MachineBasicBlock &MBB,
870 MachineBasicBlock::iterator &MII,
871 int Idx, unsigned PhysReg, int StackSlot,
872 const TargetRegisterClass *RC,
873 bool isAvailable, MachineInstr *&LastStore,
874 AvailableSpills &Spills,
875 SmallSet<MachineInstr*, 4> &ReMatDefs,
877 std::vector<MachineOperand*> &KillOps,
879 MRI->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
880 DOUT << "Store:\t" << *next(MII);
882 // If there is a dead store to this stack slot, nuke it now.
884 DOUT << "Removed dead store:\t" << *LastStore;
886 SmallVector<unsigned, 2> KillRegs;
887 InvalidateKills(*LastStore, RegKills, KillOps, &KillRegs);
888 MachineBasicBlock::iterator PrevMII = LastStore;
889 bool CheckDef = PrevMII != MBB.begin();
892 MBB.erase(LastStore);
893 VRM.RemoveMachineInstrFromMaps(LastStore);
895 // Look at defs of killed registers on the store. Mark the defs
896 // as dead since the store has been deleted and they aren't
898 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
899 bool HasOtherDef = false;
900 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
901 MachineInstr *DeadDef = PrevMII;
902 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
903 // FIXME: This assumes a remat def does not have side
906 VRM.RemoveMachineInstrFromMaps(DeadDef);
914 LastStore = next(MII);
916 // If the stack slot value was previously available in some other
917 // register, change it now. Otherwise, make the register available,
919 Spills.ModifyStackSlotOrReMat(StackSlot);
920 Spills.ClobberPhysReg(PhysReg);
921 Spills.addAvailable(StackSlot, LastStore, PhysReg, isAvailable);
925 /// rewriteMBB - Keep track of which spills are available even after the
926 /// register allocator is done with them. If possible, avid reloading vregs.
927 void LocalSpiller::RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM) {
928 DOUT << MBB.getBasicBlock()->getName() << ":\n";
930 MachineFunction &MF = *MBB.getParent();
932 // Spills - Keep track of which spilled values are available in physregs so
933 // that we can choose to reuse the physregs instead of emitting reloads.
934 AvailableSpills Spills(MRI, TII);
936 // MaybeDeadStores - When we need to write a value back into a stack slot,
937 // keep track of the inserted store. If the stack slot value is never read
938 // (because the value was used from some available register, for example), and
939 // subsequently stored to, the original store is dead. This map keeps track
940 // of inserted stores that are not used. If we see a subsequent store to the
941 // same stack slot, the original store is deleted.
942 std::vector<MachineInstr*> MaybeDeadStores;
943 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
945 // ReMatDefs - These are rematerializable def MIs which are not deleted.
946 SmallSet<MachineInstr*, 4> ReMatDefs;
948 // Keep track of kill information.
949 BitVector RegKills(MRI->getNumRegs());
950 std::vector<MachineOperand*> KillOps;
951 KillOps.resize(MRI->getNumRegs(), NULL);
953 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
955 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
957 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
959 bool BackTracked = false;
960 if (PrepForUnfoldOpti(MBB, MII,
961 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
964 MachineInstr &MI = *MII;
965 const TargetInstrDescriptor *TID = MI.getInstrDescriptor();
967 // Insert restores here if asked to.
968 if (VRM.isRestorePt(&MI)) {
969 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
970 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
971 unsigned VirtReg = RestoreRegs[i];
972 if (!VRM.getPreSplitReg(VirtReg))
973 continue; // Split interval spilled again.
974 unsigned Phys = VRM.getPhys(VirtReg);
975 RegInfo->setPhysRegUsed(Phys);
976 if (VRM.isReMaterialized(VirtReg)) {
977 MRI->reMaterialize(MBB, &MI, Phys,
978 VRM.getReMaterializedMI(VirtReg));
981 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
982 MRI->loadRegFromStackSlot(MBB, &MI, Phys, VRM.getStackSlot(VirtReg),
986 // This invalidates Phys.
987 Spills.ClobberPhysReg(Phys);
988 UpdateKills(*prior(MII), RegKills, KillOps);
989 DOUT << '\t' << *prior(MII);
993 // Insert spills here if asked to.
994 if (VRM.isSpillPt(&MI)) {
995 std::vector<std::pair<unsigned,bool> > &SpillRegs =
996 VRM.getSpillPtSpills(&MI);
997 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
998 unsigned VirtReg = SpillRegs[i].first;
999 bool isKill = SpillRegs[i].second;
1000 if (!VRM.getPreSplitReg(VirtReg))
1001 continue; // Split interval spilled again.
1002 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1003 unsigned Phys = VRM.getPhys(VirtReg);
1004 int StackSlot = VRM.getStackSlot(VirtReg);
1005 MRI->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1006 MachineInstr *StoreMI = next(MII);
1007 DOUT << "Store:\t" << StoreMI;
1008 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1010 NextMII = next(MII);
1013 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1015 ReuseInfo ReusedOperands(MI, MRI);
1016 // Process all of the spilled uses and all non spilled reg references.
1017 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1018 MachineOperand &MO = MI.getOperand(i);
1019 if (!MO.isRegister() || MO.getReg() == 0)
1020 continue; // Ignore non-register operands.
1022 unsigned VirtReg = MO.getReg();
1023 if (MRegisterInfo::isPhysicalRegister(VirtReg)) {
1024 // Ignore physregs for spilling, but remember that it is used by this
1026 RegInfo->setPhysRegUsed(VirtReg);
1030 assert(MRegisterInfo::isVirtualRegister(VirtReg) &&
1031 "Not a virtual or a physical register?");
1033 unsigned SubIdx = MO.getSubReg();
1034 if (VRM.isAssignedReg(VirtReg)) {
1035 // This virtual register was assigned a physreg!
1036 unsigned Phys = VRM.getPhys(VirtReg);
1037 RegInfo->setPhysRegUsed(Phys);
1039 ReusedOperands.markClobbered(Phys);
1040 unsigned RReg = SubIdx ? MRI->getSubReg(Phys, SubIdx) : Phys;
1041 MI.getOperand(i).setReg(RReg);
1045 // This virtual register is now known to be a spilled value.
1047 continue; // Handle defs in the loop below (handle use&def here though)
1049 bool DoReMat = VRM.isReMaterialized(VirtReg);
1050 int SSorRMId = DoReMat
1051 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1052 int ReuseSlot = SSorRMId;
1054 // Check to see if this stack slot is available.
1055 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1057 // If this is a sub-register use, make sure the reuse register is in the
1058 // right register class. For example, for x86 not all of the 32-bit
1059 // registers have accessible sub-registers.
1060 // Similarly so for EXTRACT_SUBREG. Consider this:
1062 // MOV32_mr fi#1, EDI
1064 // = EXTRACT_SUBREG fi#1
1065 // fi#1 is available in EDI, but it cannot be reused because it's not in
1066 // the right register file.
1068 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1069 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1070 if (!RC->contains(PhysReg))
1075 // This spilled operand might be part of a two-address operand. If this
1076 // is the case, then changing it will necessarily require changing the
1077 // def part of the instruction as well. However, in some cases, we
1078 // aren't allowed to modify the reused register. If none of these cases
1080 bool CanReuse = true;
1081 int ti = TID->getOperandConstraint(i, TOI::TIED_TO);
1083 MI.getOperand(ti).isRegister() &&
1084 MI.getOperand(ti).getReg() == VirtReg) {
1085 // Okay, we have a two address operand. We can reuse this physreg as
1086 // long as we are allowed to clobber the value and there isn't an
1087 // earlier def that has already clobbered the physreg.
1088 CanReuse = Spills.canClobberPhysReg(ReuseSlot) &&
1089 !ReusedOperands.isClobbered(PhysReg);
1093 // If this stack slot value is already available, reuse it!
1094 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1095 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1097 DOUT << "Reusing SS#" << ReuseSlot;
1098 DOUT << " from physreg "
1099 << MRI->getName(PhysReg) << " for vreg"
1100 << VirtReg <<" instead of reloading into physreg "
1101 << MRI->getName(VRM.getPhys(VirtReg)) << "\n";
1102 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1103 MI.getOperand(i).setReg(RReg);
1105 // The only technical detail we have is that we don't know that
1106 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1107 // later in the instruction. In particular, consider 'op V1, V2'.
1108 // If V1 is available in physreg R0, we would choose to reuse it
1109 // here, instead of reloading it into the register the allocator
1110 // indicated (say R1). However, V2 might have to be reloaded
1111 // later, and it might indicate that it needs to live in R0. When
1112 // this occurs, we need to have information available that
1113 // indicates it is safe to use R1 for the reload instead of R0.
1115 // To further complicate matters, we might conflict with an alias,
1116 // or R0 and R1 might not be compatible with each other. In this
1117 // case, we actually insert a reload for V1 in R1, ensuring that
1118 // we can get at R0 or its alias.
1119 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1120 VRM.getPhys(VirtReg), VirtReg);
1122 // Only mark it clobbered if this is a use&def operand.
1123 ReusedOperands.markClobbered(PhysReg);
1126 if (MI.getOperand(i).isKill() &&
1127 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1128 // This was the last use and the spilled value is still available
1129 // for reuse. That means the spill was unnecessary!
1130 MachineInstr* DeadStore = MaybeDeadStores[ReuseSlot];
1132 DOUT << "Removed dead store:\t" << *DeadStore;
1133 InvalidateKills(*DeadStore, RegKills, KillOps);
1134 VRM.RemoveMachineInstrFromMaps(DeadStore);
1135 MBB.erase(DeadStore);
1136 MaybeDeadStores[ReuseSlot] = NULL;
1143 // Otherwise we have a situation where we have a two-address instruction
1144 // whose mod/ref operand needs to be reloaded. This reload is already
1145 // available in some register "PhysReg", but if we used PhysReg as the
1146 // operand to our 2-addr instruction, the instruction would modify
1147 // PhysReg. This isn't cool if something later uses PhysReg and expects
1148 // to get its initial value.
1150 // To avoid this problem, and to avoid doing a load right after a store,
1151 // we emit a copy from PhysReg into the designated register for this
1153 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1154 assert(DesignatedReg && "Must map virtreg to physreg!");
1156 // Note that, if we reused a register for a previous operand, the
1157 // register we want to reload into might not actually be
1158 // available. If this occurs, use the register indicated by the
1160 if (ReusedOperands.hasReuses())
1161 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1162 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1164 // If the mapped designated register is actually the physreg we have
1165 // incoming, we don't need to inserted a dead copy.
1166 if (DesignatedReg == PhysReg) {
1167 // If this stack slot value is already available, reuse it!
1168 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1169 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1171 DOUT << "Reusing SS#" << ReuseSlot;
1172 DOUT << " from physreg " << MRI->getName(PhysReg) << " for vreg"
1174 << " instead of reloading into same physreg.\n";
1175 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1176 MI.getOperand(i).setReg(RReg);
1177 ReusedOperands.markClobbered(RReg);
1182 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1183 RegInfo->setPhysRegUsed(DesignatedReg);
1184 ReusedOperands.markClobbered(DesignatedReg);
1185 MRI->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1187 MachineInstr *CopyMI = prior(MII);
1188 UpdateKills(*CopyMI, RegKills, KillOps);
1190 // This invalidates DesignatedReg.
1191 Spills.ClobberPhysReg(DesignatedReg);
1193 Spills.addAvailable(ReuseSlot, &MI, DesignatedReg);
1195 SubIdx ? MRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1196 MI.getOperand(i).setReg(RReg);
1197 DOUT << '\t' << *prior(MII);
1202 // Otherwise, reload it and remember that we have it.
1203 PhysReg = VRM.getPhys(VirtReg);
1204 assert(PhysReg && "Must map virtreg to physreg!");
1206 // Note that, if we reused a register for a previous operand, the
1207 // register we want to reload into might not actually be
1208 // available. If this occurs, use the register indicated by the
1210 if (ReusedOperands.hasReuses())
1211 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1212 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1214 RegInfo->setPhysRegUsed(PhysReg);
1215 ReusedOperands.markClobbered(PhysReg);
1217 MRI->reMaterialize(MBB, &MI, PhysReg, VRM.getReMaterializedMI(VirtReg));
1220 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1221 MRI->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1224 // This invalidates PhysReg.
1225 Spills.ClobberPhysReg(PhysReg);
1227 // Any stores to this stack slot are not dead anymore.
1229 MaybeDeadStores[SSorRMId] = NULL;
1230 Spills.addAvailable(SSorRMId, &MI, PhysReg);
1231 // Assumes this is the last use. IsKill will be unset if reg is reused
1232 // unless it's a two-address operand.
1233 if (TID->getOperandConstraint(i, TOI::TIED_TO) == -1)
1234 MI.getOperand(i).setIsKill();
1235 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1236 MI.getOperand(i).setReg(RReg);
1237 UpdateKills(*prior(MII), RegKills, KillOps);
1238 DOUT << '\t' << *prior(MII);
1244 // If we have folded references to memory operands, make sure we clear all
1245 // physical registers that may contain the value of the spilled virtual
1247 SmallSet<int, 2> FoldedSS;
1248 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
1249 unsigned VirtReg = I->second.first;
1250 VirtRegMap::ModRef MR = I->second.second;
1251 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1253 int SS = VRM.getStackSlot(VirtReg);
1254 if (SS == VirtRegMap::NO_STACK_SLOT)
1256 FoldedSS.insert(SS);
1257 DOUT << " - StackSlot: " << SS << "\n";
1259 // If this folded instruction is just a use, check to see if it's a
1260 // straight load from the virt reg slot.
1261 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1263 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1264 if (DestReg && FrameIdx == SS) {
1265 // If this spill slot is available, turn it into a copy (or nothing)
1266 // instead of leaving it as a load!
1267 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1268 DOUT << "Promoted Load To Copy: " << MI;
1269 if (DestReg != InReg) {
1270 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1271 MRI->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1272 // Revisit the copy so we make sure to notice the effects of the
1273 // operation on the destreg (either needing to RA it if it's
1274 // virtual or needing to clobber any values if it's physical).
1276 --NextMII; // backtrack to the copy.
1279 DOUT << "Removing now-noop copy: " << MI;
1280 // Unset last kill since it's being reused.
1281 InvalidateKill(InReg, RegKills, KillOps);
1284 VRM.RemoveMachineInstrFromMaps(&MI);
1287 goto ProcessNextInst;
1290 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1291 SmallVector<MachineInstr*, 4> NewMIs;
1293 MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1294 MBB.insert(MII, NewMIs[0]);
1295 VRM.RemoveMachineInstrFromMaps(&MI);
1298 --NextMII; // backtrack to the unfolded instruction.
1300 goto ProcessNextInst;
1305 // If this reference is not a use, any previous store is now dead.
1306 // Otherwise, the store to this stack slot is not dead anymore.
1307 MachineInstr* DeadStore = MaybeDeadStores[SS];
1309 bool isDead = !(MR & VirtRegMap::isRef);
1310 MachineInstr *NewStore = NULL;
1311 if (MR & VirtRegMap::isModRef) {
1312 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1313 SmallVector<MachineInstr*, 4> NewMIs;
1314 // We can reuse this physreg as long as we are allowed to clobber
1315 // the value and there isn't an earlier def that has already clobbered
1318 !TII->isStoreToStackSlot(&MI, SS) && // Not profitable!
1319 DeadStore->findRegisterUseOperandIdx(PhysReg, true) != -1 &&
1320 MRI->unfoldMemoryOperand(MF, &MI, PhysReg, false, true, NewMIs)) {
1321 MBB.insert(MII, NewMIs[0]);
1322 NewStore = NewMIs[1];
1323 MBB.insert(MII, NewStore);
1324 VRM.RemoveMachineInstrFromMaps(&MI);
1328 --NextMII; // backtrack to the unfolded instruction.
1334 if (isDead) { // Previous store is dead.
1335 // If we get here, the store is dead, nuke it now.
1336 DOUT << "Removed dead store:\t" << *DeadStore;
1337 InvalidateKills(*DeadStore, RegKills, KillOps);
1338 VRM.RemoveMachineInstrFromMaps(DeadStore);
1339 MBB.erase(DeadStore);
1344 MaybeDeadStores[SS] = NULL;
1346 // Treat this store as a spill merged into a copy. That makes the
1347 // stack slot value available.
1348 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1349 goto ProcessNextInst;
1353 // If the spill slot value is available, and this is a new definition of
1354 // the value, the value is not available anymore.
1355 if (MR & VirtRegMap::isMod) {
1356 // Notice that the value in this stack slot has been modified.
1357 Spills.ModifyStackSlotOrReMat(SS);
1359 // If this is *just* a mod of the value, check to see if this is just a
1360 // store to the spill slot (i.e. the spill got merged into the copy). If
1361 // so, realize that the vreg is available now, and add the store to the
1362 // MaybeDeadStore info.
1364 if (!(MR & VirtRegMap::isRef)) {
1365 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1366 assert(MRegisterInfo::isPhysicalRegister(SrcReg) &&
1367 "Src hasn't been allocated yet?");
1368 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
1369 // this as a potentially dead store in case there is a subsequent
1370 // store into the stack slot without a read from it.
1371 MaybeDeadStores[StackSlot] = &MI;
1373 // If the stack slot value was previously available in some other
1374 // register, change it now. Otherwise, make the register available,
1376 Spills.addAvailable(StackSlot, &MI, SrcReg, false/*don't clobber*/);
1382 // Process all of the spilled defs.
1383 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1384 MachineOperand &MO = MI.getOperand(i);
1385 if (!(MO.isRegister() && MO.getReg() && MO.isDef()))
1388 unsigned VirtReg = MO.getReg();
1389 if (!MRegisterInfo::isVirtualRegister(VirtReg)) {
1390 // Check to see if this is a noop copy. If so, eliminate the
1391 // instruction before considering the dest reg to be changed.
1393 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1395 DOUT << "Removing now-noop copy: " << MI;
1398 VRM.RemoveMachineInstrFromMaps(&MI);
1399 Spills.disallowClobberPhysReg(VirtReg);
1400 goto ProcessNextInst;
1403 // If it's not a no-op copy, it clobbers the value in the destreg.
1404 Spills.ClobberPhysReg(VirtReg);
1405 ReusedOperands.markClobbered(VirtReg);
1407 // Check to see if this instruction is a load from a stack slot into
1408 // a register. If so, this provides the stack slot value in the reg.
1410 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
1411 assert(DestReg == VirtReg && "Unknown load situation!");
1413 // If it is a folded reference, then it's not safe to clobber.
1414 bool Folded = FoldedSS.count(FrameIdx);
1415 // Otherwise, if it wasn't available, remember that it is now!
1416 Spills.addAvailable(FrameIdx, &MI, DestReg, !Folded);
1417 goto ProcessNextInst;
1423 unsigned SubIdx = MO.getSubReg();
1424 bool DoReMat = VRM.isReMaterialized(VirtReg);
1426 ReMatDefs.insert(&MI);
1428 // The only vregs left are stack slot definitions.
1429 int StackSlot = VRM.getStackSlot(VirtReg);
1430 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1432 // If this def is part of a two-address operand, make sure to execute
1433 // the store from the correct physical register.
1435 int TiedOp = MI.getInstrDescriptor()->findTiedToSrcOperand(i);
1437 PhysReg = MI.getOperand(TiedOp).getReg();
1439 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, MRI);
1440 assert(SuperReg && MRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
1441 "Can't find corresponding super-register!");
1445 PhysReg = VRM.getPhys(VirtReg);
1446 if (ReusedOperands.isClobbered(PhysReg)) {
1447 // Another def has taken the assigned physreg. It must have been a
1448 // use&def which got it due to reuse. Undo the reuse!
1449 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1450 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1454 RegInfo->setPhysRegUsed(PhysReg);
1455 unsigned RReg = SubIdx ? MRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1456 ReusedOperands.markClobbered(RReg);
1457 MI.getOperand(i).setReg(RReg);
1460 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
1461 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
1462 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
1463 NextMII = next(MII);
1465 // Check to see if this is a noop copy. If so, eliminate the
1466 // instruction before considering the dest reg to be changed.
1469 if (TII->isMoveInstr(MI, Src, Dst) && Src == Dst) {
1471 DOUT << "Removing now-noop copy: " << MI;
1474 VRM.RemoveMachineInstrFromMaps(&MI);
1475 UpdateKills(*LastStore, RegKills, KillOps);
1476 goto ProcessNextInst;
1482 if (!Erased && !BackTracked) {
1483 for (MachineBasicBlock::iterator II = MI; II != NextMII; ++II)
1484 UpdateKills(*II, RegKills, KillOps);
1490 llvm::Spiller* llvm::createSpiller() {
1491 switch (SpillerOpt) {
1492 default: assert(0 && "Unreachable!");
1494 return new LocalSpiller();
1496 return new SimpleSpiller();