1 //===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
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 #define DEBUG_TYPE "virtregrewriter"
11 #include "VirtRegRewriter.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/ADT/DepthFirstIterator.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/STLExtras.h"
20 STATISTIC(NumDSE , "Number of dead stores elided");
21 STATISTIC(NumDSS , "Number of dead spill slots removed");
22 STATISTIC(NumCommutes, "Number of instructions commuted");
23 STATISTIC(NumDRM , "Number of re-materializable defs elided");
24 STATISTIC(NumStores , "Number of stores added");
25 STATISTIC(NumPSpills , "Number of physical register spills");
26 STATISTIC(NumOmitted , "Number of reloads omited");
27 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
28 STATISTIC(NumCopified, "Number of available reloads turned into copies");
29 STATISTIC(NumReMats , "Number of re-materialization");
30 STATISTIC(NumLoads , "Number of loads added");
31 STATISTIC(NumReused , "Number of values reused");
32 STATISTIC(NumDCE , "Number of copies elided");
33 STATISTIC(NumSUnfold , "Number of stores unfolded");
34 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
37 enum RewriterName { local, trivial };
40 static cl::opt<RewriterName>
41 RewriterOpt("rewriter",
42 cl::desc("Rewriter to use: (default: local)"),
44 cl::values(clEnumVal(local, "local rewriter"),
45 clEnumVal(trivial, "trivial rewriter"),
49 VirtRegRewriter::~VirtRegRewriter() {}
53 /// This class is intended for use with the new spilling framework only. It
54 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
56 struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
58 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
60 DOUT << "********** REWRITE MACHINE CODE **********\n";
61 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
62 MachineRegisterInfo *mri = &MF.getRegInfo();
66 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
67 liItr != liEnd; ++liItr) {
69 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
70 if (VRM.hasPhys(liItr->first)) {
71 unsigned preg = VRM.getPhys(liItr->first);
72 mri->replaceRegWith(liItr->first, preg);
73 mri->setPhysRegUsed(preg);
78 if (!liItr->second->empty()) {
79 mri->setPhysRegUsed(liItr->first);
89 // ************************************************************************ //
91 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
92 /// from top down, keep track of which spill slots or remat are available in
95 /// Note that not all physregs are created equal here. In particular, some
96 /// physregs are reloads that we are allowed to clobber or ignore at any time.
97 /// Other physregs are values that the register allocated program is using
98 /// that we cannot CHANGE, but we can read if we like. We keep track of this
99 /// on a per-stack-slot / remat id basis as the low bit in the value of the
100 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
101 /// this bit and addAvailable sets it if.
102 class VISIBILITY_HIDDEN AvailableSpills {
103 const TargetRegisterInfo *TRI;
104 const TargetInstrInfo *TII;
106 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
107 // or remat'ed virtual register values that are still available, due to
108 // being loaded or stored to, but not invalidated yet.
109 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
111 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
112 // indicating which stack slot values are currently held by a physreg. This
113 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
114 // physreg is modified.
115 std::multimap<unsigned, int> PhysRegsAvailable;
117 void disallowClobberPhysRegOnly(unsigned PhysReg);
119 void ClobberPhysRegOnly(unsigned PhysReg);
121 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
122 : TRI(tri), TII(tii) {
125 /// clear - Reset the state.
127 SpillSlotsOrReMatsAvailable.clear();
128 PhysRegsAvailable.clear();
131 const TargetRegisterInfo *getRegInfo() const { return TRI; }
133 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
134 /// available in a physical register, return that PhysReg, otherwise
136 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
137 std::map<int, unsigned>::const_iterator I =
138 SpillSlotsOrReMatsAvailable.find(Slot);
139 if (I != SpillSlotsOrReMatsAvailable.end()) {
140 return I->second >> 1; // Remove the CanClobber bit.
145 /// addAvailable - Mark that the specified stack slot / remat is available
146 /// in the specified physreg. If CanClobber is true, the physreg can be
147 /// modified at any time without changing the semantics of the program.
148 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
149 // If this stack slot is thought to be available in some other physreg,
150 // remove its record.
151 ModifyStackSlotOrReMat(SlotOrReMat);
153 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
154 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
155 (unsigned)CanClobber;
157 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
158 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
160 DOUT << "Remembering SS#" << SlotOrReMat;
161 DOUT << " in physreg " << TRI->getName(Reg) << "\n";
164 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
165 /// the value of the specified stackslot register if it desires. The
166 /// specified stack slot must be available in a physreg for this query to
168 bool canClobberPhysRegForSS(int SlotOrReMat) const {
169 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
170 "Value not available!");
171 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
174 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
175 /// physical register where values for some stack slot(s) might be
177 bool canClobberPhysReg(unsigned PhysReg) const {
178 std::multimap<unsigned, int>::const_iterator I =
179 PhysRegsAvailable.lower_bound(PhysReg);
180 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
181 int SlotOrReMat = I->second;
183 if (!canClobberPhysRegForSS(SlotOrReMat))
189 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
190 /// stackslot register. The register is still available but is no longer
191 /// allowed to be modifed.
192 void disallowClobberPhysReg(unsigned PhysReg);
194 /// ClobberPhysReg - This is called when the specified physreg changes
195 /// value. We use this to invalidate any info about stuff that lives in
196 /// it and any of its aliases.
197 void ClobberPhysReg(unsigned PhysReg);
199 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
200 /// slot changes. This removes information about which register the
201 /// previous value for this slot lives in (as the previous value is dead
203 void ModifyStackSlotOrReMat(int SlotOrReMat);
205 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
206 /// into the specified MBB. Add available physical registers as potential
207 /// live-in's. If they are reused in the MBB, they will be added to the
208 /// live-in set to make register scavenger and post-allocation scheduler.
209 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
210 std::vector<MachineOperand*> &KillOps);
213 // ************************************************************************ //
215 // ReusedOp - For each reused operand, we keep track of a bit of information,
216 // in case we need to rollback upon processing a new operand. See comments
219 // The MachineInstr operand that reused an available value.
222 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
223 unsigned StackSlotOrReMat;
225 // PhysRegReused - The physical register the value was available in.
226 unsigned PhysRegReused;
228 // AssignedPhysReg - The physreg that was assigned for use by the reload.
229 unsigned AssignedPhysReg;
231 // VirtReg - The virtual register itself.
234 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
236 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
237 AssignedPhysReg(apr), VirtReg(vreg) {}
240 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
241 /// is reused instead of reloaded.
242 class VISIBILITY_HIDDEN ReuseInfo {
244 std::vector<ReusedOp> Reuses;
245 BitVector PhysRegsClobbered;
247 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
248 PhysRegsClobbered.resize(tri->getNumRegs());
251 bool hasReuses() const {
252 return !Reuses.empty();
255 /// addReuse - If we choose to reuse a virtual register that is already
256 /// available instead of reloading it, remember that we did so.
257 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
258 unsigned PhysRegReused, unsigned AssignedPhysReg,
260 // If the reload is to the assigned register anyway, no undo will be
262 if (PhysRegReused == AssignedPhysReg) return;
264 // Otherwise, remember this.
265 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
266 AssignedPhysReg, VirtReg));
269 void markClobbered(unsigned PhysReg) {
270 PhysRegsClobbered.set(PhysReg);
273 bool isClobbered(unsigned PhysReg) const {
274 return PhysRegsClobbered.test(PhysReg);
277 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
278 /// is some other operand that is using the specified register, either pick
279 /// a new register to use, or evict the previous reload and use this reg.
280 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
281 AvailableSpills &Spills,
282 std::vector<MachineInstr*> &MaybeDeadStores,
283 SmallSet<unsigned, 8> &Rejected,
285 std::vector<MachineOperand*> &KillOps,
288 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
289 /// 'Rejected' set to remember which registers have been considered and
290 /// rejected for the reload. This avoids infinite looping in case like
293 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
294 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
296 /// sees r1 is taken by t2, tries t2's reload register r0
297 /// sees r0 is taken by t3, tries t3's reload register r1
298 /// sees r1 is taken by t2, tries t2's reload register r0 ...
299 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
300 AvailableSpills &Spills,
301 std::vector<MachineInstr*> &MaybeDeadStores,
303 std::vector<MachineOperand*> &KillOps,
305 SmallSet<unsigned, 8> Rejected;
306 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
307 RegKills, KillOps, VRM);
312 // ****************** //
313 // Utility Functions //
314 // ****************** //
316 /// findSinglePredSuccessor - Return via reference a vector of machine basic
317 /// blocks each of which is a successor of the specified BB and has no other
319 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
320 SmallVectorImpl<MachineBasicBlock *> &Succs) {
321 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
322 SE = MBB->succ_end(); SI != SE; ++SI) {
323 MachineBasicBlock *SuccMBB = *SI;
324 if (SuccMBB->pred_size() == 1)
325 Succs.push_back(SuccMBB);
329 /// InvalidateKill - Invalidate register kill information for a specific
330 /// register. This also unsets the kills marker on the last kill operand.
331 static void InvalidateKill(unsigned Reg,
332 const TargetRegisterInfo* TRI,
334 std::vector<MachineOperand*> &KillOps) {
336 KillOps[Reg]->setIsKill(false);
337 // KillOps[Reg] might be a def of a super-register.
338 unsigned KReg = KillOps[Reg]->getReg();
339 KillOps[KReg] = NULL;
340 RegKills.reset(KReg);
341 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
343 KillOps[*SR]->setIsKill(false);
351 /// InvalidateKills - MI is going to be deleted. If any of its operands are
352 /// marked kill, then invalidate the information.
353 static void InvalidateKills(MachineInstr &MI,
354 const TargetRegisterInfo* TRI,
356 std::vector<MachineOperand*> &KillOps,
357 SmallVector<unsigned, 2> *KillRegs = NULL) {
358 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
359 MachineOperand &MO = MI.getOperand(i);
360 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
362 unsigned Reg = MO.getReg();
363 if (TargetRegisterInfo::isVirtualRegister(Reg))
366 KillRegs->push_back(Reg);
367 assert(Reg < KillOps.size());
368 if (KillOps[Reg] == &MO) {
371 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
381 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
382 /// (since it's spill instruction is removed), mark it isDead. Also checks if
383 /// the def MI has other definition operands that are not dead. Returns it by
385 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
386 MachineInstr &NewDef, unsigned Reg,
388 // Due to remat, it's possible this reg isn't being reused. That is,
389 // the def of this reg (by prev MI) is now dead.
390 MachineInstr *DefMI = I;
391 MachineOperand *DefOp = NULL;
392 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
393 MachineOperand &MO = DefMI->getOperand(i);
394 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
396 if (MO.getReg() == Reg)
398 else if (!MO.isDead())
404 bool FoundUse = false, Done = false;
405 MachineBasicBlock::iterator E = &NewDef;
407 for (; !Done && I != E; ++I) {
408 MachineInstr *NMI = I;
409 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
410 MachineOperand &MO = NMI->getOperand(j);
411 if (!MO.isReg() || MO.getReg() != Reg)
415 Done = true; // Stop after scanning all the operands of this MI.
426 /// UpdateKills - Track and update kill info. If a MI reads a register that is
427 /// marked kill, then it must be due to register reuse. Transfer the kill info
429 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
431 std::vector<MachineOperand*> &KillOps) {
432 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
433 MachineOperand &MO = MI.getOperand(i);
434 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
436 unsigned Reg = MO.getReg();
440 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
441 // That can't be right. Register is killed but not re-defined and it's
442 // being reused. Let's fix that.
443 KillOps[Reg]->setIsKill(false);
444 // KillOps[Reg] might be a def of a super-register.
445 unsigned KReg = KillOps[Reg]->getReg();
446 KillOps[KReg] = NULL;
447 RegKills.reset(KReg);
449 // Must be a def of a super-register. Its other sub-regsters are no
450 // longer killed as well.
451 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
456 if (!MI.isRegTiedToDefOperand(i))
457 // Unless it's a two-address operand, this is the new kill.
463 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
470 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
471 const MachineOperand &MO = MI.getOperand(i);
472 if (!MO.isReg() || !MO.isDef())
474 unsigned Reg = MO.getReg();
477 // It also defines (or partially define) aliases.
478 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
485 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
487 static void ReMaterialize(MachineBasicBlock &MBB,
488 MachineBasicBlock::iterator &MII,
489 unsigned DestReg, unsigned Reg,
490 const TargetInstrInfo *TII,
491 const TargetRegisterInfo *TRI,
493 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
495 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
496 assert(TID.getNumDefs() == 1 &&
497 "Don't know how to remat instructions that define > 1 values!");
499 TII->reMaterialize(MBB, MII, DestReg,
500 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
501 MachineInstr *NewMI = prior(MII);
502 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = NewMI->getOperand(i);
504 if (!MO.isReg() || MO.getReg() == 0)
506 unsigned VirtReg = MO.getReg();
507 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
510 unsigned SubIdx = MO.getSubReg();
511 unsigned Phys = VRM.getPhys(VirtReg);
513 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
520 /// findSuperReg - Find the SubReg's super-register of given register class
521 /// where its SubIdx sub-register is SubReg.
522 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
523 unsigned SubIdx, const TargetRegisterInfo *TRI) {
524 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
527 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
533 // ******************************** //
534 // Available Spills Implementation //
535 // ******************************** //
537 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
538 /// stackslot register. The register is still available but is no longer
539 /// allowed to be modifed.
540 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
541 std::multimap<unsigned, int>::iterator I =
542 PhysRegsAvailable.lower_bound(PhysReg);
543 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
544 int SlotOrReMat = I->second;
546 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
547 "Bidirectional map mismatch!");
548 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
549 DOUT << "PhysReg " << TRI->getName(PhysReg)
550 << " copied, it is available for use but can no longer be modified\n";
554 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
555 /// stackslot register and its aliases. The register and its aliases may
556 /// still available but is no longer allowed to be modifed.
557 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
558 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
559 disallowClobberPhysRegOnly(*AS);
560 disallowClobberPhysRegOnly(PhysReg);
563 /// ClobberPhysRegOnly - This is called when the specified physreg changes
564 /// value. We use this to invalidate any info about stuff we thing lives in it.
565 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
566 std::multimap<unsigned, int>::iterator I =
567 PhysRegsAvailable.lower_bound(PhysReg);
568 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
569 int SlotOrReMat = I->second;
570 PhysRegsAvailable.erase(I++);
571 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
572 "Bidirectional map mismatch!");
573 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
574 DOUT << "PhysReg " << TRI->getName(PhysReg)
575 << " clobbered, invalidating ";
576 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
577 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
579 DOUT << "SS#" << SlotOrReMat << "\n";
583 /// ClobberPhysReg - This is called when the specified physreg changes
584 /// value. We use this to invalidate any info about stuff we thing lives in
585 /// it and any of its aliases.
586 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
587 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
588 ClobberPhysRegOnly(*AS);
589 ClobberPhysRegOnly(PhysReg);
592 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
593 /// into the specified MBB. Add available physical registers as potential
594 /// live-in's. If they are reused in the MBB, they will be added to the
595 /// live-in set to make register scavenger and post-allocation scheduler.
596 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
598 std::vector<MachineOperand*> &KillOps) {
599 std::set<unsigned> NotAvailable;
600 for (std::multimap<unsigned, int>::iterator
601 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
603 unsigned Reg = I->first;
604 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
605 // FIXME: A temporary workaround. We can't reuse available value if it's
606 // not safe to move the def of the virtual register's class. e.g.
607 // X86::RFP* register classes. Do not add it as a live-in.
608 if (!TII->isSafeToMoveRegClassDefs(RC))
609 // This is no longer available.
610 NotAvailable.insert(Reg);
613 InvalidateKill(Reg, TRI, RegKills, KillOps);
616 // Skip over the same register.
617 std::multimap<unsigned, int>::iterator NI = next(I);
618 while (NI != E && NI->first == Reg) {
624 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
625 E = NotAvailable.end(); I != E; ++I) {
627 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
629 ClobberPhysReg(*SubRegs);
633 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
634 /// slot changes. This removes information about which register the previous
635 /// value for this slot lives in (as the previous value is dead now).
636 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
637 std::map<int, unsigned>::iterator It =
638 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
639 if (It == SpillSlotsOrReMatsAvailable.end()) return;
640 unsigned Reg = It->second >> 1;
641 SpillSlotsOrReMatsAvailable.erase(It);
643 // This register may hold the value of multiple stack slots, only remove this
644 // stack slot from the set of values the register contains.
645 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
647 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
648 "Map inverse broken!");
649 if (I->second == SlotOrReMat) break;
651 PhysRegsAvailable.erase(I);
654 // ************************** //
655 // Reuse Info Implementation //
656 // ************************** //
658 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
659 /// is some other operand that is using the specified register, either pick
660 /// a new register to use, or evict the previous reload and use this reg.
661 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
662 AvailableSpills &Spills,
663 std::vector<MachineInstr*> &MaybeDeadStores,
664 SmallSet<unsigned, 8> &Rejected,
666 std::vector<MachineOperand*> &KillOps,
668 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
671 if (Reuses.empty()) return PhysReg; // This is most often empty.
673 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
674 ReusedOp &Op = Reuses[ro];
675 // If we find some other reuse that was supposed to use this register
676 // exactly for its reload, we can change this reload to use ITS reload
677 // register. That is, unless its reload register has already been
678 // considered and subsequently rejected because it has also been reused
679 // by another operand.
680 if (Op.PhysRegReused == PhysReg &&
681 Rejected.count(Op.AssignedPhysReg) == 0) {
682 // Yup, use the reload register that we didn't use before.
683 unsigned NewReg = Op.AssignedPhysReg;
684 Rejected.insert(PhysReg);
685 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
686 RegKills, KillOps, VRM);
688 // Otherwise, we might also have a problem if a previously reused
689 // value aliases the new register. If so, codegen the previous reload
691 unsigned PRRU = Op.PhysRegReused;
692 const TargetRegisterInfo *TRI = Spills.getRegInfo();
693 if (TRI->areAliases(PRRU, PhysReg)) {
694 // Okay, we found out that an alias of a reused register
695 // was used. This isn't good because it means we have
696 // to undo a previous reuse.
697 MachineBasicBlock *MBB = MI->getParent();
698 const TargetRegisterClass *AliasRC =
699 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
701 // Copy Op out of the vector and remove it, we're going to insert an
702 // explicit load for it.
704 Reuses.erase(Reuses.begin()+ro);
706 // Ok, we're going to try to reload the assigned physreg into the
707 // slot that we were supposed to in the first place. However, that
708 // register could hold a reuse. Check to see if it conflicts or
709 // would prefer us to use a different register.
710 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
711 MI, Spills, MaybeDeadStores,
712 Rejected, RegKills, KillOps, VRM);
714 MachineBasicBlock::iterator MII = MI;
715 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
716 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
718 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
719 NewOp.StackSlotOrReMat, AliasRC);
720 MachineInstr *LoadMI = prior(MII);
721 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
722 // Any stores to this stack slot are not dead anymore.
723 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
726 Spills.ClobberPhysReg(NewPhysReg);
727 Spills.ClobberPhysReg(NewOp.PhysRegReused);
729 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
730 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
731 MI->getOperand(NewOp.Operand).setReg(RReg);
732 MI->getOperand(NewOp.Operand).setSubReg(0);
734 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
736 UpdateKills(*MII, TRI, RegKills, KillOps);
737 DOUT << '\t' << *MII;
739 DOUT << "Reuse undone!\n";
742 // Finally, PhysReg is now available, go ahead and use it.
750 // ************************************************************************ //
752 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
753 /// stack slot mod/ref. It also checks if it's possible to unfold the
754 /// instruction by having it define a specified physical register instead.
755 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
756 const TargetInstrInfo *TII,
757 const TargetRegisterInfo *TRI,
759 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
763 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
764 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
765 unsigned VirtReg = I->second.first;
766 VirtRegMap::ModRef MR = I->second.second;
767 if (MR & VirtRegMap::isModRef)
768 if (VRM.getStackSlot(VirtReg) == SS) {
769 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
776 // Does the instruction uses a register that overlaps the scratch register?
777 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
778 MachineOperand &MO = MI.getOperand(i);
779 if (!MO.isReg() || MO.getReg() == 0)
781 unsigned Reg = MO.getReg();
782 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
783 if (!VRM.hasPhys(Reg))
785 Reg = VRM.getPhys(Reg);
787 if (TRI->regsOverlap(PhysReg, Reg))
793 /// FindFreeRegister - Find a free register of a given register class by looking
794 /// at (at most) the last two machine instructions.
795 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
796 MachineBasicBlock &MBB,
797 const TargetRegisterClass *RC,
798 const TargetRegisterInfo *TRI,
799 BitVector &AllocatableRegs) {
800 BitVector Defs(TRI->getNumRegs());
801 BitVector Uses(TRI->getNumRegs());
802 SmallVector<unsigned, 4> LocalUses;
803 SmallVector<unsigned, 4> Kills;
805 // Take a look at 2 instructions at most.
806 for (unsigned Count = 0; Count < 2; ++Count) {
807 if (MII == MBB.begin())
809 MachineInstr *PrevMI = prior(MII);
810 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
811 MachineOperand &MO = PrevMI->getOperand(i);
812 if (!MO.isReg() || MO.getReg() == 0)
814 unsigned Reg = MO.getReg();
817 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
820 LocalUses.push_back(Reg);
821 if (MO.isKill() && AllocatableRegs[Reg])
822 Kills.push_back(Reg);
826 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
827 unsigned Kill = Kills[i];
828 if (!Defs[Kill] && !Uses[Kill] &&
829 TRI->getPhysicalRegisterRegClass(Kill) == RC)
832 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
833 unsigned Reg = LocalUses[i];
835 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
846 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
847 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
848 MachineOperand &MO = MI->getOperand(i);
849 if (MO.isReg() && MO.getReg() == VirtReg)
856 bool operator()(const std::pair<MachineInstr*, int> &A,
857 const std::pair<MachineInstr*, int> &B) {
858 return A.second < B.second;
863 // ***************************** //
864 // Local Spiller Implementation //
865 // ***************************** //
867 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
868 MachineRegisterInfo *RegInfo;
869 const TargetRegisterInfo *TRI;
870 const TargetInstrInfo *TII;
871 BitVector AllocatableRegs;
872 DenseMap<MachineInstr*, unsigned> DistanceMap;
875 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
876 LiveIntervals* LIs) {
877 RegInfo = &MF.getRegInfo();
878 TRI = MF.getTarget().getRegisterInfo();
879 TII = MF.getTarget().getInstrInfo();
880 AllocatableRegs = TRI->getAllocatableSet(MF);
881 DOUT << "\n**** Local spiller rewriting function '"
882 << MF.getFunction()->getName() << "':\n";
883 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
887 // Spills - Keep track of which spilled values are available in physregs
888 // so that we can choose to reuse the physregs instead of emitting
889 // reloads. This is usually refreshed per basic block.
890 AvailableSpills Spills(TRI, TII);
892 // Keep track of kill information.
893 BitVector RegKills(TRI->getNumRegs());
894 std::vector<MachineOperand*> KillOps;
895 KillOps.resize(TRI->getNumRegs(), NULL);
897 // SingleEntrySuccs - Successor blocks which have a single predecessor.
898 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
899 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
901 // Traverse the basic blocks depth first.
902 MachineBasicBlock *Entry = MF.begin();
903 SmallPtrSet<MachineBasicBlock*,16> Visited;
904 for (df_ext_iterator<MachineBasicBlock*,
905 SmallPtrSet<MachineBasicBlock*,16> >
906 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
908 MachineBasicBlock *MBB = *DFI;
909 if (!EarlyVisited.count(MBB))
910 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
912 // If this MBB is the only predecessor of a successor. Keep the
913 // availability information and visit it next.
915 // Keep visiting single predecessor successor as long as possible.
916 SinglePredSuccs.clear();
917 findSinglePredSuccessor(MBB, SinglePredSuccs);
918 if (SinglePredSuccs.empty())
921 // FIXME: More than one successors, each of which has MBB has
922 // the only predecessor.
923 MBB = SinglePredSuccs[0];
924 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
925 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
926 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
931 // Clear the availability info.
935 DOUT << "**** Post Machine Instrs ****\n";
938 // Mark unused spill slots.
939 MachineFrameInfo *MFI = MF.getFrameInfo();
940 int SS = VRM.getLowSpillSlot();
941 if (SS != VirtRegMap::NO_STACK_SLOT)
942 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
943 if (!VRM.isSpillSlotUsed(SS)) {
944 MFI->RemoveStackObject(SS);
953 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
954 /// a scratch register is available.
955 /// xorq %r12<kill>, %r13
956 /// addq %rax, -184(%rbp)
957 /// addq %r13, -184(%rbp)
959 /// xorq %r12<kill>, %r13
960 /// movq -184(%rbp), %r12
963 /// movq %r12, -184(%rbp)
964 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
965 MachineBasicBlock &MBB,
966 MachineBasicBlock::iterator &MII,
967 std::vector<MachineInstr*> &MaybeDeadStores,
968 AvailableSpills &Spills,
970 std::vector<MachineOperand*> &KillOps,
973 MachineBasicBlock::iterator NextMII = next(MII);
974 if (NextMII == MBB.end())
977 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
980 // Now let's see if the last couple of instructions happens to have freed up
982 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
983 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
987 MachineFunction &MF = *MBB.getParent();
988 TRI = MF.getTarget().getRegisterInfo();
989 MachineInstr &MI = *MII;
990 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
993 // If the next instruction also folds the same SS modref and can be unfoled,
994 // then it's worthwhile to issue a load from SS into the free register and
995 // then unfold these instructions.
996 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
999 // Load from SS to the spare physical register.
1000 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1001 // This invalidates Phys.
1002 Spills.ClobberPhysReg(PhysReg);
1003 // Remember it's available.
1004 Spills.addAvailable(SS, PhysReg);
1005 MaybeDeadStores[SS] = NULL;
1007 // Unfold current MI.
1008 SmallVector<MachineInstr*, 4> NewMIs;
1009 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1010 llvm_unreachable("Unable unfold the load / store folding instruction!");
1011 assert(NewMIs.size() == 1);
1012 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1013 VRM.transferRestorePts(&MI, NewMIs[0]);
1014 MII = MBB.insert(MII, NewMIs[0]);
1015 InvalidateKills(MI, TRI, RegKills, KillOps);
1016 VRM.RemoveMachineInstrFromMaps(&MI);
1020 // Unfold next instructions that fold the same SS.
1022 MachineInstr &NextMI = *NextMII;
1023 NextMII = next(NextMII);
1025 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1026 llvm_unreachable("Unable unfold the load / store folding instruction!");
1027 assert(NewMIs.size() == 1);
1028 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1029 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1030 MBB.insert(NextMII, NewMIs[0]);
1031 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1032 VRM.RemoveMachineInstrFromMaps(&NextMI);
1035 if (NextMII == MBB.end())
1037 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1039 // Store the value back into SS.
1040 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1041 MachineInstr *StoreMI = prior(NextMII);
1042 VRM.addSpillSlotUse(SS, StoreMI);
1043 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1048 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1049 /// instruction. e.g.
1051 /// movl %eax, -32(%ebp)
1052 /// movl -36(%ebp), %eax
1053 /// orl %eax, -32(%ebp)
1056 /// orl -36(%ebp), %eax
1057 /// mov %eax, -32(%ebp)
1058 /// This enables unfolding optimization for a subsequent instruction which will
1059 /// also eliminate the newly introduced store instruction.
1060 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1061 MachineBasicBlock::iterator &MII,
1062 std::vector<MachineInstr*> &MaybeDeadStores,
1063 AvailableSpills &Spills,
1064 BitVector &RegKills,
1065 std::vector<MachineOperand*> &KillOps,
1067 MachineFunction &MF = *MBB.getParent();
1068 MachineInstr &MI = *MII;
1069 unsigned UnfoldedOpc = 0;
1070 unsigned UnfoldPR = 0;
1071 unsigned UnfoldVR = 0;
1072 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1073 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1074 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1075 // Only transform a MI that folds a single register.
1078 UnfoldVR = I->second.first;
1079 VirtRegMap::ModRef MR = I->second.second;
1080 // MI2VirtMap be can updated which invalidate the iterator.
1081 // Increment the iterator first.
1083 if (VRM.isAssignedReg(UnfoldVR))
1085 // If this reference is not a use, any previous store is now dead.
1086 // Otherwise, the store to this stack slot is not dead anymore.
1087 FoldedSS = VRM.getStackSlot(UnfoldVR);
1088 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1089 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1090 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1091 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1094 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1103 // Look for other unfolding opportunities.
1104 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1105 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1108 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1109 MachineOperand &MO = MI.getOperand(i);
1110 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1112 unsigned VirtReg = MO.getReg();
1113 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1115 if (VRM.isAssignedReg(VirtReg)) {
1116 unsigned PhysReg = VRM.getPhys(VirtReg);
1117 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1119 } else if (VRM.isReMaterialized(VirtReg))
1121 int SS = VRM.getStackSlot(VirtReg);
1122 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1124 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1128 if (VRM.hasPhys(VirtReg)) {
1129 PhysReg = VRM.getPhys(VirtReg);
1130 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1134 // Ok, we'll need to reload the value into a register which makes
1135 // it impossible to perform the store unfolding optimization later.
1136 // Let's see if it is possible to fold the load if the store is
1137 // unfolded. This allows us to perform the store unfolding
1139 SmallVector<MachineInstr*, 4> NewMIs;
1140 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1141 assert(NewMIs.size() == 1);
1142 MachineInstr *NewMI = NewMIs.back();
1144 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1146 SmallVector<unsigned, 1> Ops;
1148 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1150 VRM.addSpillSlotUse(SS, FoldedMI);
1151 if (!VRM.hasPhys(UnfoldVR))
1152 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1153 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1154 MII = MBB.insert(MII, FoldedMI);
1155 InvalidateKills(MI, TRI, RegKills, KillOps);
1156 VRM.RemoveMachineInstrFromMaps(&MI);
1158 MF.DeleteMachineInstr(NewMI);
1161 MF.DeleteMachineInstr(NewMI);
1168 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1169 /// where SrcReg is r1 and it is tied to r0. Return true if after
1170 /// commuting this instruction it will be r0 = op r2, r1.
1171 static bool CommuteChangesDestination(MachineInstr *DefMI,
1172 const TargetInstrDesc &TID,
1174 const TargetInstrInfo *TII,
1176 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1178 if (!DefMI->getOperand(1).isReg() ||
1179 DefMI->getOperand(1).getReg() != SrcReg)
1182 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1184 unsigned SrcIdx1, SrcIdx2;
1185 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1187 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1194 /// CommuteToFoldReload -
1197 /// r1 = op r1, r2<kill>
1200 /// If op is commutable and r2 is killed, then we can xform these to
1201 /// r2 = op r2, fi#1
1203 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1204 MachineBasicBlock::iterator &MII,
1205 unsigned VirtReg, unsigned SrcReg, int SS,
1206 AvailableSpills &Spills,
1207 BitVector &RegKills,
1208 std::vector<MachineOperand*> &KillOps,
1209 const TargetRegisterInfo *TRI,
1211 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1214 MachineFunction &MF = *MBB.getParent();
1215 MachineInstr &MI = *MII;
1216 MachineBasicBlock::iterator DefMII = prior(MII);
1217 MachineInstr *DefMI = DefMII;
1218 const TargetInstrDesc &TID = DefMI->getDesc();
1220 if (DefMII != MBB.begin() &&
1221 TID.isCommutable() &&
1222 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1223 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1224 unsigned NewReg = NewDstMO.getReg();
1225 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1227 MachineInstr *ReloadMI = prior(DefMII);
1229 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1230 if (DestReg != SrcReg || FrameIdx != SS)
1232 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1236 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1238 assert(DefMI->getOperand(DefIdx).isReg() &&
1239 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1241 // Now commute def instruction.
1242 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1245 SmallVector<unsigned, 1> Ops;
1246 Ops.push_back(NewDstIdx);
1247 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1248 // Not needed since foldMemoryOperand returns new MI.
1249 MF.DeleteMachineInstr(CommutedMI);
1253 VRM.addSpillSlotUse(SS, FoldedMI);
1254 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1255 // Insert new def MI and spill MI.
1256 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1257 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1259 MachineInstr *StoreMI = MII;
1260 VRM.addSpillSlotUse(SS, StoreMI);
1261 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1262 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1264 // Delete all 3 old instructions.
1265 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1266 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1267 MBB.erase(ReloadMI);
1268 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1269 VRM.RemoveMachineInstrFromMaps(DefMI);
1271 InvalidateKills(MI, TRI, RegKills, KillOps);
1272 VRM.RemoveMachineInstrFromMaps(&MI);
1275 // If NewReg was previously holding value of some SS, it's now clobbered.
1276 // This has to be done now because it's a physical register. When this
1277 // instruction is re-visited, it's ignored.
1278 Spills.ClobberPhysReg(NewReg);
1287 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1288 /// the last store to the same slot is now dead. If so, remove the last store.
1289 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1290 MachineBasicBlock::iterator &MII,
1291 int Idx, unsigned PhysReg, int StackSlot,
1292 const TargetRegisterClass *RC,
1293 bool isAvailable, MachineInstr *&LastStore,
1294 AvailableSpills &Spills,
1295 SmallSet<MachineInstr*, 4> &ReMatDefs,
1296 BitVector &RegKills,
1297 std::vector<MachineOperand*> &KillOps,
1300 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1301 MachineInstr *StoreMI = next(MII);
1302 VRM.addSpillSlotUse(StackSlot, StoreMI);
1303 DOUT << "Store:\t" << *StoreMI;
1305 // If there is a dead store to this stack slot, nuke it now.
1307 DOUT << "Removed dead store:\t" << *LastStore;
1309 SmallVector<unsigned, 2> KillRegs;
1310 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1311 MachineBasicBlock::iterator PrevMII = LastStore;
1312 bool CheckDef = PrevMII != MBB.begin();
1315 VRM.RemoveMachineInstrFromMaps(LastStore);
1316 MBB.erase(LastStore);
1318 // Look at defs of killed registers on the store. Mark the defs
1319 // as dead since the store has been deleted and they aren't
1321 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1322 bool HasOtherDef = false;
1323 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1324 MachineInstr *DeadDef = PrevMII;
1325 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1326 // FIXME: This assumes a remat def does not have side effects.
1327 VRM.RemoveMachineInstrFromMaps(DeadDef);
1336 LastStore = next(MII);
1338 // If the stack slot value was previously available in some other
1339 // register, change it now. Otherwise, make the register available,
1341 Spills.ModifyStackSlotOrReMat(StackSlot);
1342 Spills.ClobberPhysReg(PhysReg);
1343 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1347 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1348 /// effect and all of its defs are dead.
1349 static bool isSafeToDelete(MachineInstr &MI) {
1350 const TargetInstrDesc &TID = MI.getDesc();
1351 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1352 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1353 TID.hasUnmodeledSideEffects())
1355 if (TID.getImplicitDefs())
1357 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1358 MachineOperand &MO = MI.getOperand(i);
1359 if (!MO.isReg() || !MO.getReg())
1361 if (MO.isDef() && !MO.isDead())
1363 if (MO.isUse() && MO.isKill())
1364 // FIXME: We can't remove kill markers or else the scavenger will assert.
1365 // An alternative is to add a ADD pseudo instruction to replace kill
1372 /// TransferDeadness - A identity copy definition is dead and it's being
1373 /// removed. Find the last def or use and mark it as dead / kill.
1374 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1375 unsigned Reg, BitVector &RegKills,
1376 std::vector<MachineOperand*> &KillOps,
1378 SmallPtrSet<MachineInstr*, 4> Seens;
1379 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1380 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1381 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1382 MachineInstr *UDMI = &*RI;
1383 if (UDMI->getParent() != MBB)
1385 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1386 if (DI == DistanceMap.end() || DI->second > CurDist)
1388 if (Seens.insert(UDMI))
1389 Refs.push_back(std::make_pair(UDMI, DI->second));
1394 std::sort(Refs.begin(), Refs.end(), RefSorter());
1396 while (!Refs.empty()) {
1397 MachineInstr *LastUDMI = Refs.back().first;
1400 MachineOperand *LastUD = NULL;
1401 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1402 MachineOperand &MO = LastUDMI->getOperand(i);
1403 if (!MO.isReg() || MO.getReg() != Reg)
1405 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1407 if (LastUDMI->isRegTiedToDefOperand(i))
1410 if (LastUD->isDef()) {
1411 // If the instruction has no side effect, delete it and propagate
1412 // backward further. Otherwise, mark is dead and we are done.
1413 if (!isSafeToDelete(*LastUDMI)) {
1414 LastUD->setIsDead();
1417 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1418 MBB->erase(LastUDMI);
1420 LastUD->setIsKill();
1422 KillOps[Reg] = LastUD;
1428 /// rewriteMBB - Keep track of which spills are available even after the
1429 /// register allocator is done with them. If possible, avid reloading vregs.
1430 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1432 AvailableSpills &Spills, BitVector &RegKills,
1433 std::vector<MachineOperand*> &KillOps) {
1435 DOUT << "\n**** Local spiller rewriting MBB '"
1436 << MBB.getBasicBlock()->getName() << "':\n";
1438 MachineFunction &MF = *MBB.getParent();
1440 // MaybeDeadStores - When we need to write a value back into a stack slot,
1441 // keep track of the inserted store. If the stack slot value is never read
1442 // (because the value was used from some available register, for example), and
1443 // subsequently stored to, the original store is dead. This map keeps track
1444 // of inserted stores that are not used. If we see a subsequent store to the
1445 // same stack slot, the original store is deleted.
1446 std::vector<MachineInstr*> MaybeDeadStores;
1447 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1449 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1450 SmallSet<MachineInstr*, 4> ReMatDefs;
1453 SmallSet<unsigned, 2> KilledMIRegs;
1456 KillOps.resize(TRI->getNumRegs(), NULL);
1459 DistanceMap.clear();
1460 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1462 MachineBasicBlock::iterator NextMII = next(MII);
1464 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1465 bool Erased = false;
1466 bool BackTracked = false;
1467 if (OptimizeByUnfold(MBB, MII,
1468 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1469 NextMII = next(MII);
1471 MachineInstr &MI = *MII;
1473 if (VRM.hasEmergencySpills(&MI)) {
1474 // Spill physical register(s) in the rare case the allocator has run out
1475 // of registers to allocate.
1476 SmallSet<int, 4> UsedSS;
1477 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1478 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1479 unsigned PhysReg = EmSpills[i];
1480 const TargetRegisterClass *RC =
1481 TRI->getPhysicalRegisterRegClass(PhysReg);
1482 assert(RC && "Unable to determine register class!");
1483 int SS = VRM.getEmergencySpillSlot(RC);
1484 if (UsedSS.count(SS))
1485 llvm_unreachable("Need to spill more than one physical registers!");
1487 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1488 MachineInstr *StoreMI = prior(MII);
1489 VRM.addSpillSlotUse(SS, StoreMI);
1490 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1491 MachineInstr *LoadMI = next(MII);
1492 VRM.addSpillSlotUse(SS, LoadMI);
1495 NextMII = next(MII);
1498 // Insert restores here if asked to.
1499 if (VRM.isRestorePt(&MI)) {
1500 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1501 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1502 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1503 if (!VRM.getPreSplitReg(VirtReg))
1504 continue; // Split interval spilled again.
1505 unsigned Phys = VRM.getPhys(VirtReg);
1506 RegInfo->setPhysRegUsed(Phys);
1508 // Check if the value being restored if available. If so, it must be
1509 // from a predecessor BB that fallthrough into this BB. We do not
1515 // ... # r1 not clobbered
1518 bool DoReMat = VRM.isReMaterialized(VirtReg);
1519 int SSorRMId = DoReMat
1520 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1521 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1522 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1523 if (InReg == Phys) {
1524 // If the value is already available in the expected register, save
1525 // a reload / remat.
1527 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1529 DOUT << "Reusing SS#" << SSorRMId;
1530 DOUT << " from physreg "
1531 << TRI->getName(InReg) << " for vreg"
1532 << VirtReg <<" instead of reloading into physreg "
1533 << TRI->getName(Phys) << "\n";
1536 } else if (InReg && InReg != Phys) {
1538 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1540 DOUT << "Reusing SS#" << SSorRMId;
1541 DOUT << " from physreg "
1542 << TRI->getName(InReg) << " for vreg"
1543 << VirtReg <<" by copying it into physreg "
1544 << TRI->getName(Phys) << "\n";
1546 // If the reloaded / remat value is available in another register,
1547 // copy it to the desired register.
1548 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1550 // This invalidates Phys.
1551 Spills.ClobberPhysReg(Phys);
1552 // Remember it's available.
1553 Spills.addAvailable(SSorRMId, Phys);
1556 MachineInstr *CopyMI = prior(MII);
1557 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1558 KillOpnd->setIsKill();
1559 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1561 DOUT << '\t' << *CopyMI;
1566 if (VRM.isReMaterialized(VirtReg)) {
1567 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1569 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1570 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1571 MachineInstr *LoadMI = prior(MII);
1572 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1576 // This invalidates Phys.
1577 Spills.ClobberPhysReg(Phys);
1578 // Remember it's available.
1579 Spills.addAvailable(SSorRMId, Phys);
1581 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1582 DOUT << '\t' << *prior(MII);
1586 // Insert spills here if asked to.
1587 if (VRM.isSpillPt(&MI)) {
1588 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1589 VRM.getSpillPtSpills(&MI);
1590 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1591 unsigned VirtReg = SpillRegs[i].first;
1592 bool isKill = SpillRegs[i].second;
1593 if (!VRM.getPreSplitReg(VirtReg))
1594 continue; // Split interval spilled again.
1595 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1596 unsigned Phys = VRM.getPhys(VirtReg);
1597 int StackSlot = VRM.getStackSlot(VirtReg);
1598 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1599 MachineInstr *StoreMI = next(MII);
1600 VRM.addSpillSlotUse(StackSlot, StoreMI);
1601 DOUT << "Store:\t" << *StoreMI;
1602 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1604 NextMII = next(MII);
1607 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1609 ReuseInfo ReusedOperands(MI, TRI);
1610 SmallVector<unsigned, 4> VirtUseOps;
1611 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1612 MachineOperand &MO = MI.getOperand(i);
1613 if (!MO.isReg() || MO.getReg() == 0)
1614 continue; // Ignore non-register operands.
1616 unsigned VirtReg = MO.getReg();
1617 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1618 // Ignore physregs for spilling, but remember that it is used by this
1620 RegInfo->setPhysRegUsed(VirtReg);
1624 // We want to process implicit virtual register uses first.
1625 if (MO.isImplicit())
1626 // If the virtual register is implicitly defined, emit a implicit_def
1627 // before so scavenger knows it's "defined".
1628 // FIXME: This is a horrible hack done the by register allocator to
1629 // remat a definition with virtual register operand.
1630 VirtUseOps.insert(VirtUseOps.begin(), i);
1632 VirtUseOps.push_back(i);
1635 // Process all of the spilled uses and all non spilled reg references.
1636 SmallVector<int, 2> PotentialDeadStoreSlots;
1637 KilledMIRegs.clear();
1638 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1639 unsigned i = VirtUseOps[j];
1640 MachineOperand &MO = MI.getOperand(i);
1641 unsigned VirtReg = MO.getReg();
1642 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1643 "Not a virtual register?");
1645 unsigned SubIdx = MO.getSubReg();
1646 if (VRM.isAssignedReg(VirtReg)) {
1647 // This virtual register was assigned a physreg!
1648 unsigned Phys = VRM.getPhys(VirtReg);
1649 RegInfo->setPhysRegUsed(Phys);
1651 ReusedOperands.markClobbered(Phys);
1652 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1653 MI.getOperand(i).setReg(RReg);
1654 MI.getOperand(i).setSubReg(0);
1655 if (VRM.isImplicitlyDefined(VirtReg))
1656 // FIXME: Is this needed?
1657 BuildMI(MBB, &MI, MI.getDebugLoc(),
1658 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1662 // This virtual register is now known to be a spilled value.
1664 continue; // Handle defs in the loop below (handle use&def here though)
1666 bool AvoidReload = MO.isUndef();
1667 // Check if it is defined by an implicit def. It should not be spilled.
1668 // Note, this is for correctness reason. e.g.
1669 // 8 %reg1024<def> = IMPLICIT_DEF
1670 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1671 // The live range [12, 14) are not part of the r1024 live interval since
1672 // it's defined by an implicit def. It will not conflicts with live
1673 // interval of r1025. Now suppose both registers are spilled, you can
1674 // easily see a situation where both registers are reloaded before
1675 // the INSERT_SUBREG and both target registers that would overlap.
1676 bool DoReMat = VRM.isReMaterialized(VirtReg);
1677 int SSorRMId = DoReMat
1678 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1679 int ReuseSlot = SSorRMId;
1681 // Check to see if this stack slot is available.
1682 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1684 // If this is a sub-register use, make sure the reuse register is in the
1685 // right register class. For example, for x86 not all of the 32-bit
1686 // registers have accessible sub-registers.
1687 // Similarly so for EXTRACT_SUBREG. Consider this:
1689 // MOV32_mr fi#1, EDI
1691 // = EXTRACT_SUBREG fi#1
1692 // fi#1 is available in EDI, but it cannot be reused because it's not in
1693 // the right register file.
1694 if (PhysReg && !AvoidReload &&
1695 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1696 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1697 if (!RC->contains(PhysReg))
1701 if (PhysReg && !AvoidReload) {
1702 // This spilled operand might be part of a two-address operand. If this
1703 // is the case, then changing it will necessarily require changing the
1704 // def part of the instruction as well. However, in some cases, we
1705 // aren't allowed to modify the reused register. If none of these cases
1707 bool CanReuse = true;
1708 bool isTied = MI.isRegTiedToDefOperand(i);
1710 // Okay, we have a two address operand. We can reuse this physreg as
1711 // long as we are allowed to clobber the value and there isn't an
1712 // earlier def that has already clobbered the physreg.
1713 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1714 Spills.canClobberPhysReg(PhysReg);
1718 // If this stack slot value is already available, reuse it!
1719 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1720 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1722 DOUT << "Reusing SS#" << ReuseSlot;
1723 DOUT << " from physreg "
1724 << TRI->getName(PhysReg) << " for vreg"
1725 << VirtReg <<" instead of reloading into physreg "
1726 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1727 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1728 MI.getOperand(i).setReg(RReg);
1729 MI.getOperand(i).setSubReg(0);
1731 // The only technical detail we have is that we don't know that
1732 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1733 // later in the instruction. In particular, consider 'op V1, V2'.
1734 // If V1 is available in physreg R0, we would choose to reuse it
1735 // here, instead of reloading it into the register the allocator
1736 // indicated (say R1). However, V2 might have to be reloaded
1737 // later, and it might indicate that it needs to live in R0. When
1738 // this occurs, we need to have information available that
1739 // indicates it is safe to use R1 for the reload instead of R0.
1741 // To further complicate matters, we might conflict with an alias,
1742 // or R0 and R1 might not be compatible with each other. In this
1743 // case, we actually insert a reload for V1 in R1, ensuring that
1744 // we can get at R0 or its alias.
1745 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1746 VRM.getPhys(VirtReg), VirtReg);
1748 // Only mark it clobbered if this is a use&def operand.
1749 ReusedOperands.markClobbered(PhysReg);
1752 if (MI.getOperand(i).isKill() &&
1753 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1755 // The store of this spilled value is potentially dead, but we
1756 // won't know for certain until we've confirmed that the re-use
1757 // above is valid, which means waiting until the other operands
1758 // are processed. For now we just track the spill slot, we'll
1759 // remove it after the other operands are processed if valid.
1761 PotentialDeadStoreSlots.push_back(ReuseSlot);
1764 // Mark is isKill if it's there no other uses of the same virtual
1765 // register and it's not a two-address operand. IsKill will be
1766 // unset if reg is reused.
1767 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1768 MI.getOperand(i).setIsKill();
1769 KilledMIRegs.insert(VirtReg);
1775 // Otherwise we have a situation where we have a two-address instruction
1776 // whose mod/ref operand needs to be reloaded. This reload is already
1777 // available in some register "PhysReg", but if we used PhysReg as the
1778 // operand to our 2-addr instruction, the instruction would modify
1779 // PhysReg. This isn't cool if something later uses PhysReg and expects
1780 // to get its initial value.
1782 // To avoid this problem, and to avoid doing a load right after a store,
1783 // we emit a copy from PhysReg into the designated register for this
1785 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1786 assert(DesignatedReg && "Must map virtreg to physreg!");
1788 // Note that, if we reused a register for a previous operand, the
1789 // register we want to reload into might not actually be
1790 // available. If this occurs, use the register indicated by the
1792 if (ReusedOperands.hasReuses())
1793 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1794 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1796 // If the mapped designated register is actually the physreg we have
1797 // incoming, we don't need to inserted a dead copy.
1798 if (DesignatedReg == PhysReg) {
1799 // If this stack slot value is already available, reuse it!
1800 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1801 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1803 DOUT << "Reusing SS#" << ReuseSlot;
1804 DOUT << " from physreg " << TRI->getName(PhysReg)
1805 << " for vreg" << VirtReg
1806 << " instead of reloading into same physreg.\n";
1807 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1808 MI.getOperand(i).setReg(RReg);
1809 MI.getOperand(i).setSubReg(0);
1810 ReusedOperands.markClobbered(RReg);
1815 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1816 RegInfo->setPhysRegUsed(DesignatedReg);
1817 ReusedOperands.markClobbered(DesignatedReg);
1818 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1820 MachineInstr *CopyMI = prior(MII);
1821 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1823 // This invalidates DesignatedReg.
1824 Spills.ClobberPhysReg(DesignatedReg);
1826 Spills.addAvailable(ReuseSlot, DesignatedReg);
1828 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1829 MI.getOperand(i).setReg(RReg);
1830 MI.getOperand(i).setSubReg(0);
1831 DOUT << '\t' << *prior(MII);
1836 // Otherwise, reload it and remember that we have it.
1837 PhysReg = VRM.getPhys(VirtReg);
1838 assert(PhysReg && "Must map virtreg to physreg!");
1840 // Note that, if we reused a register for a previous operand, the
1841 // register we want to reload into might not actually be
1842 // available. If this occurs, use the register indicated by the
1844 if (ReusedOperands.hasReuses())
1845 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1846 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1848 RegInfo->setPhysRegUsed(PhysReg);
1849 ReusedOperands.markClobbered(PhysReg);
1854 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1856 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1857 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1858 MachineInstr *LoadMI = prior(MII);
1859 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1862 // This invalidates PhysReg.
1863 Spills.ClobberPhysReg(PhysReg);
1865 // Any stores to this stack slot are not dead anymore.
1867 MaybeDeadStores[SSorRMId] = NULL;
1868 Spills.addAvailable(SSorRMId, PhysReg);
1869 // Assumes this is the last use. IsKill will be unset if reg is reused
1870 // unless it's a two-address operand.
1871 if (!MI.isRegTiedToDefOperand(i) &&
1872 KilledMIRegs.count(VirtReg) == 0) {
1873 MI.getOperand(i).setIsKill();
1874 KilledMIRegs.insert(VirtReg);
1877 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1878 DOUT << '\t' << *prior(MII);
1880 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1881 MI.getOperand(i).setReg(RReg);
1882 MI.getOperand(i).setSubReg(0);
1885 // Ok - now we can remove stores that have been confirmed dead.
1886 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1887 // This was the last use and the spilled value is still available
1888 // for reuse. That means the spill was unnecessary!
1889 int PDSSlot = PotentialDeadStoreSlots[j];
1890 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1892 DOUT << "Removed dead store:\t" << *DeadStore;
1893 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1894 VRM.RemoveMachineInstrFromMaps(DeadStore);
1895 MBB.erase(DeadStore);
1896 MaybeDeadStores[PDSSlot] = NULL;
1905 // If we have folded references to memory operands, make sure we clear all
1906 // physical registers that may contain the value of the spilled virtual
1908 SmallSet<int, 2> FoldedSS;
1909 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1910 unsigned VirtReg = I->second.first;
1911 VirtRegMap::ModRef MR = I->second.second;
1912 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1914 // MI2VirtMap be can updated which invalidate the iterator.
1915 // Increment the iterator first.
1917 int SS = VRM.getStackSlot(VirtReg);
1918 if (SS == VirtRegMap::NO_STACK_SLOT)
1920 FoldedSS.insert(SS);
1921 DOUT << " - StackSlot: " << SS << "\n";
1923 // If this folded instruction is just a use, check to see if it's a
1924 // straight load from the virt reg slot.
1925 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1927 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1928 if (DestReg && FrameIdx == SS) {
1929 // If this spill slot is available, turn it into a copy (or nothing)
1930 // instead of leaving it as a load!
1931 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1932 DOUT << "Promoted Load To Copy: " << MI;
1933 if (DestReg != InReg) {
1934 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1935 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1936 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1937 unsigned SubIdx = DefMO->getSubReg();
1938 // Revisit the copy so we make sure to notice the effects of the
1939 // operation on the destreg (either needing to RA it if it's
1940 // virtual or needing to clobber any values if it's physical).
1942 --NextMII; // backtrack to the copy.
1943 // Propagate the sub-register index over.
1945 DefMO = NextMII->findRegisterDefOperand(DestReg);
1946 DefMO->setSubReg(SubIdx);
1950 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1951 KillOpnd->setIsKill();
1955 DOUT << "Removing now-noop copy: " << MI;
1956 // Unset last kill since it's being reused.
1957 InvalidateKill(InReg, TRI, RegKills, KillOps);
1958 Spills.disallowClobberPhysReg(InReg);
1961 InvalidateKills(MI, TRI, RegKills, KillOps);
1962 VRM.RemoveMachineInstrFromMaps(&MI);
1965 goto ProcessNextInst;
1968 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1969 SmallVector<MachineInstr*, 4> NewMIs;
1971 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1972 MBB.insert(MII, NewMIs[0]);
1973 InvalidateKills(MI, TRI, RegKills, KillOps);
1974 VRM.RemoveMachineInstrFromMaps(&MI);
1977 --NextMII; // backtrack to the unfolded instruction.
1979 goto ProcessNextInst;
1984 // If this reference is not a use, any previous store is now dead.
1985 // Otherwise, the store to this stack slot is not dead anymore.
1986 MachineInstr* DeadStore = MaybeDeadStores[SS];
1988 bool isDead = !(MR & VirtRegMap::isRef);
1989 MachineInstr *NewStore = NULL;
1990 if (MR & VirtRegMap::isModRef) {
1991 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1992 SmallVector<MachineInstr*, 4> NewMIs;
1993 // We can reuse this physreg as long as we are allowed to clobber
1994 // the value and there isn't an earlier def that has already clobbered
1997 !ReusedOperands.isClobbered(PhysReg) &&
1998 Spills.canClobberPhysReg(PhysReg) &&
1999 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2000 MachineOperand *KillOpnd =
2001 DeadStore->findRegisterUseOperand(PhysReg, true);
2002 // Note, if the store is storing a sub-register, it's possible the
2003 // super-register is needed below.
2004 if (KillOpnd && !KillOpnd->getSubReg() &&
2005 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2006 MBB.insert(MII, NewMIs[0]);
2007 NewStore = NewMIs[1];
2008 MBB.insert(MII, NewStore);
2009 VRM.addSpillSlotUse(SS, NewStore);
2010 InvalidateKills(MI, TRI, RegKills, KillOps);
2011 VRM.RemoveMachineInstrFromMaps(&MI);
2015 --NextMII; // backtrack to the unfolded instruction.
2023 if (isDead) { // Previous store is dead.
2024 // If we get here, the store is dead, nuke it now.
2025 DOUT << "Removed dead store:\t" << *DeadStore;
2026 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2027 VRM.RemoveMachineInstrFromMaps(DeadStore);
2028 MBB.erase(DeadStore);
2033 MaybeDeadStores[SS] = NULL;
2035 // Treat this store as a spill merged into a copy. That makes the
2036 // stack slot value available.
2037 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2038 goto ProcessNextInst;
2042 // If the spill slot value is available, and this is a new definition of
2043 // the value, the value is not available anymore.
2044 if (MR & VirtRegMap::isMod) {
2045 // Notice that the value in this stack slot has been modified.
2046 Spills.ModifyStackSlotOrReMat(SS);
2048 // If this is *just* a mod of the value, check to see if this is just a
2049 // store to the spill slot (i.e. the spill got merged into the copy). If
2050 // so, realize that the vreg is available now, and add the store to the
2051 // MaybeDeadStore info.
2053 if (!(MR & VirtRegMap::isRef)) {
2054 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2055 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2056 "Src hasn't been allocated yet?");
2058 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2059 Spills, RegKills, KillOps, TRI, VRM)) {
2060 NextMII = next(MII);
2062 goto ProcessNextInst;
2065 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2066 // this as a potentially dead store in case there is a subsequent
2067 // store into the stack slot without a read from it.
2068 MaybeDeadStores[StackSlot] = &MI;
2070 // If the stack slot value was previously available in some other
2071 // register, change it now. Otherwise, make the register
2072 // available in PhysReg.
2073 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2079 // Process all of the spilled defs.
2080 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2081 MachineOperand &MO = MI.getOperand(i);
2082 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2085 unsigned VirtReg = MO.getReg();
2086 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2087 // Check to see if this is a noop copy. If so, eliminate the
2088 // instruction before considering the dest reg to be changed.
2089 // Also check if it's copying from an "undef", if so, we can't
2090 // eliminate this or else the undef marker is lost and it will
2091 // confuses the scavenger. This is extremely rare.
2092 unsigned Src, Dst, SrcSR, DstSR;
2093 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2094 !MI.findRegisterUseOperand(Src)->isUndef()) {
2096 DOUT << "Removing now-noop copy: " << MI;
2097 SmallVector<unsigned, 2> KillRegs;
2098 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2099 if (MO.isDead() && !KillRegs.empty()) {
2100 // Source register or an implicit super/sub-register use is killed.
2101 assert(KillRegs[0] == Dst ||
2102 TRI->isSubRegister(KillRegs[0], Dst) ||
2103 TRI->isSuperRegister(KillRegs[0], Dst));
2104 // Last def is now dead.
2105 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2107 VRM.RemoveMachineInstrFromMaps(&MI);
2110 Spills.disallowClobberPhysReg(VirtReg);
2111 goto ProcessNextInst;
2114 // If it's not a no-op copy, it clobbers the value in the destreg.
2115 Spills.ClobberPhysReg(VirtReg);
2116 ReusedOperands.markClobbered(VirtReg);
2118 // Check to see if this instruction is a load from a stack slot into
2119 // a register. If so, this provides the stack slot value in the reg.
2121 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2122 assert(DestReg == VirtReg && "Unknown load situation!");
2124 // If it is a folded reference, then it's not safe to clobber.
2125 bool Folded = FoldedSS.count(FrameIdx);
2126 // Otherwise, if it wasn't available, remember that it is now!
2127 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2128 goto ProcessNextInst;
2134 unsigned SubIdx = MO.getSubReg();
2135 bool DoReMat = VRM.isReMaterialized(VirtReg);
2137 ReMatDefs.insert(&MI);
2139 // The only vregs left are stack slot definitions.
2140 int StackSlot = VRM.getStackSlot(VirtReg);
2141 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2143 // If this def is part of a two-address operand, make sure to execute
2144 // the store from the correct physical register.
2147 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2148 PhysReg = MI.getOperand(TiedOp).getReg();
2150 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2151 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2152 "Can't find corresponding super-register!");
2156 PhysReg = VRM.getPhys(VirtReg);
2157 if (ReusedOperands.isClobbered(PhysReg)) {
2158 // Another def has taken the assigned physreg. It must have been a
2159 // use&def which got it due to reuse. Undo the reuse!
2160 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2161 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2165 assert(PhysReg && "VR not assigned a physical register?");
2166 RegInfo->setPhysRegUsed(PhysReg);
2167 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2168 ReusedOperands.markClobbered(RReg);
2169 MI.getOperand(i).setReg(RReg);
2170 MI.getOperand(i).setSubReg(0);
2173 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2174 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2175 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2176 NextMII = next(MII);
2178 // Check to see if this is a noop copy. If so, eliminate the
2179 // instruction before considering the dest reg to be changed.
2181 unsigned Src, Dst, SrcSR, DstSR;
2182 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2184 DOUT << "Removing now-noop copy: " << MI;
2185 InvalidateKills(MI, TRI, RegKills, KillOps);
2186 VRM.RemoveMachineInstrFromMaps(&MI);
2189 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2190 goto ProcessNextInst;
2196 // Delete dead instructions without side effects.
2197 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2198 InvalidateKills(MI, TRI, RegKills, KillOps);
2199 VRM.RemoveMachineInstrFromMaps(&MI);
2204 DistanceMap.insert(std::make_pair(&MI, Dist++));
2205 if (!Erased && !BackTracked) {
2206 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2207 UpdateKills(*II, TRI, RegKills, KillOps);
2216 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2217 switch (RewriterOpt) {
2218 default: llvm_unreachable("Unreachable!");
2220 return new LocalRewriter();
2222 return new TrivialRewriter();