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())
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.isDef()) {
394 if (MO.getReg() == Reg)
396 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())
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
1294 VRM.RemoveMachineInstrFromMaps(DeadDef);
1303 LastStore = next(MII);
1305 // If the stack slot value was previously available in some other
1306 // register, change it now. Otherwise, make the register available,
1308 Spills.ModifyStackSlotOrReMat(StackSlot);
1309 Spills.ClobberPhysReg(PhysReg);
1310 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1314 /// TransferDeadness - A identity copy definition is dead and it's being
1315 /// removed. Find the last def or use and mark it as dead / kill.
1316 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1317 unsigned Reg, BitVector &RegKills,
1318 std::vector<MachineOperand*> &KillOps,
1320 SmallPtrSet<MachineInstr*, 4> Seens;
1321 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1322 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1323 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1324 MachineInstr *UDMI = &*RI;
1325 if (UDMI->getParent() != MBB)
1327 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1328 if (DI == DistanceMap.end() || DI->second > CurDist)
1330 if (Seens.insert(UDMI))
1331 Refs.push_back(std::make_pair(UDMI, DI->second));
1336 std::sort(Refs.begin(), Refs.end(), RefSorter());
1338 while (!Refs.empty()) {
1339 MachineInstr *LastUDMI = Refs.back().first;
1342 MachineOperand *LastUD = NULL;
1343 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1344 MachineOperand &MO = LastUDMI->getOperand(i);
1345 if (!MO.isReg() || MO.getReg() != Reg)
1347 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1349 if (LastUDMI->isRegTiedToDefOperand(i))
1352 if (LastUD->isDef()) {
1353 // If the instruction has no side effect, delete it and propagate
1354 // backward further. Otherwise, mark is dead and we are done.
1355 const TargetInstrDesc &TID = LastUDMI->getDesc();
1356 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1357 TID.hasUnmodeledSideEffects()) {
1358 LastUD->setIsDead();
1361 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1362 MBB->erase(LastUDMI);
1364 LastUD->setIsKill();
1366 KillOps[Reg] = LastUD;
1372 /// rewriteMBB - Keep track of which spills are available even after the
1373 /// register allocator is done with them. If possible, avid reloading vregs.
1374 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1376 AvailableSpills &Spills, BitVector &RegKills,
1377 std::vector<MachineOperand*> &KillOps) {
1379 DOUT << "\n**** Local spiller rewriting MBB '"
1380 << MBB.getBasicBlock()->getName() << "':\n";
1382 MachineFunction &MF = *MBB.getParent();
1384 // MaybeDeadStores - When we need to write a value back into a stack slot,
1385 // keep track of the inserted store. If the stack slot value is never read
1386 // (because the value was used from some available register, for example), and
1387 // subsequently stored to, the original store is dead. This map keeps track
1388 // of inserted stores that are not used. If we see a subsequent store to the
1389 // same stack slot, the original store is deleted.
1390 std::vector<MachineInstr*> MaybeDeadStores;
1391 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1393 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1394 SmallSet<MachineInstr*, 4> ReMatDefs;
1397 SmallSet<unsigned, 2> KilledMIRegs;
1400 KillOps.resize(TRI->getNumRegs(), NULL);
1403 DistanceMap.clear();
1404 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1406 MachineBasicBlock::iterator NextMII = next(MII);
1408 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1409 bool Erased = false;
1410 bool BackTracked = false;
1411 if (OptimizeByUnfold(MBB, MII,
1412 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1413 NextMII = next(MII);
1415 MachineInstr &MI = *MII;
1417 if (VRM.hasEmergencySpills(&MI)) {
1418 // Spill physical register(s) in the rare case the allocator has run out
1419 // of registers to allocate.
1420 SmallSet<int, 4> UsedSS;
1421 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1422 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1423 unsigned PhysReg = EmSpills[i];
1424 const TargetRegisterClass *RC =
1425 TRI->getPhysicalRegisterRegClass(PhysReg);
1426 assert(RC && "Unable to determine register class!");
1427 int SS = VRM.getEmergencySpillSlot(RC);
1428 if (UsedSS.count(SS))
1429 assert(0 && "Need to spill more than one physical registers!");
1431 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1432 MachineInstr *StoreMI = prior(MII);
1433 VRM.addSpillSlotUse(SS, StoreMI);
1434 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1435 MachineInstr *LoadMI = next(MII);
1436 VRM.addSpillSlotUse(SS, LoadMI);
1439 NextMII = next(MII);
1442 // Insert restores here if asked to.
1443 if (VRM.isRestorePt(&MI)) {
1444 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1445 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1446 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1447 if (!VRM.getPreSplitReg(VirtReg))
1448 continue; // Split interval spilled again.
1449 unsigned Phys = VRM.getPhys(VirtReg);
1450 RegInfo->setPhysRegUsed(Phys);
1452 // Check if the value being restored if available. If so, it must be
1453 // from a predecessor BB that fallthrough into this BB. We do not
1459 // ... # r1 not clobbered
1462 bool DoReMat = VRM.isReMaterialized(VirtReg);
1463 int SSorRMId = DoReMat
1464 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1465 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1466 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1467 if (InReg == Phys) {
1468 // If the value is already available in the expected register, save
1469 // a reload / remat.
1471 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1473 DOUT << "Reusing SS#" << SSorRMId;
1474 DOUT << " from physreg "
1475 << TRI->getName(InReg) << " for vreg"
1476 << VirtReg <<" instead of reloading into physreg "
1477 << TRI->getName(Phys) << "\n";
1480 } else if (InReg && InReg != Phys) {
1482 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1484 DOUT << "Reusing SS#" << SSorRMId;
1485 DOUT << " from physreg "
1486 << TRI->getName(InReg) << " for vreg"
1487 << VirtReg <<" by copying it into physreg "
1488 << TRI->getName(Phys) << "\n";
1490 // If the reloaded / remat value is available in another register,
1491 // copy it to the desired register.
1492 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1494 // This invalidates Phys.
1495 Spills.ClobberPhysReg(Phys);
1496 // Remember it's available.
1497 Spills.addAvailable(SSorRMId, Phys);
1500 MachineInstr *CopyMI = prior(MII);
1501 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1502 KillOpnd->setIsKill();
1503 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1505 DOUT << '\t' << *CopyMI;
1510 if (VRM.isReMaterialized(VirtReg)) {
1511 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1513 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1514 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1515 MachineInstr *LoadMI = prior(MII);
1516 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1520 // This invalidates Phys.
1521 Spills.ClobberPhysReg(Phys);
1522 // Remember it's available.
1523 Spills.addAvailable(SSorRMId, Phys);
1525 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1526 DOUT << '\t' << *prior(MII);
1530 // Insert spills here if asked to.
1531 if (VRM.isSpillPt(&MI)) {
1532 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1533 VRM.getSpillPtSpills(&MI);
1534 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1535 unsigned VirtReg = SpillRegs[i].first;
1536 bool isKill = SpillRegs[i].second;
1537 if (!VRM.getPreSplitReg(VirtReg))
1538 continue; // Split interval spilled again.
1539 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1540 unsigned Phys = VRM.getPhys(VirtReg);
1541 int StackSlot = VRM.getStackSlot(VirtReg);
1542 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1543 MachineInstr *StoreMI = next(MII);
1544 VRM.addSpillSlotUse(StackSlot, StoreMI);
1545 DOUT << "Store:\t" << *StoreMI;
1546 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1548 NextMII = next(MII);
1551 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1553 ReuseInfo ReusedOperands(MI, TRI);
1554 SmallVector<unsigned, 4> VirtUseOps;
1555 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1556 MachineOperand &MO = MI.getOperand(i);
1557 if (!MO.isReg() || MO.getReg() == 0)
1558 continue; // Ignore non-register operands.
1560 unsigned VirtReg = MO.getReg();
1561 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1562 // Ignore physregs for spilling, but remember that it is used by this
1564 RegInfo->setPhysRegUsed(VirtReg);
1568 // We want to process implicit virtual register uses first.
1569 if (MO.isImplicit())
1570 // If the virtual register is implicitly defined, emit a implicit_def
1571 // before so scavenger knows it's "defined".
1572 VirtUseOps.insert(VirtUseOps.begin(), i);
1574 VirtUseOps.push_back(i);
1577 // Process all of the spilled uses and all non spilled reg references.
1578 SmallVector<int, 2> PotentialDeadStoreSlots;
1579 KilledMIRegs.clear();
1580 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1581 unsigned i = VirtUseOps[j];
1582 MachineOperand &MO = MI.getOperand(i);
1583 unsigned VirtReg = MO.getReg();
1584 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1585 "Not a virtual register?");
1587 unsigned SubIdx = MO.getSubReg();
1588 if (VRM.isAssignedReg(VirtReg)) {
1589 // This virtual register was assigned a physreg!
1590 unsigned Phys = VRM.getPhys(VirtReg);
1591 RegInfo->setPhysRegUsed(Phys);
1593 ReusedOperands.markClobbered(Phys);
1594 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1595 MI.getOperand(i).setReg(RReg);
1596 MI.getOperand(i).setSubReg(0);
1597 if (VRM.isImplicitlyDefined(VirtReg))
1598 BuildMI(MBB, &MI, MI.getDebugLoc(),
1599 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1603 // This virtual register is now known to be a spilled value.
1605 continue; // Handle defs in the loop below (handle use&def here though)
1607 bool AvoidReload = false;
1608 if (LIs->hasInterval(VirtReg)) {
1609 LiveInterval &LI = LIs->getInterval(VirtReg);
1610 if (!LI.liveAt(LIs->getUseIndex(LI.beginNumber())))
1611 // Must be defined by an implicit def. It should not be spilled. Note,
1612 // this is for correctness reason. e.g.
1613 // 8 %reg1024<def> = IMPLICIT_DEF
1614 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1615 // The live range [12, 14) are not part of the r1024 live interval since
1616 // it's defined by an implicit def. It will not conflicts with live
1617 // interval of r1025. Now suppose both registers are spilled, you can
1618 // easily see a situation where both registers are reloaded before
1619 // the INSERT_SUBREG and both target registers that would overlap.
1623 bool DoReMat = VRM.isReMaterialized(VirtReg);
1624 int SSorRMId = DoReMat
1625 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1626 int ReuseSlot = SSorRMId;
1628 // Check to see if this stack slot is available.
1629 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1631 // If this is a sub-register use, make sure the reuse register is in the
1632 // right register class. For example, for x86 not all of the 32-bit
1633 // registers have accessible sub-registers.
1634 // Similarly so for EXTRACT_SUBREG. Consider this:
1636 // MOV32_mr fi#1, EDI
1638 // = EXTRACT_SUBREG fi#1
1639 // fi#1 is available in EDI, but it cannot be reused because it's not in
1640 // the right register file.
1641 if (PhysReg && !AvoidReload &&
1642 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1643 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1644 if (!RC->contains(PhysReg))
1648 if (PhysReg && !AvoidReload) {
1649 // This spilled operand might be part of a two-address operand. If this
1650 // is the case, then changing it will necessarily require changing the
1651 // def part of the instruction as well. However, in some cases, we
1652 // aren't allowed to modify the reused register. If none of these cases
1654 bool CanReuse = true;
1655 bool isTied = MI.isRegTiedToDefOperand(i);
1657 // Okay, we have a two address operand. We can reuse this physreg as
1658 // long as we are allowed to clobber the value and there isn't an
1659 // earlier def that has already clobbered the physreg.
1660 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1661 Spills.canClobberPhysReg(PhysReg);
1665 // If this stack slot value is already available, reuse it!
1666 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1667 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1669 DOUT << "Reusing SS#" << ReuseSlot;
1670 DOUT << " from physreg "
1671 << TRI->getName(PhysReg) << " for vreg"
1672 << VirtReg <<" instead of reloading into physreg "
1673 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1674 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1675 MI.getOperand(i).setReg(RReg);
1676 MI.getOperand(i).setSubReg(0);
1678 // The only technical detail we have is that we don't know that
1679 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1680 // later in the instruction. In particular, consider 'op V1, V2'.
1681 // If V1 is available in physreg R0, we would choose to reuse it
1682 // here, instead of reloading it into the register the allocator
1683 // indicated (say R1). However, V2 might have to be reloaded
1684 // later, and it might indicate that it needs to live in R0. When
1685 // this occurs, we need to have information available that
1686 // indicates it is safe to use R1 for the reload instead of R0.
1688 // To further complicate matters, we might conflict with an alias,
1689 // or R0 and R1 might not be compatible with each other. In this
1690 // case, we actually insert a reload for V1 in R1, ensuring that
1691 // we can get at R0 or its alias.
1692 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1693 VRM.getPhys(VirtReg), VirtReg);
1695 // Only mark it clobbered if this is a use&def operand.
1696 ReusedOperands.markClobbered(PhysReg);
1699 if (MI.getOperand(i).isKill() &&
1700 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1702 // The store of this spilled value is potentially dead, but we
1703 // won't know for certain until we've confirmed that the re-use
1704 // above is valid, which means waiting until the other operands
1705 // are processed. For now we just track the spill slot, we'll
1706 // remove it after the other operands are processed if valid.
1708 PotentialDeadStoreSlots.push_back(ReuseSlot);
1711 // Mark is isKill if it's there no other uses of the same virtual
1712 // register and it's not a two-address operand. IsKill will be
1713 // unset if reg is reused.
1714 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1715 MI.getOperand(i).setIsKill();
1716 KilledMIRegs.insert(VirtReg);
1722 // Otherwise we have a situation where we have a two-address instruction
1723 // whose mod/ref operand needs to be reloaded. This reload is already
1724 // available in some register "PhysReg", but if we used PhysReg as the
1725 // operand to our 2-addr instruction, the instruction would modify
1726 // PhysReg. This isn't cool if something later uses PhysReg and expects
1727 // to get its initial value.
1729 // To avoid this problem, and to avoid doing a load right after a store,
1730 // we emit a copy from PhysReg into the designated register for this
1732 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1733 assert(DesignatedReg && "Must map virtreg to physreg!");
1735 // Note that, if we reused a register for a previous operand, the
1736 // register we want to reload into might not actually be
1737 // available. If this occurs, use the register indicated by the
1739 if (ReusedOperands.hasReuses())
1740 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1741 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1743 // If the mapped designated register is actually the physreg we have
1744 // incoming, we don't need to inserted a dead copy.
1745 if (DesignatedReg == PhysReg) {
1746 // If this stack slot value is already available, reuse it!
1747 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1748 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1750 DOUT << "Reusing SS#" << ReuseSlot;
1751 DOUT << " from physreg " << TRI->getName(PhysReg)
1752 << " for vreg" << VirtReg
1753 << " instead of reloading into same physreg.\n";
1754 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1755 MI.getOperand(i).setReg(RReg);
1756 MI.getOperand(i).setSubReg(0);
1757 ReusedOperands.markClobbered(RReg);
1762 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1763 RegInfo->setPhysRegUsed(DesignatedReg);
1764 ReusedOperands.markClobbered(DesignatedReg);
1765 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1767 MachineInstr *CopyMI = prior(MII);
1768 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1770 // This invalidates DesignatedReg.
1771 Spills.ClobberPhysReg(DesignatedReg);
1773 Spills.addAvailable(ReuseSlot, DesignatedReg);
1775 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1776 MI.getOperand(i).setReg(RReg);
1777 MI.getOperand(i).setSubReg(0);
1778 DOUT << '\t' << *prior(MII);
1783 // Otherwise, reload it and remember that we have it.
1784 PhysReg = VRM.getPhys(VirtReg);
1785 assert(PhysReg && "Must map virtreg to physreg!");
1787 // Note that, if we reused a register for a previous operand, the
1788 // register we want to reload into might not actually be
1789 // available. If this occurs, use the register indicated by the
1791 if (ReusedOperands.hasReuses())
1792 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1793 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1795 RegInfo->setPhysRegUsed(PhysReg);
1796 ReusedOperands.markClobbered(PhysReg);
1801 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1803 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1804 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1805 MachineInstr *LoadMI = prior(MII);
1806 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1809 // This invalidates PhysReg.
1810 Spills.ClobberPhysReg(PhysReg);
1812 // Any stores to this stack slot are not dead anymore.
1814 MaybeDeadStores[SSorRMId] = NULL;
1815 Spills.addAvailable(SSorRMId, PhysReg);
1816 // Assumes this is the last use. IsKill will be unset if reg is reused
1817 // unless it's a two-address operand.
1818 if (!MI.isRegTiedToDefOperand(i) &&
1819 KilledMIRegs.count(VirtReg) == 0) {
1820 MI.getOperand(i).setIsKill();
1821 KilledMIRegs.insert(VirtReg);
1824 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
1825 DOUT << '\t' << *prior(MII);
1827 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1828 MI.getOperand(i).setReg(RReg);
1829 MI.getOperand(i).setSubReg(0);
1832 // Ok - now we can remove stores that have been confirmed dead.
1833 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1834 // This was the last use and the spilled value is still available
1835 // for reuse. That means the spill was unnecessary!
1836 int PDSSlot = PotentialDeadStoreSlots[j];
1837 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1839 DOUT << "Removed dead store:\t" << *DeadStore;
1840 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1841 VRM.RemoveMachineInstrFromMaps(DeadStore);
1842 MBB.erase(DeadStore);
1843 MaybeDeadStores[PDSSlot] = NULL;
1852 // If we have folded references to memory operands, make sure we clear all
1853 // physical registers that may contain the value of the spilled virtual
1855 SmallSet<int, 2> FoldedSS;
1856 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1857 unsigned VirtReg = I->second.first;
1858 VirtRegMap::ModRef MR = I->second.second;
1859 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1861 // MI2VirtMap be can updated which invalidate the iterator.
1862 // Increment the iterator first.
1864 int SS = VRM.getStackSlot(VirtReg);
1865 if (SS == VirtRegMap::NO_STACK_SLOT)
1867 FoldedSS.insert(SS);
1868 DOUT << " - StackSlot: " << SS << "\n";
1870 // If this folded instruction is just a use, check to see if it's a
1871 // straight load from the virt reg slot.
1872 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1874 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1875 if (DestReg && FrameIdx == SS) {
1876 // If this spill slot is available, turn it into a copy (or nothing)
1877 // instead of leaving it as a load!
1878 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1879 DOUT << "Promoted Load To Copy: " << MI;
1880 if (DestReg != InReg) {
1881 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1882 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1883 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1884 unsigned SubIdx = DefMO->getSubReg();
1885 // Revisit the copy so we make sure to notice the effects of the
1886 // operation on the destreg (either needing to RA it if it's
1887 // virtual or needing to clobber any values if it's physical).
1889 --NextMII; // backtrack to the copy.
1890 // Propagate the sub-register index over.
1892 DefMO = NextMII->findRegisterDefOperand(DestReg);
1893 DefMO->setSubReg(SubIdx);
1897 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1898 KillOpnd->setIsKill();
1902 DOUT << "Removing now-noop copy: " << MI;
1903 // Unset last kill since it's being reused.
1904 InvalidateKill(InReg, TRI, RegKills, KillOps);
1905 Spills.disallowClobberPhysReg(InReg);
1908 InvalidateKills(MI, TRI, RegKills, KillOps);
1909 VRM.RemoveMachineInstrFromMaps(&MI);
1912 goto ProcessNextInst;
1915 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1916 SmallVector<MachineInstr*, 4> NewMIs;
1918 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1919 MBB.insert(MII, NewMIs[0]);
1920 InvalidateKills(MI, TRI, RegKills, KillOps);
1921 VRM.RemoveMachineInstrFromMaps(&MI);
1924 --NextMII; // backtrack to the unfolded instruction.
1926 goto ProcessNextInst;
1931 // If this reference is not a use, any previous store is now dead.
1932 // Otherwise, the store to this stack slot is not dead anymore.
1933 MachineInstr* DeadStore = MaybeDeadStores[SS];
1935 bool isDead = !(MR & VirtRegMap::isRef);
1936 MachineInstr *NewStore = NULL;
1937 if (MR & VirtRegMap::isModRef) {
1938 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1939 SmallVector<MachineInstr*, 4> NewMIs;
1940 // We can reuse this physreg as long as we are allowed to clobber
1941 // the value and there isn't an earlier def that has already clobbered
1944 !ReusedOperands.isClobbered(PhysReg) &&
1945 Spills.canClobberPhysReg(PhysReg) &&
1946 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1947 MachineOperand *KillOpnd =
1948 DeadStore->findRegisterUseOperand(PhysReg, true);
1949 // Note, if the store is storing a sub-register, it's possible the
1950 // super-register is needed below.
1951 if (KillOpnd && !KillOpnd->getSubReg() &&
1952 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1953 MBB.insert(MII, NewMIs[0]);
1954 NewStore = NewMIs[1];
1955 MBB.insert(MII, NewStore);
1956 VRM.addSpillSlotUse(SS, NewStore);
1957 InvalidateKills(MI, TRI, RegKills, KillOps);
1958 VRM.RemoveMachineInstrFromMaps(&MI);
1962 --NextMII; // backtrack to the unfolded instruction.
1970 if (isDead) { // Previous store is dead.
1971 // If we get here, the store is dead, nuke it now.
1972 DOUT << "Removed dead store:\t" << *DeadStore;
1973 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
1974 VRM.RemoveMachineInstrFromMaps(DeadStore);
1975 MBB.erase(DeadStore);
1980 MaybeDeadStores[SS] = NULL;
1982 // Treat this store as a spill merged into a copy. That makes the
1983 // stack slot value available.
1984 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
1985 goto ProcessNextInst;
1989 // If the spill slot value is available, and this is a new definition of
1990 // the value, the value is not available anymore.
1991 if (MR & VirtRegMap::isMod) {
1992 // Notice that the value in this stack slot has been modified.
1993 Spills.ModifyStackSlotOrReMat(SS);
1995 // If this is *just* a mod of the value, check to see if this is just a
1996 // store to the spill slot (i.e. the spill got merged into the copy). If
1997 // so, realize that the vreg is available now, and add the store to the
1998 // MaybeDeadStore info.
2000 if (!(MR & VirtRegMap::isRef)) {
2001 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2002 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2003 "Src hasn't been allocated yet?");
2005 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2006 Spills, RegKills, KillOps, TRI, VRM)) {
2007 NextMII = next(MII);
2009 goto ProcessNextInst;
2012 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2013 // this as a potentially dead store in case there is a subsequent
2014 // store into the stack slot without a read from it.
2015 MaybeDeadStores[StackSlot] = &MI;
2017 // If the stack slot value was previously available in some other
2018 // register, change it now. Otherwise, make the register
2019 // available in PhysReg.
2020 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2026 // Process all of the spilled defs.
2027 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2028 MachineOperand &MO = MI.getOperand(i);
2029 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2032 unsigned VirtReg = MO.getReg();
2033 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2034 // Check to see if this is a noop copy. If so, eliminate the
2035 // instruction before considering the dest reg to be changed.
2036 unsigned Src, Dst, SrcSR, DstSR;
2037 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2039 DOUT << "Removing now-noop copy: " << MI;
2040 SmallVector<unsigned, 2> KillRegs;
2041 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2042 if (MO.isDead() && !KillRegs.empty()) {
2043 // Source register or an implicit super/sub-register use is killed.
2044 assert(KillRegs[0] == Dst ||
2045 TRI->isSubRegister(KillRegs[0], Dst) ||
2046 TRI->isSuperRegister(KillRegs[0], Dst));
2047 // Last def is now dead.
2048 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2050 VRM.RemoveMachineInstrFromMaps(&MI);
2053 Spills.disallowClobberPhysReg(VirtReg);
2054 goto ProcessNextInst;
2057 // If it's not a no-op copy, it clobbers the value in the destreg.
2058 Spills.ClobberPhysReg(VirtReg);
2059 ReusedOperands.markClobbered(VirtReg);
2061 // Check to see if this instruction is a load from a stack slot into
2062 // a register. If so, this provides the stack slot value in the reg.
2064 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2065 assert(DestReg == VirtReg && "Unknown load situation!");
2067 // If it is a folded reference, then it's not safe to clobber.
2068 bool Folded = FoldedSS.count(FrameIdx);
2069 // Otherwise, if it wasn't available, remember that it is now!
2070 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2071 goto ProcessNextInst;
2077 unsigned SubIdx = MO.getSubReg();
2078 bool DoReMat = VRM.isReMaterialized(VirtReg);
2080 ReMatDefs.insert(&MI);
2082 // The only vregs left are stack slot definitions.
2083 int StackSlot = VRM.getStackSlot(VirtReg);
2084 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2086 // If this def is part of a two-address operand, make sure to execute
2087 // the store from the correct physical register.
2090 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2091 PhysReg = MI.getOperand(TiedOp).getReg();
2093 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2094 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2095 "Can't find corresponding super-register!");
2099 PhysReg = VRM.getPhys(VirtReg);
2100 if (ReusedOperands.isClobbered(PhysReg)) {
2101 // Another def has taken the assigned physreg. It must have been a
2102 // use&def which got it due to reuse. Undo the reuse!
2103 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2104 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2108 assert(PhysReg && "VR not assigned a physical register?");
2109 RegInfo->setPhysRegUsed(PhysReg);
2110 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2111 ReusedOperands.markClobbered(RReg);
2112 MI.getOperand(i).setReg(RReg);
2113 MI.getOperand(i).setSubReg(0);
2116 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2117 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2118 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2119 NextMII = next(MII);
2121 // Check to see if this is a noop copy. If so, eliminate the
2122 // instruction before considering the dest reg to be changed.
2124 unsigned Src, Dst, SrcSR, DstSR;
2125 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2127 DOUT << "Removing now-noop copy: " << MI;
2128 InvalidateKills(MI, TRI, RegKills, KillOps);
2129 VRM.RemoveMachineInstrFromMaps(&MI);
2132 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2133 goto ProcessNextInst;
2139 DistanceMap.insert(std::make_pair(&MI, Dist++));
2140 if (!Erased && !BackTracked) {
2141 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2142 UpdateKills(*II, TRI, RegKills, KillOps);
2151 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2152 switch (RewriterOpt) {
2153 default: assert(0 && "Unreachable!");
2155 return new LocalRewriter();
2157 return new TrivialRewriter();