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/ADT/DepthFirstIterator.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/ADT/STLExtras.h"
19 STATISTIC(NumDSE , "Number of dead stores elided");
20 STATISTIC(NumDSS , "Number of dead spill slots removed");
21 STATISTIC(NumCommutes, "Number of instructions commuted");
22 STATISTIC(NumDRM , "Number of re-materializable defs elided");
23 STATISTIC(NumStores , "Number of stores added");
24 STATISTIC(NumPSpills , "Number of physical register spills");
25 STATISTIC(NumOmitted , "Number of reloads omited");
26 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
27 STATISTIC(NumCopified, "Number of available reloads turned into copies");
28 STATISTIC(NumReMats , "Number of re-materialization");
29 STATISTIC(NumLoads , "Number of loads added");
30 STATISTIC(NumReused , "Number of values reused");
31 STATISTIC(NumDCE , "Number of copies elided");
32 STATISTIC(NumSUnfold , "Number of stores unfolded");
33 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
36 enum RewriterName { local, trivial };
39 static cl::opt<RewriterName>
40 RewriterOpt("rewriter",
41 cl::desc("Rewriter to use: (default: local)"),
43 cl::values(clEnumVal(local, "local rewriter"),
44 clEnumVal(trivial, "trivial rewriter"),
48 VirtRegRewriter::~VirtRegRewriter() {}
52 /// This class is intended for use with the new spilling framework only. It
53 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
55 struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
57 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
59 DOUT << "********** REWRITE MACHINE CODE **********\n";
60 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
61 MachineRegisterInfo *mri = &MF.getRegInfo();
65 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
66 liItr != liEnd; ++liItr) {
68 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
69 if (VRM.hasPhys(liItr->first)) {
70 unsigned preg = VRM.getPhys(liItr->first);
71 mri->replaceRegWith(liItr->first, preg);
72 mri->setPhysRegUsed(preg);
77 if (!liItr->second->empty()) {
78 mri->setPhysRegUsed(liItr->first);
88 // ************************************************************************ //
90 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
91 /// from top down, keep track of which spill slots or remat are available in
94 /// Note that not all physregs are created equal here. In particular, some
95 /// physregs are reloads that we are allowed to clobber or ignore at any time.
96 /// Other physregs are values that the register allocated program is using
97 /// that we cannot CHANGE, but we can read if we like. We keep track of this
98 /// on a per-stack-slot / remat id basis as the low bit in the value of the
99 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
100 /// this bit and addAvailable sets it if.
101 class VISIBILITY_HIDDEN AvailableSpills {
102 const TargetRegisterInfo *TRI;
103 const TargetInstrInfo *TII;
105 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
106 // or remat'ed virtual register values that are still available, due to
107 // being loaded or stored to, but not invalidated yet.
108 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
110 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
111 // indicating which stack slot values are currently held by a physreg. This
112 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
113 // physreg is modified.
114 std::multimap<unsigned, int> PhysRegsAvailable;
116 void disallowClobberPhysRegOnly(unsigned PhysReg);
118 void ClobberPhysRegOnly(unsigned PhysReg);
120 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
121 : TRI(tri), TII(tii) {
124 /// clear - Reset the state.
126 SpillSlotsOrReMatsAvailable.clear();
127 PhysRegsAvailable.clear();
130 const TargetRegisterInfo *getRegInfo() const { return TRI; }
132 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
133 /// available in a physical register, return that PhysReg, otherwise
135 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
136 std::map<int, unsigned>::const_iterator I =
137 SpillSlotsOrReMatsAvailable.find(Slot);
138 if (I != SpillSlotsOrReMatsAvailable.end()) {
139 return I->second >> 1; // Remove the CanClobber bit.
144 /// addAvailable - Mark that the specified stack slot / remat is available
145 /// in the specified physreg. If CanClobber is true, the physreg can be
146 /// modified at any time without changing the semantics of the program.
147 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
148 // If this stack slot is thought to be available in some other physreg,
149 // remove its record.
150 ModifyStackSlotOrReMat(SlotOrReMat);
152 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
153 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
154 (unsigned)CanClobber;
156 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
157 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
159 DOUT << "Remembering SS#" << SlotOrReMat;
160 DOUT << " in physreg " << TRI->getName(Reg) << "\n";
163 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
164 /// the value of the specified stackslot register if it desires. The
165 /// specified stack slot must be available in a physreg for this query to
167 bool canClobberPhysRegForSS(int SlotOrReMat) const {
168 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
169 "Value not available!");
170 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
173 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
174 /// physical register where values for some stack slot(s) might be
176 bool canClobberPhysReg(unsigned PhysReg) const {
177 std::multimap<unsigned, int>::const_iterator I =
178 PhysRegsAvailable.lower_bound(PhysReg);
179 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
180 int SlotOrReMat = I->second;
182 if (!canClobberPhysRegForSS(SlotOrReMat))
188 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
189 /// stackslot register. The register is still available but is no longer
190 /// allowed to be modifed.
191 void disallowClobberPhysReg(unsigned PhysReg);
193 /// ClobberPhysReg - This is called when the specified physreg changes
194 /// value. We use this to invalidate any info about stuff that lives in
195 /// it and any of its aliases.
196 void ClobberPhysReg(unsigned PhysReg);
198 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
199 /// slot changes. This removes information about which register the
200 /// previous value for this slot lives in (as the previous value is dead
202 void ModifyStackSlotOrReMat(int SlotOrReMat);
204 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
205 /// into the specified MBB. Add available physical registers as potential
206 /// live-in's. If they are reused in the MBB, they will be added to the
207 /// live-in set to make register scavenger and post-allocation scheduler.
208 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
209 std::vector<MachineOperand*> &KillOps);
212 // ************************************************************************ //
214 // ReusedOp - For each reused operand, we keep track of a bit of information,
215 // in case we need to rollback upon processing a new operand. See comments
218 // The MachineInstr operand that reused an available value.
221 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
222 unsigned StackSlotOrReMat;
224 // PhysRegReused - The physical register the value was available in.
225 unsigned PhysRegReused;
227 // AssignedPhysReg - The physreg that was assigned for use by the reload.
228 unsigned AssignedPhysReg;
230 // VirtReg - The virtual register itself.
233 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
235 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
236 AssignedPhysReg(apr), VirtReg(vreg) {}
239 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
240 /// is reused instead of reloaded.
241 class VISIBILITY_HIDDEN ReuseInfo {
243 std::vector<ReusedOp> Reuses;
244 BitVector PhysRegsClobbered;
246 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
247 PhysRegsClobbered.resize(tri->getNumRegs());
250 bool hasReuses() const {
251 return !Reuses.empty();
254 /// addReuse - If we choose to reuse a virtual register that is already
255 /// available instead of reloading it, remember that we did so.
256 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
257 unsigned PhysRegReused, unsigned AssignedPhysReg,
259 // If the reload is to the assigned register anyway, no undo will be
261 if (PhysRegReused == AssignedPhysReg) return;
263 // Otherwise, remember this.
264 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
265 AssignedPhysReg, VirtReg));
268 void markClobbered(unsigned PhysReg) {
269 PhysRegsClobbered.set(PhysReg);
272 bool isClobbered(unsigned PhysReg) const {
273 return PhysRegsClobbered.test(PhysReg);
276 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
277 /// is some other operand that is using the specified register, either pick
278 /// a new register to use, or evict the previous reload and use this reg.
279 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
280 AvailableSpills &Spills,
281 std::vector<MachineInstr*> &MaybeDeadStores,
282 SmallSet<unsigned, 8> &Rejected,
284 std::vector<MachineOperand*> &KillOps,
287 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
288 /// 'Rejected' set to remember which registers have been considered and
289 /// rejected for the reload. This avoids infinite looping in case like
292 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
293 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
295 /// sees r1 is taken by t2, tries t2's reload register r0
296 /// sees r0 is taken by t3, tries t3's reload register r1
297 /// sees r1 is taken by t2, tries t2's reload register r0 ...
298 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
299 AvailableSpills &Spills,
300 std::vector<MachineInstr*> &MaybeDeadStores,
302 std::vector<MachineOperand*> &KillOps,
304 SmallSet<unsigned, 8> Rejected;
305 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
306 RegKills, KillOps, VRM);
311 // ****************** //
312 // Utility Functions //
313 // ****************** //
315 /// findSinglePredSuccessor - Return via reference a vector of machine basic
316 /// blocks each of which is a successor of the specified BB and has no other
318 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
319 SmallVectorImpl<MachineBasicBlock *> &Succs) {
320 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
321 SE = MBB->succ_end(); SI != SE; ++SI) {
322 MachineBasicBlock *SuccMBB = *SI;
323 if (SuccMBB->pred_size() == 1)
324 Succs.push_back(SuccMBB);
328 /// InvalidateKill - Invalidate register kill information for a specific
329 /// register. This also unsets the kills marker on the last kill operand.
330 static void InvalidateKill(unsigned Reg,
331 const TargetRegisterInfo* TRI,
333 std::vector<MachineOperand*> &KillOps) {
335 KillOps[Reg]->setIsKill(false);
336 // KillOps[Reg] might be a def of a super-register.
337 unsigned KReg = KillOps[Reg]->getReg();
338 KillOps[KReg] = NULL;
339 RegKills.reset(KReg);
340 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
342 KillOps[*SR]->setIsKill(false);
350 /// InvalidateKills - MI is going to be deleted. If any of its operands are
351 /// marked kill, then invalidate the information.
352 static void InvalidateKills(MachineInstr &MI,
353 const TargetRegisterInfo* TRI,
355 std::vector<MachineOperand*> &KillOps,
356 SmallVector<unsigned, 2> *KillRegs = NULL) {
357 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
358 MachineOperand &MO = MI.getOperand(i);
359 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
361 unsigned Reg = MO.getReg();
362 if (TargetRegisterInfo::isVirtualRegister(Reg))
365 KillRegs->push_back(Reg);
366 assert(Reg < KillOps.size());
367 if (KillOps[Reg] == &MO) {
370 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
380 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
381 /// (since it's spill instruction is removed), mark it isDead. Also checks if
382 /// the def MI has other definition operands that are not dead. Returns it by
384 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
385 MachineInstr &NewDef, unsigned Reg,
387 // Due to remat, it's possible this reg isn't being reused. That is,
388 // the def of this reg (by prev MI) is now dead.
389 MachineInstr *DefMI = I;
390 MachineOperand *DefOp = NULL;
391 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
392 MachineOperand &MO = DefMI->getOperand(i);
393 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
395 if (MO.getReg() == Reg)
397 else if (!MO.isDead())
403 bool FoundUse = false, Done = false;
404 MachineBasicBlock::iterator E = &NewDef;
406 for (; !Done && I != E; ++I) {
407 MachineInstr *NMI = I;
408 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
409 MachineOperand &MO = NMI->getOperand(j);
410 if (!MO.isReg() || MO.getReg() != Reg)
414 Done = true; // Stop after scanning all the operands of this MI.
425 /// UpdateKills - Track and update kill info. If a MI reads a register that is
426 /// marked kill, then it must be due to register reuse. Transfer the kill info
428 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
430 std::vector<MachineOperand*> &KillOps) {
431 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
432 MachineOperand &MO = MI.getOperand(i);
433 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
435 unsigned Reg = MO.getReg();
439 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
440 // That can't be right. Register is killed but not re-defined and it's
441 // being reused. Let's fix that.
442 KillOps[Reg]->setIsKill(false);
443 // KillOps[Reg] might be a def of a super-register.
444 unsigned KReg = KillOps[Reg]->getReg();
445 KillOps[KReg] = NULL;
446 RegKills.reset(KReg);
448 // Must be a def of a super-register. Its other sub-regsters are no
449 // longer killed as well.
450 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
455 if (!MI.isRegTiedToDefOperand(i))
456 // Unless it's a two-address operand, this is the new kill.
462 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
469 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
470 const MachineOperand &MO = MI.getOperand(i);
471 if (!MO.isReg() || !MO.isDef())
473 unsigned Reg = MO.getReg();
476 // It also defines (or partially define) aliases.
477 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
484 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
486 static void ReMaterialize(MachineBasicBlock &MBB,
487 MachineBasicBlock::iterator &MII,
488 unsigned DestReg, unsigned Reg,
489 const TargetInstrInfo *TII,
490 const TargetRegisterInfo *TRI,
492 TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
493 MachineInstr *NewMI = prior(MII);
494 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
495 MachineOperand &MO = NewMI->getOperand(i);
496 if (!MO.isReg() || MO.getReg() == 0)
498 unsigned VirtReg = MO.getReg();
499 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
502 unsigned SubIdx = MO.getSubReg();
503 unsigned Phys = VRM.getPhys(VirtReg);
505 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
512 /// findSuperReg - Find the SubReg's super-register of given register class
513 /// where its SubIdx sub-register is SubReg.
514 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
515 unsigned SubIdx, const TargetRegisterInfo *TRI) {
516 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
519 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
525 // ******************************** //
526 // Available Spills Implementation //
527 // ******************************** //
529 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
530 /// stackslot register. The register is still available but is no longer
531 /// allowed to be modifed.
532 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
533 std::multimap<unsigned, int>::iterator I =
534 PhysRegsAvailable.lower_bound(PhysReg);
535 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
536 int SlotOrReMat = I->second;
538 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
539 "Bidirectional map mismatch!");
540 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
541 DOUT << "PhysReg " << TRI->getName(PhysReg)
542 << " copied, it is available for use but can no longer be modified\n";
546 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
547 /// stackslot register and its aliases. The register and its aliases may
548 /// still available but is no longer allowed to be modifed.
549 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
550 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
551 disallowClobberPhysRegOnly(*AS);
552 disallowClobberPhysRegOnly(PhysReg);
555 /// ClobberPhysRegOnly - This is called when the specified physreg changes
556 /// value. We use this to invalidate any info about stuff we thing lives in it.
557 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
558 std::multimap<unsigned, int>::iterator I =
559 PhysRegsAvailable.lower_bound(PhysReg);
560 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
561 int SlotOrReMat = I->second;
562 PhysRegsAvailable.erase(I++);
563 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
564 "Bidirectional map mismatch!");
565 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
566 DOUT << "PhysReg " << TRI->getName(PhysReg)
567 << " clobbered, invalidating ";
568 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
569 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
571 DOUT << "SS#" << SlotOrReMat << "\n";
575 /// ClobberPhysReg - This is called when the specified physreg changes
576 /// value. We use this to invalidate any info about stuff we thing lives in
577 /// it and any of its aliases.
578 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
579 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
580 ClobberPhysRegOnly(*AS);
581 ClobberPhysRegOnly(PhysReg);
584 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
585 /// into the specified MBB. Add available physical registers as potential
586 /// live-in's. If they are reused in the MBB, they will be added to the
587 /// live-in set to make register scavenger and post-allocation scheduler.
588 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
590 std::vector<MachineOperand*> &KillOps) {
591 std::set<unsigned> NotAvailable;
592 for (std::multimap<unsigned, int>::iterator
593 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
595 unsigned Reg = I->first;
596 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
597 // FIXME: A temporary workaround. We can't reuse available value if it's
598 // not safe to move the def of the virtual register's class. e.g.
599 // X86::RFP* register classes. Do not add it as a live-in.
600 if (!TII->isSafeToMoveRegClassDefs(RC))
601 // This is no longer available.
602 NotAvailable.insert(Reg);
605 InvalidateKill(Reg, TRI, RegKills, KillOps);
608 // Skip over the same register.
609 std::multimap<unsigned, int>::iterator NI = next(I);
610 while (NI != E && NI->first == Reg) {
616 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
617 E = NotAvailable.end(); I != E; ++I) {
619 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
621 ClobberPhysReg(*SubRegs);
625 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
626 /// slot changes. This removes information about which register the previous
627 /// value for this slot lives in (as the previous value is dead now).
628 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
629 std::map<int, unsigned>::iterator It =
630 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
631 if (It == SpillSlotsOrReMatsAvailable.end()) return;
632 unsigned Reg = It->second >> 1;
633 SpillSlotsOrReMatsAvailable.erase(It);
635 // This register may hold the value of multiple stack slots, only remove this
636 // stack slot from the set of values the register contains.
637 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
639 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
640 "Map inverse broken!");
641 if (I->second == SlotOrReMat) break;
643 PhysRegsAvailable.erase(I);
646 // ************************** //
647 // Reuse Info Implementation //
648 // ************************** //
650 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
651 /// is some other operand that is using the specified register, either pick
652 /// a new register to use, or evict the previous reload and use this reg.
653 unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
654 AvailableSpills &Spills,
655 std::vector<MachineInstr*> &MaybeDeadStores,
656 SmallSet<unsigned, 8> &Rejected,
658 std::vector<MachineOperand*> &KillOps,
660 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
663 if (Reuses.empty()) return PhysReg; // This is most often empty.
665 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
666 ReusedOp &Op = Reuses[ro];
667 // If we find some other reuse that was supposed to use this register
668 // exactly for its reload, we can change this reload to use ITS reload
669 // register. That is, unless its reload register has already been
670 // considered and subsequently rejected because it has also been reused
671 // by another operand.
672 if (Op.PhysRegReused == PhysReg &&
673 Rejected.count(Op.AssignedPhysReg) == 0) {
674 // Yup, use the reload register that we didn't use before.
675 unsigned NewReg = Op.AssignedPhysReg;
676 Rejected.insert(PhysReg);
677 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
678 RegKills, KillOps, VRM);
680 // Otherwise, we might also have a problem if a previously reused
681 // value aliases the new register. If so, codegen the previous reload
683 unsigned PRRU = Op.PhysRegReused;
684 const TargetRegisterInfo *TRI = Spills.getRegInfo();
685 if (TRI->areAliases(PRRU, PhysReg)) {
686 // Okay, we found out that an alias of a reused register
687 // was used. This isn't good because it means we have
688 // to undo a previous reuse.
689 MachineBasicBlock *MBB = MI->getParent();
690 const TargetRegisterClass *AliasRC =
691 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
693 // Copy Op out of the vector and remove it, we're going to insert an
694 // explicit load for it.
696 Reuses.erase(Reuses.begin()+ro);
698 // Ok, we're going to try to reload the assigned physreg into the
699 // slot that we were supposed to in the first place. However, that
700 // register could hold a reuse. Check to see if it conflicts or
701 // would prefer us to use a different register.
702 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
703 MI, Spills, MaybeDeadStores,
704 Rejected, RegKills, KillOps, VRM);
706 MachineBasicBlock::iterator MII = MI;
707 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
708 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
710 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
711 NewOp.StackSlotOrReMat, AliasRC);
712 MachineInstr *LoadMI = prior(MII);
713 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
714 // Any stores to this stack slot are not dead anymore.
715 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
718 Spills.ClobberPhysReg(NewPhysReg);
719 Spills.ClobberPhysReg(NewOp.PhysRegReused);
721 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
722 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
723 MI->getOperand(NewOp.Operand).setReg(RReg);
724 MI->getOperand(NewOp.Operand).setSubReg(0);
726 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
728 UpdateKills(*MII, TRI, RegKills, KillOps);
729 DOUT << '\t' << *MII;
731 DOUT << "Reuse undone!\n";
734 // Finally, PhysReg is now available, go ahead and use it.
742 // ************************************************************************ //
744 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
745 /// stack slot mod/ref. It also checks if it's possible to unfold the
746 /// instruction by having it define a specified physical register instead.
747 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
748 const TargetInstrInfo *TII,
749 const TargetRegisterInfo *TRI,
751 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
755 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
756 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
757 unsigned VirtReg = I->second.first;
758 VirtRegMap::ModRef MR = I->second.second;
759 if (MR & VirtRegMap::isModRef)
760 if (VRM.getStackSlot(VirtReg) == SS) {
761 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
768 // Does the instruction uses a register that overlaps the scratch register?
769 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
770 MachineOperand &MO = MI.getOperand(i);
771 if (!MO.isReg() || MO.getReg() == 0)
773 unsigned Reg = MO.getReg();
774 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
775 if (!VRM.hasPhys(Reg))
777 Reg = VRM.getPhys(Reg);
779 if (TRI->regsOverlap(PhysReg, Reg))
785 /// FindFreeRegister - Find a free register of a given register class by looking
786 /// at (at most) the last two machine instructions.
787 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
788 MachineBasicBlock &MBB,
789 const TargetRegisterClass *RC,
790 const TargetRegisterInfo *TRI,
791 BitVector &AllocatableRegs) {
792 BitVector Defs(TRI->getNumRegs());
793 BitVector Uses(TRI->getNumRegs());
794 SmallVector<unsigned, 4> LocalUses;
795 SmallVector<unsigned, 4> Kills;
797 // Take a look at 2 instructions at most.
798 for (unsigned Count = 0; Count < 2; ++Count) {
799 if (MII == MBB.begin())
801 MachineInstr *PrevMI = prior(MII);
802 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
803 MachineOperand &MO = PrevMI->getOperand(i);
804 if (!MO.isReg() || MO.getReg() == 0)
806 unsigned Reg = MO.getReg();
809 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
812 LocalUses.push_back(Reg);
813 if (MO.isKill() && AllocatableRegs[Reg])
814 Kills.push_back(Reg);
818 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
819 unsigned Kill = Kills[i];
820 if (!Defs[Kill] && !Uses[Kill] &&
821 TRI->getPhysicalRegisterRegClass(Kill) == RC)
824 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
825 unsigned Reg = LocalUses[i];
827 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
838 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
839 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
840 MachineOperand &MO = MI->getOperand(i);
841 if (MO.isReg() && MO.getReg() == VirtReg)
848 bool operator()(const std::pair<MachineInstr*, int> &A,
849 const std::pair<MachineInstr*, int> &B) {
850 return A.second < B.second;
855 // ***************************** //
856 // Local Spiller Implementation //
857 // ***************************** //
859 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
860 MachineRegisterInfo *RegInfo;
861 const TargetRegisterInfo *TRI;
862 const TargetInstrInfo *TII;
863 BitVector AllocatableRegs;
864 DenseMap<MachineInstr*, unsigned> DistanceMap;
867 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
868 LiveIntervals* LIs) {
869 RegInfo = &MF.getRegInfo();
870 TRI = MF.getTarget().getRegisterInfo();
871 TII = MF.getTarget().getInstrInfo();
872 AllocatableRegs = TRI->getAllocatableSet(MF);
873 DOUT << "\n**** Local spiller rewriting function '"
874 << MF.getFunction()->getName() << "':\n";
875 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
879 // Spills - Keep track of which spilled values are available in physregs
880 // so that we can choose to reuse the physregs instead of emitting
881 // reloads. This is usually refreshed per basic block.
882 AvailableSpills Spills(TRI, TII);
884 // Keep track of kill information.
885 BitVector RegKills(TRI->getNumRegs());
886 std::vector<MachineOperand*> KillOps;
887 KillOps.resize(TRI->getNumRegs(), NULL);
889 // SingleEntrySuccs - Successor blocks which have a single predecessor.
890 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
891 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
893 // Traverse the basic blocks depth first.
894 MachineBasicBlock *Entry = MF.begin();
895 SmallPtrSet<MachineBasicBlock*,16> Visited;
896 for (df_ext_iterator<MachineBasicBlock*,
897 SmallPtrSet<MachineBasicBlock*,16> >
898 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
900 MachineBasicBlock *MBB = *DFI;
901 if (!EarlyVisited.count(MBB))
902 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
904 // If this MBB is the only predecessor of a successor. Keep the
905 // availability information and visit it next.
907 // Keep visiting single predecessor successor as long as possible.
908 SinglePredSuccs.clear();
909 findSinglePredSuccessor(MBB, SinglePredSuccs);
910 if (SinglePredSuccs.empty())
913 // FIXME: More than one successors, each of which has MBB has
914 // the only predecessor.
915 MBB = SinglePredSuccs[0];
916 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
917 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
918 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
923 // Clear the availability info.
927 DOUT << "**** Post Machine Instrs ****\n";
930 // Mark unused spill slots.
931 MachineFrameInfo *MFI = MF.getFrameInfo();
932 int SS = VRM.getLowSpillSlot();
933 if (SS != VirtRegMap::NO_STACK_SLOT)
934 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
935 if (!VRM.isSpillSlotUsed(SS)) {
936 MFI->RemoveStackObject(SS);
945 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
946 /// a scratch register is available.
947 /// xorq %r12<kill>, %r13
948 /// addq %rax, -184(%rbp)
949 /// addq %r13, -184(%rbp)
951 /// xorq %r12<kill>, %r13
952 /// movq -184(%rbp), %r12
955 /// movq %r12, -184(%rbp)
956 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
957 MachineBasicBlock &MBB,
958 MachineBasicBlock::iterator &MII,
959 std::vector<MachineInstr*> &MaybeDeadStores,
960 AvailableSpills &Spills,
962 std::vector<MachineOperand*> &KillOps,
965 MachineBasicBlock::iterator NextMII = next(MII);
966 if (NextMII == MBB.end())
969 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
972 // Now let's see if the last couple of instructions happens to have freed up
974 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
975 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
979 MachineFunction &MF = *MBB.getParent();
980 TRI = MF.getTarget().getRegisterInfo();
981 MachineInstr &MI = *MII;
982 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
985 // If the next instruction also folds the same SS modref and can be unfoled,
986 // then it's worthwhile to issue a load from SS into the free register and
987 // then unfold these instructions.
988 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
991 // Load from SS to the spare physical register.
992 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
993 // This invalidates Phys.
994 Spills.ClobberPhysReg(PhysReg);
995 // Remember it's available.
996 Spills.addAvailable(SS, PhysReg);
997 MaybeDeadStores[SS] = NULL;
999 // Unfold current MI.
1000 SmallVector<MachineInstr*, 4> NewMIs;
1001 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1002 assert(0 && "Unable unfold the load / store folding instruction!");
1003 assert(NewMIs.size() == 1);
1004 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1005 VRM.transferRestorePts(&MI, NewMIs[0]);
1006 MII = MBB.insert(MII, NewMIs[0]);
1007 InvalidateKills(MI, TRI, RegKills, KillOps);
1008 VRM.RemoveMachineInstrFromMaps(&MI);
1012 // Unfold next instructions that fold the same SS.
1014 MachineInstr &NextMI = *NextMII;
1015 NextMII = next(NextMII);
1017 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1018 assert(0 && "Unable unfold the load / store folding instruction!");
1019 assert(NewMIs.size() == 1);
1020 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1021 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1022 MBB.insert(NextMII, NewMIs[0]);
1023 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1024 VRM.RemoveMachineInstrFromMaps(&NextMI);
1027 if (NextMII == MBB.end())
1029 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1031 // Store the value back into SS.
1032 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1033 MachineInstr *StoreMI = prior(NextMII);
1034 VRM.addSpillSlotUse(SS, StoreMI);
1035 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1040 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1041 /// instruction. e.g.
1043 /// movl %eax, -32(%ebp)
1044 /// movl -36(%ebp), %eax
1045 /// orl %eax, -32(%ebp)
1048 /// orl -36(%ebp), %eax
1049 /// mov %eax, -32(%ebp)
1050 /// This enables unfolding optimization for a subsequent instruction which will
1051 /// also eliminate the newly introduced store instruction.
1052 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1053 MachineBasicBlock::iterator &MII,
1054 std::vector<MachineInstr*> &MaybeDeadStores,
1055 AvailableSpills &Spills,
1056 BitVector &RegKills,
1057 std::vector<MachineOperand*> &KillOps,
1059 MachineFunction &MF = *MBB.getParent();
1060 MachineInstr &MI = *MII;
1061 unsigned UnfoldedOpc = 0;
1062 unsigned UnfoldPR = 0;
1063 unsigned UnfoldVR = 0;
1064 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1065 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1066 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1067 // Only transform a MI that folds a single register.
1070 UnfoldVR = I->second.first;
1071 VirtRegMap::ModRef MR = I->second.second;
1072 // MI2VirtMap be can updated which invalidate the iterator.
1073 // Increment the iterator first.
1075 if (VRM.isAssignedReg(UnfoldVR))
1077 // If this reference is not a use, any previous store is now dead.
1078 // Otherwise, the store to this stack slot is not dead anymore.
1079 FoldedSS = VRM.getStackSlot(UnfoldVR);
1080 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1081 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1082 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1083 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1086 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1095 // Look for other unfolding opportunities.
1096 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1097 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1100 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1101 MachineOperand &MO = MI.getOperand(i);
1102 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1104 unsigned VirtReg = MO.getReg();
1105 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1107 if (VRM.isAssignedReg(VirtReg)) {
1108 unsigned PhysReg = VRM.getPhys(VirtReg);
1109 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1111 } else if (VRM.isReMaterialized(VirtReg))
1113 int SS = VRM.getStackSlot(VirtReg);
1114 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1116 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1120 if (VRM.hasPhys(VirtReg)) {
1121 PhysReg = VRM.getPhys(VirtReg);
1122 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1126 // Ok, we'll need to reload the value into a register which makes
1127 // it impossible to perform the store unfolding optimization later.
1128 // Let's see if it is possible to fold the load if the store is
1129 // unfolded. This allows us to perform the store unfolding
1131 SmallVector<MachineInstr*, 4> NewMIs;
1132 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1133 assert(NewMIs.size() == 1);
1134 MachineInstr *NewMI = NewMIs.back();
1136 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1138 SmallVector<unsigned, 1> Ops;
1140 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1142 VRM.addSpillSlotUse(SS, FoldedMI);
1143 if (!VRM.hasPhys(UnfoldVR))
1144 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1145 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1146 MII = MBB.insert(MII, FoldedMI);
1147 InvalidateKills(MI, TRI, RegKills, KillOps);
1148 VRM.RemoveMachineInstrFromMaps(&MI);
1150 MF.DeleteMachineInstr(NewMI);
1153 MF.DeleteMachineInstr(NewMI);
1160 /// CommuteToFoldReload -
1163 /// r1 = op r1, r2<kill>
1166 /// If op is commutable and r2 is killed, then we can xform these to
1167 /// r2 = op r2, fi#1
1169 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1170 MachineBasicBlock::iterator &MII,
1171 unsigned VirtReg, unsigned SrcReg, int SS,
1172 AvailableSpills &Spills,
1173 BitVector &RegKills,
1174 std::vector<MachineOperand*> &KillOps,
1175 const TargetRegisterInfo *TRI,
1177 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1180 MachineFunction &MF = *MBB.getParent();
1181 MachineInstr &MI = *MII;
1182 MachineBasicBlock::iterator DefMII = prior(MII);
1183 MachineInstr *DefMI = DefMII;
1184 const TargetInstrDesc &TID = DefMI->getDesc();
1186 if (DefMII != MBB.begin() &&
1187 TID.isCommutable() &&
1188 TII->CommuteChangesDestination(DefMI, NewDstIdx)) {
1189 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1190 unsigned NewReg = NewDstMO.getReg();
1191 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1193 MachineInstr *ReloadMI = prior(DefMII);
1195 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1196 if (DestReg != SrcReg || FrameIdx != SS)
1198 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1202 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1204 assert(DefMI->getOperand(DefIdx).isReg() &&
1205 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1207 // Now commute def instruction.
1208 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1211 SmallVector<unsigned, 1> Ops;
1212 Ops.push_back(NewDstIdx);
1213 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1214 // Not needed since foldMemoryOperand returns new MI.
1215 MF.DeleteMachineInstr(CommutedMI);
1219 VRM.addSpillSlotUse(SS, FoldedMI);
1220 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1221 // Insert new def MI and spill MI.
1222 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1223 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1225 MachineInstr *StoreMI = MII;
1226 VRM.addSpillSlotUse(SS, StoreMI);
1227 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1228 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1230 // Delete all 3 old instructions.
1231 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1232 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1233 MBB.erase(ReloadMI);
1234 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1235 VRM.RemoveMachineInstrFromMaps(DefMI);
1237 InvalidateKills(MI, TRI, RegKills, KillOps);
1238 VRM.RemoveMachineInstrFromMaps(&MI);
1241 // If NewReg was previously holding value of some SS, it's now clobbered.
1242 // This has to be done now because it's a physical register. When this
1243 // instruction is re-visited, it's ignored.
1244 Spills.ClobberPhysReg(NewReg);
1253 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1254 /// the last store to the same slot is now dead. If so, remove the last store.
1255 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1256 MachineBasicBlock::iterator &MII,
1257 int Idx, unsigned PhysReg, int StackSlot,
1258 const TargetRegisterClass *RC,
1259 bool isAvailable, MachineInstr *&LastStore,
1260 AvailableSpills &Spills,
1261 SmallSet<MachineInstr*, 4> &ReMatDefs,
1262 BitVector &RegKills,
1263 std::vector<MachineOperand*> &KillOps,
1266 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1267 MachineInstr *StoreMI = next(MII);
1268 VRM.addSpillSlotUse(StackSlot, StoreMI);
1269 DOUT << "Store:\t" << *StoreMI;
1271 // If there is a dead store to this stack slot, nuke it now.
1273 DOUT << "Removed dead store:\t" << *LastStore;
1275 SmallVector<unsigned, 2> KillRegs;
1276 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1277 MachineBasicBlock::iterator PrevMII = LastStore;
1278 bool CheckDef = PrevMII != MBB.begin();
1281 VRM.RemoveMachineInstrFromMaps(LastStore);
1282 MBB.erase(LastStore);
1284 // Look at defs of killed registers on the store. Mark the defs
1285 // as dead since the store has been deleted and they aren't
1287 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1288 bool HasOtherDef = false;
1289 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1290 MachineInstr *DeadDef = PrevMII;
1291 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1292 // FIXME: This assumes a remat def does not have side effects.
1293 VRM.RemoveMachineInstrFromMaps(DeadDef);
1302 LastStore = next(MII);
1304 // If the stack slot value was previously available in some other
1305 // register, change it now. Otherwise, make the register available,
1307 Spills.ModifyStackSlotOrReMat(StackSlot);
1308 Spills.ClobberPhysReg(PhysReg);
1309 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1313 /// TransferDeadness - A identity copy definition is dead and it's being
1314 /// removed. Find the last def or use and mark it as dead / kill.
1315 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1316 unsigned Reg, BitVector &RegKills,
1317 std::vector<MachineOperand*> &KillOps,
1319 SmallPtrSet<MachineInstr*, 4> Seens;
1320 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1321 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1322 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1323 MachineInstr *UDMI = &*RI;
1324 if (UDMI->getParent() != MBB)
1326 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1327 if (DI == DistanceMap.end() || DI->second > CurDist)
1329 if (Seens.insert(UDMI))
1330 Refs.push_back(std::make_pair(UDMI, DI->second));
1335 std::sort(Refs.begin(), Refs.end(), RefSorter());
1337 while (!Refs.empty()) {
1338 MachineInstr *LastUDMI = Refs.back().first;
1341 MachineOperand *LastUD = NULL;
1342 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1343 MachineOperand &MO = LastUDMI->getOperand(i);
1344 if (!MO.isReg() || MO.getReg() != Reg)
1346 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1348 if (LastUDMI->isRegTiedToDefOperand(i))
1351 if (LastUD->isDef()) {
1352 // If the instruction has no side effect, delete it and propagate
1353 // backward further. Otherwise, mark is dead and we are done.
1354 const TargetInstrDesc &TID = LastUDMI->getDesc();
1355 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1356 TID.hasUnmodeledSideEffects()) {
1357 LastUD->setIsDead();
1360 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1361 MBB->erase(LastUDMI);
1363 LastUD->setIsKill();
1365 KillOps[Reg] = LastUD;
1371 /// rewriteMBB - Keep track of which spills are available even after the
1372 /// register allocator is done with them. If possible, avid reloading vregs.
1373 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1375 AvailableSpills &Spills, BitVector &RegKills,
1376 std::vector<MachineOperand*> &KillOps) {
1378 DOUT << "\n**** Local spiller rewriting MBB '"
1379 << MBB.getBasicBlock()->getName() << "':\n";
1381 MachineFunction &MF = *MBB.getParent();
1383 // MaybeDeadStores - When we need to write a value back into a stack slot,
1384 // keep track of the inserted store. If the stack slot value is never read
1385 // (because the value was used from some available register, for example), and
1386 // subsequently stored to, the original store is dead. This map keeps track
1387 // of inserted stores that are not used. If we see a subsequent store to the
1388 // same stack slot, the original store is deleted.
1389 std::vector<MachineInstr*> MaybeDeadStores;
1390 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1392 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1393 SmallSet<MachineInstr*, 4> ReMatDefs;
1396 SmallSet<unsigned, 2> KilledMIRegs;
1399 KillOps.resize(TRI->getNumRegs(), NULL);
1402 DistanceMap.clear();
1403 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1405 MachineBasicBlock::iterator NextMII = next(MII);
1407 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1408 bool Erased = false;
1409 bool BackTracked = false;
1410 if (OptimizeByUnfold(MBB, MII,
1411 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1412 NextMII = next(MII);
1414 MachineInstr &MI = *MII;
1416 if (VRM.hasEmergencySpills(&MI)) {
1417 // Spill physical register(s) in the rare case the allocator has run out
1418 // of registers to allocate.
1419 SmallSet<int, 4> UsedSS;
1420 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1421 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1422 unsigned PhysReg = EmSpills[i];
1423 const TargetRegisterClass *RC =
1424 TRI->getPhysicalRegisterRegClass(PhysReg);
1425 assert(RC && "Unable to determine register class!");
1426 int SS = VRM.getEmergencySpillSlot(RC);
1427 if (UsedSS.count(SS))
1428 assert(0 && "Need to spill more than one physical registers!");
1430 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1431 MachineInstr *StoreMI = prior(MII);
1432 VRM.addSpillSlotUse(SS, StoreMI);
1433 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1434 MachineInstr *LoadMI = next(MII);
1435 VRM.addSpillSlotUse(SS, LoadMI);
1438 NextMII = next(MII);
1441 // Insert restores here if asked to.
1442 if (VRM.isRestorePt(&MI)) {
1443 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1444 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1445 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1446 if (!VRM.getPreSplitReg(VirtReg))
1447 continue; // Split interval spilled again.
1448 unsigned Phys = VRM.getPhys(VirtReg);
1449 RegInfo->setPhysRegUsed(Phys);
1451 // Check if the value being restored if available. If so, it must be
1452 // from a predecessor BB that fallthrough into this BB. We do not
1458 // ... # r1 not clobbered
1461 bool DoReMat = VRM.isReMaterialized(VirtReg);
1462 int SSorRMId = DoReMat
1463 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1464 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1465 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1466 if (InReg == Phys) {
1467 // If the value is already available in the expected register, save
1468 // a reload / remat.
1470 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1472 DOUT << "Reusing SS#" << SSorRMId;
1473 DOUT << " from physreg "
1474 << TRI->getName(InReg) << " for vreg"
1475 << VirtReg <<" instead of reloading into physreg "
1476 << TRI->getName(Phys) << "\n";
1479 } else if (InReg && InReg != Phys) {
1481 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1483 DOUT << "Reusing SS#" << SSorRMId;
1484 DOUT << " from physreg "
1485 << TRI->getName(InReg) << " for vreg"
1486 << VirtReg <<" by copying it into physreg "
1487 << TRI->getName(Phys) << "\n";
1489 // If the reloaded / remat value is available in another register,
1490 // copy it to the desired register.
1491 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1493 // This invalidates Phys.
1494 Spills.ClobberPhysReg(Phys);
1495 // Remember it's available.
1496 Spills.addAvailable(SSorRMId, Phys);
1499 MachineInstr *CopyMI = prior(MII);
1500 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1501 KillOpnd->setIsKill();
1502 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1504 DOUT << '\t' << *CopyMI;
1509 if (VRM.isReMaterialized(VirtReg)) {
1510 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1512 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1513 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1514 MachineInstr *LoadMI = prior(MII);
1515 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1519 // This invalidates Phys.
1520 Spills.ClobberPhysReg(Phys);
1521 // Remember it's available.
1522 Spills.addAvailable(SSorRMId, Phys);
1524 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1525 DOUT << '\t' << *prior(MII);
1529 // Insert spills here if asked to.
1530 if (VRM.isSpillPt(&MI)) {
1531 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1532 VRM.getSpillPtSpills(&MI);
1533 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1534 unsigned VirtReg = SpillRegs[i].first;
1535 bool isKill = SpillRegs[i].second;
1536 if (!VRM.getPreSplitReg(VirtReg))
1537 continue; // Split interval spilled again.
1538 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1539 unsigned Phys = VRM.getPhys(VirtReg);
1540 int StackSlot = VRM.getStackSlot(VirtReg);
1541 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1542 MachineInstr *StoreMI = next(MII);
1543 VRM.addSpillSlotUse(StackSlot, StoreMI);
1544 DOUT << "Store:\t" << *StoreMI;
1545 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1547 NextMII = next(MII);
1550 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1552 ReuseInfo ReusedOperands(MI, TRI);
1553 SmallVector<unsigned, 4> VirtUseOps;
1554 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1555 MachineOperand &MO = MI.getOperand(i);
1556 if (!MO.isReg() || MO.getReg() == 0)
1557 continue; // Ignore non-register operands.
1559 unsigned VirtReg = MO.getReg();
1560 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1561 // Ignore physregs for spilling, but remember that it is used by this
1563 RegInfo->setPhysRegUsed(VirtReg);
1567 // We want to process implicit virtual register uses first.
1568 if (MO.isImplicit())
1569 // If the virtual register is implicitly defined, emit a implicit_def
1570 // before so scavenger knows it's "defined".
1571 // FIXME: This is a horrible hack done the by register allocator to
1572 // remat a definition with virtual register operand.
1573 VirtUseOps.insert(VirtUseOps.begin(), i);
1575 VirtUseOps.push_back(i);
1578 // Process all of the spilled uses and all non spilled reg references.
1579 SmallVector<int, 2> PotentialDeadStoreSlots;
1580 KilledMIRegs.clear();
1581 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1582 unsigned i = VirtUseOps[j];
1583 MachineOperand &MO = MI.getOperand(i);
1584 unsigned VirtReg = MO.getReg();
1585 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1586 "Not a virtual register?");
1588 unsigned SubIdx = MO.getSubReg();
1589 if (VRM.isAssignedReg(VirtReg)) {
1590 // This virtual register was assigned a physreg!
1591 unsigned Phys = VRM.getPhys(VirtReg);
1592 RegInfo->setPhysRegUsed(Phys);
1594 ReusedOperands.markClobbered(Phys);
1595 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1596 MI.getOperand(i).setReg(RReg);
1597 MI.getOperand(i).setSubReg(0);
1598 if (VRM.isImplicitlyDefined(VirtReg))
1599 // FIXME: Is this needed?
1600 BuildMI(MBB, &MI, MI.getDebugLoc(),
1601 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1605 // This virtual register is now known to be a spilled value.
1607 continue; // Handle defs in the loop below (handle use&def here though)
1609 bool AvoidReload = MO.isUndef();
1610 // Check if it is defined by an implicit def. It should not be spilled.
1611 // Note, this is for correctness reason. e.g.
1612 // 8 %reg1024<def> = IMPLICIT_DEF
1613 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1614 // The live range [12, 14) are not part of the r1024 live interval since
1615 // it's defined by an implicit def. It will not conflicts with live
1616 // interval of r1025. Now suppose both registers are spilled, you can
1617 // easily see a situation where both registers are reloaded before
1618 // the INSERT_SUBREG and both target registers that would overlap.
1619 bool DoReMat = VRM.isReMaterialized(VirtReg);
1620 int SSorRMId = DoReMat
1621 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1622 int ReuseSlot = SSorRMId;
1624 // Check to see if this stack slot is available.
1625 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1627 // If this is a sub-register use, make sure the reuse register is in the
1628 // right register class. For example, for x86 not all of the 32-bit
1629 // registers have accessible sub-registers.
1630 // Similarly so for EXTRACT_SUBREG. Consider this:
1632 // MOV32_mr fi#1, EDI
1634 // = EXTRACT_SUBREG fi#1
1635 // fi#1 is available in EDI, but it cannot be reused because it's not in
1636 // the right register file.
1637 if (PhysReg && !AvoidReload &&
1638 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1639 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1640 if (!RC->contains(PhysReg))
1644 if (PhysReg && !AvoidReload) {
1645 // This spilled operand might be part of a two-address operand. If this
1646 // is the case, then changing it will necessarily require changing the
1647 // def part of the instruction as well. However, in some cases, we
1648 // aren't allowed to modify the reused register. If none of these cases
1650 bool CanReuse = true;
1651 bool isTied = MI.isRegTiedToDefOperand(i);
1653 // Okay, we have a two address operand. We can reuse this physreg as
1654 // long as we are allowed to clobber the value and there isn't an
1655 // earlier def that has already clobbered the physreg.
1656 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1657 Spills.canClobberPhysReg(PhysReg);
1661 // If this stack slot value is already available, reuse it!
1662 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1663 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1665 DOUT << "Reusing SS#" << ReuseSlot;
1666 DOUT << " from physreg "
1667 << TRI->getName(PhysReg) << " for vreg"
1668 << VirtReg <<" instead of reloading into physreg "
1669 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1670 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1671 MI.getOperand(i).setReg(RReg);
1672 MI.getOperand(i).setSubReg(0);
1674 // The only technical detail we have is that we don't know that
1675 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1676 // later in the instruction. In particular, consider 'op V1, V2'.
1677 // If V1 is available in physreg R0, we would choose to reuse it
1678 // here, instead of reloading it into the register the allocator
1679 // indicated (say R1). However, V2 might have to be reloaded
1680 // later, and it might indicate that it needs to live in R0. When
1681 // this occurs, we need to have information available that
1682 // indicates it is safe to use R1 for the reload instead of R0.
1684 // To further complicate matters, we might conflict with an alias,
1685 // or R0 and R1 might not be compatible with each other. In this
1686 // case, we actually insert a reload for V1 in R1, ensuring that
1687 // we can get at R0 or its alias.
1688 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1689 VRM.getPhys(VirtReg), VirtReg);
1691 // Only mark it clobbered if this is a use&def operand.
1692 ReusedOperands.markClobbered(PhysReg);
1695 if (MI.getOperand(i).isKill() &&
1696 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1698 // The store of this spilled value is potentially dead, but we
1699 // won't know for certain until we've confirmed that the re-use
1700 // above is valid, which means waiting until the other operands
1701 // are processed. For now we just track the spill slot, we'll
1702 // remove it after the other operands are processed if valid.
1704 PotentialDeadStoreSlots.push_back(ReuseSlot);
1707 // Mark is isKill if it's there no other uses of the same virtual
1708 // register and it's not a two-address operand. IsKill will be
1709 // unset if reg is reused.
1710 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1711 MI.getOperand(i).setIsKill();
1712 KilledMIRegs.insert(VirtReg);
1718 // Otherwise we have a situation where we have a two-address instruction
1719 // whose mod/ref operand needs to be reloaded. This reload is already
1720 // available in some register "PhysReg", but if we used PhysReg as the
1721 // operand to our 2-addr instruction, the instruction would modify
1722 // PhysReg. This isn't cool if something later uses PhysReg and expects
1723 // to get its initial value.
1725 // To avoid this problem, and to avoid doing a load right after a store,
1726 // we emit a copy from PhysReg into the designated register for this
1728 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1729 assert(DesignatedReg && "Must map virtreg to physreg!");
1731 // Note that, if we reused a register for a previous operand, the
1732 // register we want to reload into might not actually be
1733 // available. If this occurs, use the register indicated by the
1735 if (ReusedOperands.hasReuses())
1736 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1737 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1739 // If the mapped designated register is actually the physreg we have
1740 // incoming, we don't need to inserted a dead copy.
1741 if (DesignatedReg == PhysReg) {
1742 // If this stack slot value is already available, reuse it!
1743 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1744 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1746 DOUT << "Reusing SS#" << ReuseSlot;
1747 DOUT << " from physreg " << TRI->getName(PhysReg)
1748 << " for vreg" << VirtReg
1749 << " instead of reloading into same physreg.\n";
1750 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1751 MI.getOperand(i).setReg(RReg);
1752 MI.getOperand(i).setSubReg(0);
1753 ReusedOperands.markClobbered(RReg);
1758 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1759 RegInfo->setPhysRegUsed(DesignatedReg);
1760 ReusedOperands.markClobbered(DesignatedReg);
1761 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1763 MachineInstr *CopyMI = prior(MII);
1764 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1766 // This invalidates DesignatedReg.
1767 Spills.ClobberPhysReg(DesignatedReg);
1769 Spills.addAvailable(ReuseSlot, DesignatedReg);
1771 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1772 MI.getOperand(i).setReg(RReg);
1773 MI.getOperand(i).setSubReg(0);
1774 DOUT << '\t' << *prior(MII);
1779 // Otherwise, reload it and remember that we have it.
1780 PhysReg = VRM.getPhys(VirtReg);
1781 assert(PhysReg && "Must map virtreg to physreg!");
1783 // Note that, if we reused a register for a previous operand, the
1784 // register we want to reload into might not actually be
1785 // available. If this occurs, use the register indicated by the
1787 if (ReusedOperands.hasReuses())
1788 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1789 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1791 RegInfo->setPhysRegUsed(PhysReg);
1792 ReusedOperands.markClobbered(PhysReg);
1797 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1799 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1800 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1801 MachineInstr *LoadMI = prior(MII);
1802 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1805 // This invalidates PhysReg.
1806 Spills.ClobberPhysReg(PhysReg);
1808 // Any stores to this stack slot are not dead anymore.
1810 MaybeDeadStores[SSorRMId] = NULL;
1811 Spills.addAvailable(SSorRMId, PhysReg);
1812 // Assumes this is the last use. IsKill will be unset if reg is reused
1813 // unless it's a two-address operand.
1814 if (!MI.isRegTiedToDefOperand(i) &&
1815 KilledMIRegs.count(VirtReg) == 0) {
1816 MI.getOperand(i).setIsKill();
1817 KilledMIRegs.insert(VirtReg);
1820 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1821 DOUT << '\t' << *prior(MII);
1823 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1824 MI.getOperand(i).setReg(RReg);
1825 MI.getOperand(i).setSubReg(0);
1828 // Ok - now we can remove stores that have been confirmed dead.
1829 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1830 // This was the last use and the spilled value is still available
1831 // for reuse. That means the spill was unnecessary!
1832 int PDSSlot = PotentialDeadStoreSlots[j];
1833 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1835 DOUT << "Removed dead store:\t" << *DeadStore;
1836 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1837 VRM.RemoveMachineInstrFromMaps(DeadStore);
1838 MBB.erase(DeadStore);
1839 MaybeDeadStores[PDSSlot] = NULL;
1848 // If we have folded references to memory operands, make sure we clear all
1849 // physical registers that may contain the value of the spilled virtual
1851 SmallSet<int, 2> FoldedSS;
1852 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1853 unsigned VirtReg = I->second.first;
1854 VirtRegMap::ModRef MR = I->second.second;
1855 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1857 // MI2VirtMap be can updated which invalidate the iterator.
1858 // Increment the iterator first.
1860 int SS = VRM.getStackSlot(VirtReg);
1861 if (SS == VirtRegMap::NO_STACK_SLOT)
1863 FoldedSS.insert(SS);
1864 DOUT << " - StackSlot: " << SS << "\n";
1866 // If this folded instruction is just a use, check to see if it's a
1867 // straight load from the virt reg slot.
1868 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1870 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1871 if (DestReg && FrameIdx == SS) {
1872 // If this spill slot is available, turn it into a copy (or nothing)
1873 // instead of leaving it as a load!
1874 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1875 DOUT << "Promoted Load To Copy: " << MI;
1876 if (DestReg != InReg) {
1877 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1878 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1879 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1880 unsigned SubIdx = DefMO->getSubReg();
1881 // Revisit the copy so we make sure to notice the effects of the
1882 // operation on the destreg (either needing to RA it if it's
1883 // virtual or needing to clobber any values if it's physical).
1885 --NextMII; // backtrack to the copy.
1886 // Propagate the sub-register index over.
1888 DefMO = NextMII->findRegisterDefOperand(DestReg);
1889 DefMO->setSubReg(SubIdx);
1893 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1894 KillOpnd->setIsKill();
1898 DOUT << "Removing now-noop copy: " << MI;
1899 // Unset last kill since it's being reused.
1900 InvalidateKill(InReg, TRI, RegKills, KillOps);
1901 Spills.disallowClobberPhysReg(InReg);
1904 InvalidateKills(MI, TRI, RegKills, KillOps);
1905 VRM.RemoveMachineInstrFromMaps(&MI);
1908 goto ProcessNextInst;
1911 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1912 SmallVector<MachineInstr*, 4> NewMIs;
1914 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1915 MBB.insert(MII, NewMIs[0]);
1916 InvalidateKills(MI, TRI, RegKills, KillOps);
1917 VRM.RemoveMachineInstrFromMaps(&MI);
1920 --NextMII; // backtrack to the unfolded instruction.
1922 goto ProcessNextInst;
1927 // If this reference is not a use, any previous store is now dead.
1928 // Otherwise, the store to this stack slot is not dead anymore.
1929 MachineInstr* DeadStore = MaybeDeadStores[SS];
1931 bool isDead = !(MR & VirtRegMap::isRef);
1932 MachineInstr *NewStore = NULL;
1933 if (MR & VirtRegMap::isModRef) {
1934 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1935 SmallVector<MachineInstr*, 4> NewMIs;
1936 // We can reuse this physreg as long as we are allowed to clobber
1937 // the value and there isn't an earlier def that has already clobbered
1940 !ReusedOperands.isClobbered(PhysReg) &&
1941 Spills.canClobberPhysReg(PhysReg) &&
1942 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1943 MachineOperand *KillOpnd =
1944 DeadStore->findRegisterUseOperand(PhysReg, true);
1945 // Note, if the store is storing a sub-register, it's possible the
1946 // super-register is needed below.
1947 if (KillOpnd && !KillOpnd->getSubReg() &&
1948 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1949 MBB.insert(MII, NewMIs[0]);
1950 NewStore = NewMIs[1];
1951 MBB.insert(MII, NewStore);
1952 VRM.addSpillSlotUse(SS, NewStore);
1953 InvalidateKills(MI, TRI, RegKills, KillOps);
1954 VRM.RemoveMachineInstrFromMaps(&MI);
1958 --NextMII; // backtrack to the unfolded instruction.
1966 if (isDead) { // Previous store is dead.
1967 // If we get here, the store is dead, nuke it now.
1968 DOUT << "Removed dead store:\t" << *DeadStore;
1969 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1970 VRM.RemoveMachineInstrFromMaps(DeadStore);
1971 MBB.erase(DeadStore);
1976 MaybeDeadStores[SS] = NULL;
1978 // Treat this store as a spill merged into a copy. That makes the
1979 // stack slot value available.
1980 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1981 goto ProcessNextInst;
1985 // If the spill slot value is available, and this is a new definition of
1986 // the value, the value is not available anymore.
1987 if (MR & VirtRegMap::isMod) {
1988 // Notice that the value in this stack slot has been modified.
1989 Spills.ModifyStackSlotOrReMat(SS);
1991 // If this is *just* a mod of the value, check to see if this is just a
1992 // store to the spill slot (i.e. the spill got merged into the copy). If
1993 // so, realize that the vreg is available now, and add the store to the
1994 // MaybeDeadStore info.
1996 if (!(MR & VirtRegMap::isRef)) {
1997 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
1998 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
1999 "Src hasn't been allocated yet?");
2001 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2002 Spills, RegKills, KillOps, TRI, VRM)) {
2003 NextMII = next(MII);
2005 goto ProcessNextInst;
2008 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2009 // this as a potentially dead store in case there is a subsequent
2010 // store into the stack slot without a read from it.
2011 MaybeDeadStores[StackSlot] = &MI;
2013 // If the stack slot value was previously available in some other
2014 // register, change it now. Otherwise, make the register
2015 // available in PhysReg.
2016 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2022 // Process all of the spilled defs.
2023 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2024 MachineOperand &MO = MI.getOperand(i);
2025 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2028 unsigned VirtReg = MO.getReg();
2029 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2030 // Check to see if this is a noop copy. If so, eliminate the
2031 // instruction before considering the dest reg to be changed.
2032 unsigned Src, Dst, SrcSR, DstSR;
2033 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2035 DOUT << "Removing now-noop copy: " << MI;
2036 SmallVector<unsigned, 2> KillRegs;
2037 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2038 if (MO.isDead() && !KillRegs.empty()) {
2039 // Source register or an implicit super/sub-register use is killed.
2040 assert(KillRegs[0] == Dst ||
2041 TRI->isSubRegister(KillRegs[0], Dst) ||
2042 TRI->isSuperRegister(KillRegs[0], Dst));
2043 // Last def is now dead.
2044 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2046 VRM.RemoveMachineInstrFromMaps(&MI);
2049 Spills.disallowClobberPhysReg(VirtReg);
2050 goto ProcessNextInst;
2053 // If it's not a no-op copy, it clobbers the value in the destreg.
2054 Spills.ClobberPhysReg(VirtReg);
2055 ReusedOperands.markClobbered(VirtReg);
2057 // Check to see if this instruction is a load from a stack slot into
2058 // a register. If so, this provides the stack slot value in the reg.
2060 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2061 assert(DestReg == VirtReg && "Unknown load situation!");
2063 // If it is a folded reference, then it's not safe to clobber.
2064 bool Folded = FoldedSS.count(FrameIdx);
2065 // Otherwise, if it wasn't available, remember that it is now!
2066 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2067 goto ProcessNextInst;
2073 unsigned SubIdx = MO.getSubReg();
2074 bool DoReMat = VRM.isReMaterialized(VirtReg);
2076 ReMatDefs.insert(&MI);
2078 // The only vregs left are stack slot definitions.
2079 int StackSlot = VRM.getStackSlot(VirtReg);
2080 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2082 // If this def is part of a two-address operand, make sure to execute
2083 // the store from the correct physical register.
2086 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2087 PhysReg = MI.getOperand(TiedOp).getReg();
2089 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2090 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2091 "Can't find corresponding super-register!");
2095 PhysReg = VRM.getPhys(VirtReg);
2096 if (ReusedOperands.isClobbered(PhysReg)) {
2097 // Another def has taken the assigned physreg. It must have been a
2098 // use&def which got it due to reuse. Undo the reuse!
2099 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2100 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2104 assert(PhysReg && "VR not assigned a physical register?");
2105 RegInfo->setPhysRegUsed(PhysReg);
2106 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2107 ReusedOperands.markClobbered(RReg);
2108 MI.getOperand(i).setReg(RReg);
2109 MI.getOperand(i).setSubReg(0);
2112 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2113 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2114 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2115 NextMII = next(MII);
2117 // Check to see if this is a noop copy. If so, eliminate the
2118 // instruction before considering the dest reg to be changed.
2120 unsigned Src, Dst, SrcSR, DstSR;
2121 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2123 DOUT << "Removing now-noop copy: " << MI;
2124 InvalidateKills(MI, TRI, RegKills, KillOps);
2125 VRM.RemoveMachineInstrFromMaps(&MI);
2128 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2129 goto ProcessNextInst;
2135 DistanceMap.insert(std::make_pair(&MI, Dist++));
2136 if (!Erased && !BackTracked) {
2137 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2138 UpdateKills(*II, TRI, RegKills, KillOps);
2147 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2148 switch (RewriterOpt) {
2149 default: assert(0 && "Unreachable!");
2151 return new LocalRewriter();
2153 return new TrivialRewriter();