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 "VirtRegMap.h"
13 #include "llvm/Function.h"
14 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineRegisterInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/Statistic.h"
29 STATISTIC(NumDSE , "Number of dead stores elided");
30 STATISTIC(NumDSS , "Number of dead spill slots removed");
31 STATISTIC(NumCommutes, "Number of instructions commuted");
32 STATISTIC(NumDRM , "Number of re-materializable defs elided");
33 STATISTIC(NumStores , "Number of stores added");
34 STATISTIC(NumPSpills , "Number of physical register spills");
35 STATISTIC(NumOmitted , "Number of reloads omited");
36 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
37 STATISTIC(NumCopified, "Number of available reloads turned into copies");
38 STATISTIC(NumReMats , "Number of re-materialization");
39 STATISTIC(NumLoads , "Number of loads added");
40 STATISTIC(NumReused , "Number of values reused");
41 STATISTIC(NumDCE , "Number of copies elided");
42 STATISTIC(NumSUnfold , "Number of stores unfolded");
43 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
46 enum RewriterName { local, trivial };
49 static cl::opt<RewriterName>
50 RewriterOpt("rewriter",
51 cl::desc("Rewriter to use (default=local)"),
53 cl::values(clEnumVal(local, "local rewriter"),
54 clEnumVal(trivial, "trivial rewriter"),
59 ScheduleSpills("schedule-spills",
60 cl::desc("Schedule spill code"),
63 VirtRegRewriter::~VirtRegRewriter() {}
65 /// substitutePhysReg - Replace virtual register in MachineOperand with a
66 /// physical register. Do the right thing with the sub-register index.
67 /// Note that operands may be added, so the MO reference is no longer valid.
68 static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
69 const TargetRegisterInfo &TRI) {
70 if (unsigned SubIdx = MO.getSubReg()) {
71 // Insert the physical subreg and reset the subreg field.
72 MO.setReg(TRI.getSubReg(Reg, SubIdx));
75 // Any def, dead, and kill flags apply to the full virtual register, so they
76 // also apply to the full physical register. Add imp-def/dead and imp-kill
78 MachineInstr &MI = *MO.getParent();
81 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
83 MI.addRegisterDefined(Reg, &TRI);
84 else if (!MO.isUndef() &&
86 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
87 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
95 /// This class is intended for use with the new spilling framework only. It
96 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
98 struct TrivialRewriter : public VirtRegRewriter {
100 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
101 LiveIntervals* LIs) {
102 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
103 DEBUG(dbgs() << "********** Function: "
104 << MF.getFunction()->getName() << '\n');
105 DEBUG(dbgs() << "**** Machine Instrs"
106 << "(NOTE! Does not include spills and reloads!) ****\n");
109 MachineRegisterInfo *mri = &MF.getRegInfo();
110 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
112 bool changed = false;
114 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
115 liItr != liEnd; ++liItr) {
117 const LiveInterval *li = liItr->second;
118 unsigned reg = li->reg;
120 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
122 mri->setPhysRegUsed(reg);
125 if (!VRM.hasPhys(reg))
127 unsigned pReg = VRM.getPhys(reg);
128 mri->setPhysRegUsed(pReg);
129 // Copy the register use-list before traversing it.
130 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
131 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
132 E = mri->reg_end(); I != E; ++I)
133 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
134 for (unsigned N=0; N != reglist.size(); ++N)
135 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
137 changed |= !reglist.empty();
141 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
151 // ************************************************************************ //
155 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
156 /// from top down, keep track of which spill slots or remat are available in
159 /// Note that not all physregs are created equal here. In particular, some
160 /// physregs are reloads that we are allowed to clobber or ignore at any time.
161 /// Other physregs are values that the register allocated program is using
162 /// that we cannot CHANGE, but we can read if we like. We keep track of this
163 /// on a per-stack-slot / remat id basis as the low bit in the value of the
164 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
165 /// this bit and addAvailable sets it if.
166 class AvailableSpills {
167 const TargetRegisterInfo *TRI;
168 const TargetInstrInfo *TII;
170 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
171 // or remat'ed virtual register values that are still available, due to
172 // being loaded or stored to, but not invalidated yet.
173 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
175 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
176 // indicating which stack slot values are currently held by a physreg. This
177 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
178 // physreg is modified.
179 std::multimap<unsigned, int> PhysRegsAvailable;
181 void disallowClobberPhysRegOnly(unsigned PhysReg);
183 void ClobberPhysRegOnly(unsigned PhysReg);
185 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
186 : TRI(tri), TII(tii) {
189 /// clear - Reset the state.
191 SpillSlotsOrReMatsAvailable.clear();
192 PhysRegsAvailable.clear();
195 const TargetRegisterInfo *getRegInfo() const { return TRI; }
197 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
198 /// available in a physical register, return that PhysReg, otherwise
200 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
201 std::map<int, unsigned>::const_iterator I =
202 SpillSlotsOrReMatsAvailable.find(Slot);
203 if (I != SpillSlotsOrReMatsAvailable.end()) {
204 return I->second >> 1; // Remove the CanClobber bit.
209 /// addAvailable - Mark that the specified stack slot / remat is available
210 /// in the specified physreg. If CanClobber is true, the physreg can be
211 /// modified at any time without changing the semantics of the program.
212 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
213 // If this stack slot is thought to be available in some other physreg,
214 // remove its record.
215 ModifyStackSlotOrReMat(SlotOrReMat);
217 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
218 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
219 (unsigned)CanClobber;
221 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
222 DEBUG(dbgs() << "Remembering RM#"
223 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
225 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
226 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
229 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
230 /// the value of the specified stackslot register if it desires. The
231 /// specified stack slot must be available in a physreg for this query to
233 bool canClobberPhysRegForSS(int SlotOrReMat) const {
234 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
235 "Value not available!");
236 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
239 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
240 /// physical register where values for some stack slot(s) might be
242 bool canClobberPhysReg(unsigned PhysReg) const {
243 std::multimap<unsigned, int>::const_iterator I =
244 PhysRegsAvailable.lower_bound(PhysReg);
245 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
246 int SlotOrReMat = I->second;
248 if (!canClobberPhysRegForSS(SlotOrReMat))
254 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
255 /// stackslot register. The register is still available but is no longer
256 /// allowed to be modifed.
257 void disallowClobberPhysReg(unsigned PhysReg);
259 /// ClobberPhysReg - This is called when the specified physreg changes
260 /// value. We use this to invalidate any info about stuff that lives in
261 /// it and any of its aliases.
262 void ClobberPhysReg(unsigned PhysReg);
264 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
265 /// slot changes. This removes information about which register the
266 /// previous value for this slot lives in (as the previous value is dead
268 void ModifyStackSlotOrReMat(int SlotOrReMat);
270 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
271 /// into the specified MBB. Add available physical registers as potential
272 /// live-in's. If they are reused in the MBB, they will be added to the
273 /// live-in set to make register scavenger and post-allocation scheduler.
274 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
275 std::vector<MachineOperand*> &KillOps);
280 // ************************************************************************ //
282 // Given a location where a reload of a spilled register or a remat of
283 // a constant is to be inserted, attempt to find a safe location to
284 // insert the load at an earlier point in the basic-block, to hide
285 // latency of the load and to avoid address-generation interlock
287 static MachineBasicBlock::iterator
288 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
289 MachineBasicBlock::iterator const Begin,
291 const TargetRegisterInfo *TRI,
294 const TargetInstrInfo *TII,
295 const MachineFunction &MF)
300 // Spill backscheduling is of primary interest to addresses, so
301 // don't do anything if the register isn't in the register class
302 // used for pointers.
304 const TargetLowering *TL = MF.getTarget().getTargetLowering();
306 if (!TL->isTypeLegal(TL->getPointerTy()))
307 // Believe it or not, this is true on PIC16.
310 const TargetRegisterClass *ptrRegClass =
311 TL->getRegClassFor(TL->getPointerTy());
312 if (!ptrRegClass->contains(PhysReg))
315 // Scan upwards through the preceding instructions. If an instruction doesn't
316 // reference the stack slot or the register we're loading, we can
317 // backschedule the reload up past it.
318 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
319 while (NewInsertLoc != Begin) {
320 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
321 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
322 MachineOperand &Op = Prev->getOperand(i);
323 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
326 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
327 Prev->findRegisterDefOperand(PhysReg))
329 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
330 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
331 Prev->findRegisterDefOperand(*Alias))
337 // If we made it to the beginning of the block, turn around and move back
338 // down just past any existing reloads. They're likely to be reloads/remats
339 // for instructions earlier than what our current reload/remat is for, so
340 // they should be scheduled earlier.
341 if (NewInsertLoc == Begin) {
343 while (InsertLoc != NewInsertLoc &&
344 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
345 TII->isTriviallyReMaterializable(NewInsertLoc)))
354 // ReusedOp - For each reused operand, we keep track of a bit of information,
355 // in case we need to rollback upon processing a new operand. See comments
358 // The MachineInstr operand that reused an available value.
361 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
362 unsigned StackSlotOrReMat;
364 // PhysRegReused - The physical register the value was available in.
365 unsigned PhysRegReused;
367 // AssignedPhysReg - The physreg that was assigned for use by the reload.
368 unsigned AssignedPhysReg;
370 // VirtReg - The virtual register itself.
373 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
375 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
376 AssignedPhysReg(apr), VirtReg(vreg) {}
379 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
380 /// is reused instead of reloaded.
383 std::vector<ReusedOp> Reuses;
384 BitVector PhysRegsClobbered;
386 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
387 PhysRegsClobbered.resize(tri->getNumRegs());
390 bool hasReuses() const {
391 return !Reuses.empty();
394 /// addReuse - If we choose to reuse a virtual register that is already
395 /// available instead of reloading it, remember that we did so.
396 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
397 unsigned PhysRegReused, unsigned AssignedPhysReg,
399 // If the reload is to the assigned register anyway, no undo will be
401 if (PhysRegReused == AssignedPhysReg) return;
403 // Otherwise, remember this.
404 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
405 AssignedPhysReg, VirtReg));
408 void markClobbered(unsigned PhysReg) {
409 PhysRegsClobbered.set(PhysReg);
412 bool isClobbered(unsigned PhysReg) const {
413 return PhysRegsClobbered.test(PhysReg);
416 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
417 /// is some other operand that is using the specified register, either pick
418 /// a new register to use, or evict the previous reload and use this reg.
419 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
420 MachineFunction &MF, MachineInstr *MI,
421 AvailableSpills &Spills,
422 std::vector<MachineInstr*> &MaybeDeadStores,
423 SmallSet<unsigned, 8> &Rejected,
425 std::vector<MachineOperand*> &KillOps,
428 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
429 /// 'Rejected' set to remember which registers have been considered and
430 /// rejected for the reload. This avoids infinite looping in case like
433 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
434 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
436 /// sees r1 is taken by t2, tries t2's reload register r0
437 /// sees r0 is taken by t3, tries t3's reload register r1
438 /// sees r1 is taken by t2, tries t2's reload register r0 ...
439 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
440 AvailableSpills &Spills,
441 std::vector<MachineInstr*> &MaybeDeadStores,
443 std::vector<MachineOperand*> &KillOps,
445 SmallSet<unsigned, 8> Rejected;
446 MachineFunction &MF = *MI->getParent()->getParent();
447 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
448 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
449 Rejected, RegKills, KillOps, VRM);
455 // ****************** //
456 // Utility Functions //
457 // ****************** //
459 /// findSinglePredSuccessor - Return via reference a vector of machine basic
460 /// blocks each of which is a successor of the specified BB and has no other
462 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
463 SmallVectorImpl<MachineBasicBlock *> &Succs){
464 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
465 SE = MBB->succ_end(); SI != SE; ++SI) {
466 MachineBasicBlock *SuccMBB = *SI;
467 if (SuccMBB->pred_size() == 1)
468 Succs.push_back(SuccMBB);
472 /// InvalidateKill - Invalidate register kill information for a specific
473 /// register. This also unsets the kills marker on the last kill operand.
474 static void InvalidateKill(unsigned Reg,
475 const TargetRegisterInfo* TRI,
477 std::vector<MachineOperand*> &KillOps) {
479 KillOps[Reg]->setIsKill(false);
480 // KillOps[Reg] might be a def of a super-register.
481 unsigned KReg = KillOps[Reg]->getReg();
482 KillOps[KReg] = NULL;
483 RegKills.reset(KReg);
484 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
486 KillOps[*SR]->setIsKill(false);
494 /// InvalidateKills - MI is going to be deleted. If any of its operands are
495 /// marked kill, then invalidate the information.
496 static void InvalidateKills(MachineInstr &MI,
497 const TargetRegisterInfo* TRI,
499 std::vector<MachineOperand*> &KillOps,
500 SmallVector<unsigned, 2> *KillRegs = NULL) {
501 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
502 MachineOperand &MO = MI.getOperand(i);
503 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
505 unsigned Reg = MO.getReg();
506 if (TargetRegisterInfo::isVirtualRegister(Reg))
509 KillRegs->push_back(Reg);
510 assert(Reg < KillOps.size());
511 if (KillOps[Reg] == &MO) {
514 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
524 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
525 /// (since its spill instruction is removed), mark it isDead. Also checks if
526 /// the def MI has other definition operands that are not dead. Returns it by
528 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
529 MachineInstr &NewDef, unsigned Reg,
531 const TargetRegisterInfo *TRI) {
532 // Due to remat, it's possible this reg isn't being reused. That is,
533 // the def of this reg (by prev MI) is now dead.
534 MachineInstr *DefMI = I;
535 MachineOperand *DefOp = NULL;
536 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
537 MachineOperand &MO = DefMI->getOperand(i);
538 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
540 if (MO.getReg() == Reg)
542 else if (!MO.isDead())
548 bool FoundUse = false, Done = false;
549 MachineBasicBlock::iterator E = &NewDef;
551 for (; !Done && I != E; ++I) {
552 MachineInstr *NMI = I;
553 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
554 MachineOperand &MO = NMI->getOperand(j);
555 if (!MO.isReg() || MO.getReg() == 0 ||
556 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
560 Done = true; // Stop after scanning all the operands of this MI.
571 /// UpdateKills - Track and update kill info. If a MI reads a register that is
572 /// marked kill, then it must be due to register reuse. Transfer the kill info
574 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
576 std::vector<MachineOperand*> &KillOps) {
577 // These do not affect kill info at all.
578 if (MI.isDebugValue())
580 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
581 MachineOperand &MO = MI.getOperand(i);
582 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
584 unsigned Reg = MO.getReg();
588 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
589 // That can't be right. Register is killed but not re-defined and it's
590 // being reused. Let's fix that.
591 KillOps[Reg]->setIsKill(false);
592 // KillOps[Reg] might be a def of a super-register.
593 unsigned KReg = KillOps[Reg]->getReg();
594 KillOps[KReg] = NULL;
595 RegKills.reset(KReg);
597 // Must be a def of a super-register. Its other sub-regsters are no
598 // longer killed as well.
599 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
604 // Check for subreg kills as well.
610 // = d4 <avoiding reload>
611 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
613 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
614 KillOps[SReg]->setIsKill(false);
615 unsigned KReg = KillOps[SReg]->getReg();
616 KillOps[KReg] = NULL;
617 RegKills.reset(KReg);
619 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
620 KillOps[*SSR] = NULL;
621 RegKills.reset(*SSR);
630 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
637 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI.getOperand(i);
639 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
641 unsigned Reg = MO.getReg();
644 // It also defines (or partially define) aliases.
645 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
649 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
656 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
658 static void ReMaterialize(MachineBasicBlock &MBB,
659 MachineBasicBlock::iterator &MII,
660 unsigned DestReg, unsigned Reg,
661 const TargetInstrInfo *TII,
662 const TargetRegisterInfo *TRI,
664 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
666 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
667 assert(TID.getNumDefs() == 1 &&
668 "Don't know how to remat instructions that define > 1 values!");
670 TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
671 MachineInstr *NewMI = prior(MII);
672 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
673 MachineOperand &MO = NewMI->getOperand(i);
674 if (!MO.isReg() || MO.getReg() == 0)
676 unsigned VirtReg = MO.getReg();
677 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
680 unsigned Phys = VRM.getPhys(VirtReg);
681 assert(Phys && "Virtual register is not assigned a register?");
682 substitutePhysReg(MO, Phys, *TRI);
687 /// findSuperReg - Find the SubReg's super-register of given register class
688 /// where its SubIdx sub-register is SubReg.
689 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
690 unsigned SubIdx, const TargetRegisterInfo *TRI) {
691 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
694 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
700 // ******************************** //
701 // Available Spills Implementation //
702 // ******************************** //
704 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
705 /// stackslot register. The register is still available but is no longer
706 /// allowed to be modifed.
707 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
708 std::multimap<unsigned, int>::iterator I =
709 PhysRegsAvailable.lower_bound(PhysReg);
710 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
711 int SlotOrReMat = I->second;
713 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
714 "Bidirectional map mismatch!");
715 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
716 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
717 << " copied, it is available for use but can no longer be modified\n");
721 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
722 /// stackslot register and its aliases. The register and its aliases may
723 /// still available but is no longer allowed to be modifed.
724 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
725 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
726 disallowClobberPhysRegOnly(*AS);
727 disallowClobberPhysRegOnly(PhysReg);
730 /// ClobberPhysRegOnly - This is called when the specified physreg changes
731 /// value. We use this to invalidate any info about stuff we thing lives in it.
732 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
733 std::multimap<unsigned, int>::iterator I =
734 PhysRegsAvailable.lower_bound(PhysReg);
735 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
736 int SlotOrReMat = I->second;
737 PhysRegsAvailable.erase(I++);
738 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
739 "Bidirectional map mismatch!");
740 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
741 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
742 << " clobbered, invalidating ");
743 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
744 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
746 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
750 /// ClobberPhysReg - This is called when the specified physreg changes
751 /// value. We use this to invalidate any info about stuff we thing lives in
752 /// it and any of its aliases.
753 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
754 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
755 ClobberPhysRegOnly(*AS);
756 ClobberPhysRegOnly(PhysReg);
759 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
760 /// into the specified MBB. Add available physical registers as potential
761 /// live-in's. If they are reused in the MBB, they will be added to the
762 /// live-in set to make register scavenger and post-allocation scheduler.
763 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
765 std::vector<MachineOperand*> &KillOps) {
766 std::set<unsigned> NotAvailable;
767 for (std::multimap<unsigned, int>::iterator
768 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
770 unsigned Reg = I->first;
771 const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
772 // FIXME: A temporary workaround. We can't reuse available value if it's
773 // not safe to move the def of the virtual register's class. e.g.
774 // X86::RFP* register classes. Do not add it as a live-in.
775 if (!TII->isSafeToMoveRegClassDefs(RC))
776 // This is no longer available.
777 NotAvailable.insert(Reg);
780 InvalidateKill(Reg, TRI, RegKills, KillOps);
783 // Skip over the same register.
784 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
785 while (NI != E && NI->first == Reg) {
791 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
792 E = NotAvailable.end(); I != E; ++I) {
794 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
796 ClobberPhysReg(*SubRegs);
800 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
801 /// slot changes. This removes information about which register the previous
802 /// value for this slot lives in (as the previous value is dead now).
803 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
804 std::map<int, unsigned>::iterator It =
805 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
806 if (It == SpillSlotsOrReMatsAvailable.end()) return;
807 unsigned Reg = It->second >> 1;
808 SpillSlotsOrReMatsAvailable.erase(It);
810 // This register may hold the value of multiple stack slots, only remove this
811 // stack slot from the set of values the register contains.
812 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
814 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
815 "Map inverse broken!");
816 if (I->second == SlotOrReMat) break;
818 PhysRegsAvailable.erase(I);
821 // ************************** //
822 // Reuse Info Implementation //
823 // ************************** //
825 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
826 /// is some other operand that is using the specified register, either pick
827 /// a new register to use, or evict the previous reload and use this reg.
828 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
831 MachineInstr *MI, AvailableSpills &Spills,
832 std::vector<MachineInstr*> &MaybeDeadStores,
833 SmallSet<unsigned, 8> &Rejected,
835 std::vector<MachineOperand*> &KillOps,
837 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
838 const TargetRegisterInfo *TRI = Spills.getRegInfo();
840 if (Reuses.empty()) return PhysReg; // This is most often empty.
842 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
843 ReusedOp &Op = Reuses[ro];
844 // If we find some other reuse that was supposed to use this register
845 // exactly for its reload, we can change this reload to use ITS reload
846 // register. That is, unless its reload register has already been
847 // considered and subsequently rejected because it has also been reused
848 // by another operand.
849 if (Op.PhysRegReused == PhysReg &&
850 Rejected.count(Op.AssignedPhysReg) == 0 &&
851 RC->contains(Op.AssignedPhysReg)) {
852 // Yup, use the reload register that we didn't use before.
853 unsigned NewReg = Op.AssignedPhysReg;
854 Rejected.insert(PhysReg);
855 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores,
856 Rejected, RegKills, KillOps, VRM);
858 // Otherwise, we might also have a problem if a previously reused
859 // value aliases the new register. If so, codegen the previous reload
861 unsigned PRRU = Op.PhysRegReused;
862 if (TRI->regsOverlap(PRRU, PhysReg)) {
863 // Okay, we found out that an alias of a reused register
864 // was used. This isn't good because it means we have
865 // to undo a previous reuse.
866 MachineBasicBlock *MBB = MI->getParent();
867 const TargetRegisterClass *AliasRC =
868 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
870 // Copy Op out of the vector and remove it, we're going to insert an
871 // explicit load for it.
873 Reuses.erase(Reuses.begin()+ro);
875 // MI may be using only a sub-register of PhysRegUsed.
876 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
878 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
879 "A reuse cannot be a virtual register");
880 if (PRRU != RealPhysRegUsed) {
881 // What was the sub-register index?
882 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
884 "Operand physreg is not a sub-register of PhysRegUsed");
887 // Ok, we're going to try to reload the assigned physreg into the
888 // slot that we were supposed to in the first place. However, that
889 // register could hold a reuse. Check to see if it conflicts or
890 // would prefer us to use a different register.
891 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
892 MF, MI, Spills, MaybeDeadStores,
893 Rejected, RegKills, KillOps, VRM);
895 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
896 int SSorRMId = DoReMat
897 ? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
899 // Back-schedule reloads and remats.
900 MachineBasicBlock::iterator InsertLoc =
901 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
902 DoReMat, SSorRMId, TII, MF);
905 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
908 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
909 NewOp.StackSlotOrReMat, AliasRC, TRI);
910 MachineInstr *LoadMI = prior(InsertLoc);
911 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
912 // Any stores to this stack slot are not dead anymore.
913 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
916 Spills.ClobberPhysReg(NewPhysReg);
917 Spills.ClobberPhysReg(NewOp.PhysRegReused);
919 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
920 MI->getOperand(NewOp.Operand).setReg(RReg);
921 MI->getOperand(NewOp.Operand).setSubReg(0);
923 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
924 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
925 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
927 DEBUG(dbgs() << "Reuse undone!\n");
930 // Finally, PhysReg is now available, go ahead and use it.
938 // ************************************************************************ //
940 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
941 /// stack slot mod/ref. It also checks if it's possible to unfold the
942 /// instruction by having it define a specified physical register instead.
943 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
944 const TargetInstrInfo *TII,
945 const TargetRegisterInfo *TRI,
947 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
951 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
952 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
953 unsigned VirtReg = I->second.first;
954 VirtRegMap::ModRef MR = I->second.second;
955 if (MR & VirtRegMap::isModRef)
956 if (VRM.getStackSlot(VirtReg) == SS) {
957 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
964 // Does the instruction uses a register that overlaps the scratch register?
965 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
966 MachineOperand &MO = MI.getOperand(i);
967 if (!MO.isReg() || MO.getReg() == 0)
969 unsigned Reg = MO.getReg();
970 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
971 if (!VRM.hasPhys(Reg))
973 Reg = VRM.getPhys(Reg);
975 if (TRI->regsOverlap(PhysReg, Reg))
981 /// FindFreeRegister - Find a free register of a given register class by looking
982 /// at (at most) the last two machine instructions.
983 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
984 MachineBasicBlock &MBB,
985 const TargetRegisterClass *RC,
986 const TargetRegisterInfo *TRI,
987 BitVector &AllocatableRegs) {
988 BitVector Defs(TRI->getNumRegs());
989 BitVector Uses(TRI->getNumRegs());
990 SmallVector<unsigned, 4> LocalUses;
991 SmallVector<unsigned, 4> Kills;
993 // Take a look at 2 instructions at most.
996 if (MII == MBB.begin())
998 MachineInstr *PrevMI = prior(MII);
1001 if (PrevMI->isDebugValue())
1002 continue; // Skip over dbg_value instructions.
1005 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
1006 MachineOperand &MO = PrevMI->getOperand(i);
1007 if (!MO.isReg() || MO.getReg() == 0)
1009 unsigned Reg = MO.getReg();
1012 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1015 LocalUses.push_back(Reg);
1016 if (MO.isKill() && AllocatableRegs[Reg])
1017 Kills.push_back(Reg);
1021 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1022 unsigned Kill = Kills[i];
1023 if (!Defs[Kill] && !Uses[Kill] &&
1027 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1028 unsigned Reg = LocalUses[i];
1030 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1039 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1040 const TargetRegisterInfo &TRI) {
1041 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1042 MachineOperand &MO = MI->getOperand(i);
1043 if (MO.isReg() && MO.getReg() == VirtReg)
1044 substitutePhysReg(MO, PhysReg, TRI);
1051 bool operator()(const std::pair<MachineInstr*, int> &A,
1052 const std::pair<MachineInstr*, int> &B) {
1053 return A.second < B.second;
1057 // ***************************** //
1058 // Local Spiller Implementation //
1059 // ***************************** //
1061 class LocalRewriter : public VirtRegRewriter {
1062 MachineRegisterInfo *MRI;
1063 const TargetRegisterInfo *TRI;
1064 const TargetInstrInfo *TII;
1066 BitVector AllocatableRegs;
1067 DenseMap<MachineInstr*, unsigned> DistanceMap;
1068 DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
1070 MachineBasicBlock *MBB; // Basic block currently being processed.
1074 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1075 LiveIntervals* LIs);
1079 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1080 MachineBasicBlock::iterator &MII,
1081 std::vector<MachineInstr*> &MaybeDeadStores,
1082 AvailableSpills &Spills,
1083 BitVector &RegKills,
1084 std::vector<MachineOperand*> &KillOps);
1086 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1087 std::vector<MachineInstr*> &MaybeDeadStores,
1088 AvailableSpills &Spills,
1089 BitVector &RegKills,
1090 std::vector<MachineOperand*> &KillOps);
1092 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1093 unsigned VirtReg, unsigned SrcReg, int SS,
1094 AvailableSpills &Spills,
1095 BitVector &RegKills,
1096 std::vector<MachineOperand*> &KillOps,
1097 const TargetRegisterInfo *TRI);
1099 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1100 int Idx, unsigned PhysReg, int StackSlot,
1101 const TargetRegisterClass *RC,
1102 bool isAvailable, MachineInstr *&LastStore,
1103 AvailableSpills &Spills,
1104 SmallSet<MachineInstr*, 4> &ReMatDefs,
1105 BitVector &RegKills,
1106 std::vector<MachineOperand*> &KillOps);
1108 void TransferDeadness(unsigned Reg, BitVector &RegKills,
1109 std::vector<MachineOperand*> &KillOps);
1111 bool InsertEmergencySpills(MachineInstr *MI);
1113 bool InsertRestores(MachineInstr *MI,
1114 AvailableSpills &Spills,
1115 BitVector &RegKills,
1116 std::vector<MachineOperand*> &KillOps);
1118 bool InsertSpills(MachineInstr *MI);
1120 void RewriteMBB(LiveIntervals *LIs,
1121 AvailableSpills &Spills, BitVector &RegKills,
1122 std::vector<MachineOperand*> &KillOps);
1126 bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1127 LiveIntervals* LIs) {
1128 MRI = &MF.getRegInfo();
1129 TRI = MF.getTarget().getRegisterInfo();
1130 TII = MF.getTarget().getInstrInfo();
1132 AllocatableRegs = TRI->getAllocatableSet(MF);
1133 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1134 << MF.getFunction()->getName() << "':\n");
1135 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1136 " reloads!) ****\n");
1139 // Spills - Keep track of which spilled values are available in physregs
1140 // so that we can choose to reuse the physregs instead of emitting
1141 // reloads. This is usually refreshed per basic block.
1142 AvailableSpills Spills(TRI, TII);
1144 // Keep track of kill information.
1145 BitVector RegKills(TRI->getNumRegs());
1146 std::vector<MachineOperand*> KillOps;
1147 KillOps.resize(TRI->getNumRegs(), NULL);
1149 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1150 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1151 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1153 // Traverse the basic blocks depth first.
1154 MachineBasicBlock *Entry = MF.begin();
1155 SmallPtrSet<MachineBasicBlock*,16> Visited;
1156 for (df_ext_iterator<MachineBasicBlock*,
1157 SmallPtrSet<MachineBasicBlock*,16> >
1158 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1161 if (!EarlyVisited.count(MBB))
1162 RewriteMBB(LIs, Spills, RegKills, KillOps);
1164 // If this MBB is the only predecessor of a successor. Keep the
1165 // availability information and visit it next.
1167 // Keep visiting single predecessor successor as long as possible.
1168 SinglePredSuccs.clear();
1169 findSinglePredSuccessor(MBB, SinglePredSuccs);
1170 if (SinglePredSuccs.empty())
1173 // FIXME: More than one successors, each of which has MBB has
1174 // the only predecessor.
1175 MBB = SinglePredSuccs[0];
1176 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1177 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1178 RewriteMBB(LIs, Spills, RegKills, KillOps);
1183 // Clear the availability info.
1187 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1190 // Mark unused spill slots.
1191 MachineFrameInfo *MFI = MF.getFrameInfo();
1192 int SS = VRM->getLowSpillSlot();
1193 if (SS != VirtRegMap::NO_STACK_SLOT) {
1194 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1195 SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1196 if (!VRM->isSpillSlotUsed(SS)) {
1197 MFI->RemoveStackObject(SS);
1198 for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1199 MachineInstr *DVMI = DbgValues[j];
1200 MachineBasicBlock *DVMBB = DVMI->getParent();
1201 DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1202 VRM->RemoveMachineInstrFromMaps(DVMI);
1210 Slot2DbgValues.clear();
1215 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1216 /// a scratch register is available.
1217 /// xorq %r12<kill>, %r13
1218 /// addq %rax, -184(%rbp)
1219 /// addq %r13, -184(%rbp)
1221 /// xorq %r12<kill>, %r13
1222 /// movq -184(%rbp), %r12
1225 /// movq %r12, -184(%rbp)
1226 bool LocalRewriter::
1227 OptimizeByUnfold2(unsigned VirtReg, int SS,
1228 MachineBasicBlock::iterator &MII,
1229 std::vector<MachineInstr*> &MaybeDeadStores,
1230 AvailableSpills &Spills,
1231 BitVector &RegKills,
1232 std::vector<MachineOperand*> &KillOps) {
1234 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1235 // Skip over dbg_value instructions.
1236 while (NextMII != MBB->end() && NextMII->isDebugValue())
1237 NextMII = llvm::next(NextMII);
1238 if (NextMII == MBB->end())
1241 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1244 // Now let's see if the last couple of instructions happens to have freed up
1246 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1247 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1251 MachineFunction &MF = *MBB->getParent();
1252 TRI = MF.getTarget().getRegisterInfo();
1253 MachineInstr &MI = *MII;
1254 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1257 // If the next instruction also folds the same SS modref and can be unfoled,
1258 // then it's worthwhile to issue a load from SS into the free register and
1259 // then unfold these instructions.
1260 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1263 // Back-schedule reloads and remats.
1264 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1266 // Load from SS to the spare physical register.
1267 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1268 // This invalidates Phys.
1269 Spills.ClobberPhysReg(PhysReg);
1270 // Remember it's available.
1271 Spills.addAvailable(SS, PhysReg);
1272 MaybeDeadStores[SS] = NULL;
1274 // Unfold current MI.
1275 SmallVector<MachineInstr*, 4> NewMIs;
1276 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1277 llvm_unreachable("Unable unfold the load / store folding instruction!");
1278 assert(NewMIs.size() == 1);
1279 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1280 VRM->transferRestorePts(&MI, NewMIs[0]);
1281 MII = MBB->insert(MII, NewMIs[0]);
1282 InvalidateKills(MI, TRI, RegKills, KillOps);
1283 VRM->RemoveMachineInstrFromMaps(&MI);
1287 // Unfold next instructions that fold the same SS.
1289 MachineInstr &NextMI = *NextMII;
1290 NextMII = llvm::next(NextMII);
1292 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1293 llvm_unreachable("Unable unfold the load / store folding instruction!");
1294 assert(NewMIs.size() == 1);
1295 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1296 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1297 MBB->insert(NextMII, NewMIs[0]);
1298 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1299 VRM->RemoveMachineInstrFromMaps(&NextMI);
1300 MBB->erase(&NextMI);
1302 // Skip over dbg_value instructions.
1303 while (NextMII != MBB->end() && NextMII->isDebugValue())
1304 NextMII = llvm::next(NextMII);
1305 if (NextMII == MBB->end())
1307 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1309 // Store the value back into SS.
1310 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1311 MachineInstr *StoreMI = prior(NextMII);
1312 VRM->addSpillSlotUse(SS, StoreMI);
1313 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1318 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1319 /// instruction. e.g.
1321 /// movl %eax, -32(%ebp)
1322 /// movl -36(%ebp), %eax
1323 /// orl %eax, -32(%ebp)
1326 /// orl -36(%ebp), %eax
1327 /// mov %eax, -32(%ebp)
1328 /// This enables unfolding optimization for a subsequent instruction which will
1329 /// also eliminate the newly introduced store instruction.
1330 bool LocalRewriter::
1331 OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1332 std::vector<MachineInstr*> &MaybeDeadStores,
1333 AvailableSpills &Spills,
1334 BitVector &RegKills,
1335 std::vector<MachineOperand*> &KillOps) {
1336 MachineFunction &MF = *MBB->getParent();
1337 MachineInstr &MI = *MII;
1338 unsigned UnfoldedOpc = 0;
1339 unsigned UnfoldPR = 0;
1340 unsigned UnfoldVR = 0;
1341 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1342 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1343 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1344 // Only transform a MI that folds a single register.
1347 UnfoldVR = I->second.first;
1348 VirtRegMap::ModRef MR = I->second.second;
1349 // MI2VirtMap be can updated which invalidate the iterator.
1350 // Increment the iterator first.
1352 if (VRM->isAssignedReg(UnfoldVR))
1354 // If this reference is not a use, any previous store is now dead.
1355 // Otherwise, the store to this stack slot is not dead anymore.
1356 FoldedSS = VRM->getStackSlot(UnfoldVR);
1357 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1358 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1359 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1360 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1363 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1372 // Look for other unfolding opportunities.
1373 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1377 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1378 MachineOperand &MO = MI.getOperand(i);
1379 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1381 unsigned VirtReg = MO.getReg();
1382 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1384 if (VRM->isAssignedReg(VirtReg)) {
1385 unsigned PhysReg = VRM->getPhys(VirtReg);
1386 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1388 } else if (VRM->isReMaterialized(VirtReg))
1390 int SS = VRM->getStackSlot(VirtReg);
1391 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1393 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1397 if (VRM->hasPhys(VirtReg)) {
1398 PhysReg = VRM->getPhys(VirtReg);
1399 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1403 // Ok, we'll need to reload the value into a register which makes
1404 // it impossible to perform the store unfolding optimization later.
1405 // Let's see if it is possible to fold the load if the store is
1406 // unfolded. This allows us to perform the store unfolding
1408 SmallVector<MachineInstr*, 4> NewMIs;
1409 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1410 assert(NewMIs.size() == 1);
1411 MachineInstr *NewMI = NewMIs.back();
1412 MBB->insert(MII, NewMI);
1414 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1416 SmallVector<unsigned, 1> Ops;
1418 MachineInstr *FoldedMI = TII->foldMemoryOperand(NewMI, Ops, SS);
1419 NewMI->eraseFromParent();
1421 VRM->addSpillSlotUse(SS, FoldedMI);
1422 if (!VRM->hasPhys(UnfoldVR))
1423 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1424 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1426 InvalidateKills(MI, TRI, RegKills, KillOps);
1427 VRM->RemoveMachineInstrFromMaps(&MI);
1437 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1438 /// where SrcReg is r1 and it is tied to r0. Return true if after
1439 /// commuting this instruction it will be r0 = op r2, r1.
1440 static bool CommuteChangesDestination(MachineInstr *DefMI,
1441 const TargetInstrDesc &TID,
1443 const TargetInstrInfo *TII,
1445 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1447 if (!DefMI->getOperand(1).isReg() ||
1448 DefMI->getOperand(1).getReg() != SrcReg)
1451 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1453 unsigned SrcIdx1, SrcIdx2;
1454 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1456 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1463 /// CommuteToFoldReload -
1466 /// r1 = op r1, r2<kill>
1469 /// If op is commutable and r2 is killed, then we can xform these to
1470 /// r2 = op r2, fi#1
1472 bool LocalRewriter::
1473 CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1474 unsigned VirtReg, unsigned SrcReg, int SS,
1475 AvailableSpills &Spills,
1476 BitVector &RegKills,
1477 std::vector<MachineOperand*> &KillOps,
1478 const TargetRegisterInfo *TRI) {
1479 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1482 MachineInstr &MI = *MII;
1483 MachineBasicBlock::iterator DefMII = prior(MII);
1484 MachineInstr *DefMI = DefMII;
1485 const TargetInstrDesc &TID = DefMI->getDesc();
1487 if (DefMII != MBB->begin() &&
1488 TID.isCommutable() &&
1489 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1490 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1491 unsigned NewReg = NewDstMO.getReg();
1492 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1494 MachineInstr *ReloadMI = prior(DefMII);
1496 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1497 if (DestReg != SrcReg || FrameIdx != SS)
1499 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1503 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1505 assert(DefMI->getOperand(DefIdx).isReg() &&
1506 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1508 // Now commute def instruction.
1509 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1512 MBB->insert(MII, CommutedMI);
1513 SmallVector<unsigned, 1> Ops;
1514 Ops.push_back(NewDstIdx);
1515 MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
1516 // Not needed since foldMemoryOperand returns new MI.
1517 CommutedMI->eraseFromParent();
1521 VRM->addSpillSlotUse(SS, FoldedMI);
1522 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1523 // Insert new def MI and spill MI.
1524 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1525 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1527 MachineInstr *StoreMI = MII;
1528 VRM->addSpillSlotUse(SS, StoreMI);
1529 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1530 MII = FoldedMI; // Update MII to backtrack.
1532 // Delete all 3 old instructions.
1533 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1534 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1535 MBB->erase(ReloadMI);
1536 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1537 VRM->RemoveMachineInstrFromMaps(DefMI);
1539 InvalidateKills(MI, TRI, RegKills, KillOps);
1540 VRM->RemoveMachineInstrFromMaps(&MI);
1543 // If NewReg was previously holding value of some SS, it's now clobbered.
1544 // This has to be done now because it's a physical register. When this
1545 // instruction is re-visited, it's ignored.
1546 Spills.ClobberPhysReg(NewReg);
1555 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1556 /// the last store to the same slot is now dead. If so, remove the last store.
1557 void LocalRewriter::
1558 SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1559 int Idx, unsigned PhysReg, int StackSlot,
1560 const TargetRegisterClass *RC,
1561 bool isAvailable, MachineInstr *&LastStore,
1562 AvailableSpills &Spills,
1563 SmallSet<MachineInstr*, 4> &ReMatDefs,
1564 BitVector &RegKills,
1565 std::vector<MachineOperand*> &KillOps) {
1567 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1568 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1570 MachineInstr *StoreMI = prior(oldNextMII);
1571 VRM->addSpillSlotUse(StackSlot, StoreMI);
1572 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1574 // If there is a dead store to this stack slot, nuke it now.
1576 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1578 SmallVector<unsigned, 2> KillRegs;
1579 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1580 MachineBasicBlock::iterator PrevMII = LastStore;
1581 bool CheckDef = PrevMII != MBB->begin();
1584 VRM->RemoveMachineInstrFromMaps(LastStore);
1585 MBB->erase(LastStore);
1587 // Look at defs of killed registers on the store. Mark the defs
1588 // as dead since the store has been deleted and they aren't
1590 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1591 bool HasOtherDef = false;
1592 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1593 MachineInstr *DeadDef = PrevMII;
1594 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1595 // FIXME: This assumes a remat def does not have side effects.
1596 VRM->RemoveMachineInstrFromMaps(DeadDef);
1597 MBB->erase(DeadDef);
1605 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1606 // the last of multiple instructions is the actual store.
1607 LastStore = prior(oldNextMII);
1609 // If the stack slot value was previously available in some other
1610 // register, change it now. Otherwise, make the register available,
1612 Spills.ModifyStackSlotOrReMat(StackSlot);
1613 Spills.ClobberPhysReg(PhysReg);
1614 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1618 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1619 /// effect and all of its defs are dead.
1620 static bool isSafeToDelete(MachineInstr &MI) {
1621 const TargetInstrDesc &TID = MI.getDesc();
1622 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1623 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1624 TID.hasUnmodeledSideEffects())
1626 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1627 MachineOperand &MO = MI.getOperand(i);
1628 if (!MO.isReg() || !MO.getReg())
1630 if (MO.isDef() && !MO.isDead())
1632 if (MO.isUse() && MO.isKill())
1633 // FIXME: We can't remove kill markers or else the scavenger will assert.
1634 // An alternative is to add a ADD pseudo instruction to replace kill
1641 /// TransferDeadness - A identity copy definition is dead and it's being
1642 /// removed. Find the last def or use and mark it as dead / kill.
1643 void LocalRewriter::
1644 TransferDeadness(unsigned Reg, BitVector &RegKills,
1645 std::vector<MachineOperand*> &KillOps) {
1646 SmallPtrSet<MachineInstr*, 4> Seens;
1647 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1648 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1649 RE = MRI->reg_end(); RI != RE; ++RI) {
1650 MachineInstr *UDMI = &*RI;
1651 if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
1653 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1654 if (DI == DistanceMap.end())
1656 if (Seens.insert(UDMI))
1657 Refs.push_back(std::make_pair(UDMI, DI->second));
1662 std::sort(Refs.begin(), Refs.end(), RefSorter());
1664 while (!Refs.empty()) {
1665 MachineInstr *LastUDMI = Refs.back().first;
1668 MachineOperand *LastUD = NULL;
1669 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1670 MachineOperand &MO = LastUDMI->getOperand(i);
1671 if (!MO.isReg() || MO.getReg() != Reg)
1673 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1675 if (LastUDMI->isRegTiedToDefOperand(i))
1678 if (LastUD->isDef()) {
1679 // If the instruction has no side effect, delete it and propagate
1680 // backward further. Otherwise, mark is dead and we are done.
1681 if (!isSafeToDelete(*LastUDMI)) {
1682 LastUD->setIsDead();
1685 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1686 MBB->erase(LastUDMI);
1688 LastUD->setIsKill();
1690 KillOps[Reg] = LastUD;
1696 /// InsertEmergencySpills - Insert emergency spills before MI if requested by
1697 /// VRM. Return true if spills were inserted.
1698 bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1699 if (!VRM->hasEmergencySpills(MI))
1701 MachineBasicBlock::iterator MII = MI;
1702 SmallSet<int, 4> UsedSS;
1703 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1704 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1705 unsigned PhysReg = EmSpills[i];
1706 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
1707 assert(RC && "Unable to determine register class!");
1708 int SS = VRM->getEmergencySpillSlot(RC);
1709 if (UsedSS.count(SS))
1710 llvm_unreachable("Need to spill more than one physical registers!");
1712 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
1713 MachineInstr *StoreMI = prior(MII);
1714 VRM->addSpillSlotUse(SS, StoreMI);
1716 // Back-schedule reloads and remats.
1717 MachineBasicBlock::iterator InsertLoc =
1718 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1719 TII, *MBB->getParent());
1721 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
1723 MachineInstr *LoadMI = prior(InsertLoc);
1724 VRM->addSpillSlotUse(SS, LoadMI);
1726 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1731 /// InsertRestores - Restore registers before MI is requested by VRM. Return
1732 /// true is any instructions were inserted.
1733 bool LocalRewriter::InsertRestores(MachineInstr *MI,
1734 AvailableSpills &Spills,
1735 BitVector &RegKills,
1736 std::vector<MachineOperand*> &KillOps) {
1737 if (!VRM->isRestorePt(MI))
1739 MachineBasicBlock::iterator MII = MI;
1740 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1741 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1742 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1743 if (!VRM->getPreSplitReg(VirtReg))
1744 continue; // Split interval spilled again.
1745 unsigned Phys = VRM->getPhys(VirtReg);
1746 MRI->setPhysRegUsed(Phys);
1748 // Check if the value being restored if available. If so, it must be
1749 // from a predecessor BB that fallthrough into this BB. We do not
1755 // ... # r1 not clobbered
1758 bool DoReMat = VRM->isReMaterialized(VirtReg);
1759 int SSorRMId = DoReMat
1760 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1761 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1762 if (InReg == Phys) {
1763 // If the value is already available in the expected register, save
1764 // a reload / remat.
1766 DEBUG(dbgs() << "Reusing RM#"
1767 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1769 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1770 DEBUG(dbgs() << " from physreg "
1771 << TRI->getName(InReg) << " for vreg"
1772 << VirtReg <<" instead of reloading into physreg "
1773 << TRI->getName(Phys) << '\n');
1776 } else if (InReg && InReg != Phys) {
1778 DEBUG(dbgs() << "Reusing RM#"
1779 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1781 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1782 DEBUG(dbgs() << " from physreg "
1783 << TRI->getName(InReg) << " for vreg"
1784 << VirtReg <<" by copying it into physreg "
1785 << TRI->getName(Phys) << '\n');
1787 // If the reloaded / remat value is available in another register,
1788 // copy it to the desired register.
1790 // Back-schedule reloads and remats.
1791 MachineBasicBlock::iterator InsertLoc =
1792 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1794 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1795 TII->get(TargetOpcode::COPY), Phys)
1796 .addReg(InReg, RegState::Kill);
1798 // This invalidates Phys.
1799 Spills.ClobberPhysReg(Phys);
1800 // Remember it's available.
1801 Spills.addAvailable(SSorRMId, Phys);
1803 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1804 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1806 DEBUG(dbgs() << '\t' << *CopyMI);
1811 // Back-schedule reloads and remats.
1812 MachineBasicBlock::iterator InsertLoc =
1813 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1816 if (VRM->isReMaterialized(VirtReg)) {
1817 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1819 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1820 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1821 MachineInstr *LoadMI = prior(InsertLoc);
1822 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1824 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1827 // This invalidates Phys.
1828 Spills.ClobberPhysReg(Phys);
1829 // Remember it's available.
1830 Spills.addAvailable(SSorRMId, Phys);
1832 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1833 DEBUG(dbgs() << '\t' << *prior(MII));
1838 /// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1839 /// true if spills were inserted.
1840 bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1841 if (!VRM->isSpillPt(MI))
1843 MachineBasicBlock::iterator MII = MI;
1844 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1845 VRM->getSpillPtSpills(MI);
1846 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1847 unsigned VirtReg = SpillRegs[i].first;
1848 bool isKill = SpillRegs[i].second;
1849 if (!VRM->getPreSplitReg(VirtReg))
1850 continue; // Split interval spilled again.
1851 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1852 unsigned Phys = VRM->getPhys(VirtReg);
1853 int StackSlot = VRM->getStackSlot(VirtReg);
1854 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1855 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1857 MachineInstr *StoreMI = prior(oldNextMII);
1858 VRM->addSpillSlotUse(StackSlot, StoreMI);
1859 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1860 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1866 /// rewriteMBB - Keep track of which spills are available even after the
1867 /// register allocator is done with them. If possible, avoid reloading vregs.
1869 LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1870 AvailableSpills &Spills, BitVector &RegKills,
1871 std::vector<MachineOperand*> &KillOps) {
1873 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1874 << MBB->getName() << "':\n");
1876 MachineFunction &MF = *MBB->getParent();
1878 // MaybeDeadStores - When we need to write a value back into a stack slot,
1879 // keep track of the inserted store. If the stack slot value is never read
1880 // (because the value was used from some available register, for example), and
1881 // subsequently stored to, the original store is dead. This map keeps track
1882 // of inserted stores that are not used. If we see a subsequent store to the
1883 // same stack slot, the original store is deleted.
1884 std::vector<MachineInstr*> MaybeDeadStores;
1885 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1887 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1888 SmallSet<MachineInstr*, 4> ReMatDefs;
1891 SmallSet<unsigned, 2> KilledMIRegs;
1893 // Keep track of the registers we have already spilled in case there are
1894 // multiple defs of the same register in MI.
1895 SmallSet<unsigned, 8> SpilledMIRegs;
1899 KillOps.resize(TRI->getNumRegs(), NULL);
1901 DistanceMap.clear();
1902 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1904 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1906 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1907 NextMII = llvm::next(MII);
1909 if (InsertEmergencySpills(MII))
1910 NextMII = llvm::next(MII);
1912 InsertRestores(MII, Spills, RegKills, KillOps);
1914 if (InsertSpills(MII))
1915 NextMII = llvm::next(MII);
1917 bool Erased = false;
1918 bool BackTracked = false;
1919 MachineInstr &MI = *MII;
1921 // Remember DbgValue's which reference stack slots.
1922 if (MI.isDebugValue() && MI.getOperand(0).isFI())
1923 Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
1925 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1927 ReuseInfo ReusedOperands(MI, TRI);
1928 SmallVector<unsigned, 4> VirtUseOps;
1929 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1930 MachineOperand &MO = MI.getOperand(i);
1931 if (!MO.isReg() || MO.getReg() == 0)
1932 continue; // Ignore non-register operands.
1934 unsigned VirtReg = MO.getReg();
1935 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1936 // Ignore physregs for spilling, but remember that it is used by this
1938 MRI->setPhysRegUsed(VirtReg);
1942 // We want to process implicit virtual register uses first.
1943 if (MO.isImplicit())
1944 // If the virtual register is implicitly defined, emit a implicit_def
1945 // before so scavenger knows it's "defined".
1946 // FIXME: This is a horrible hack done the by register allocator to
1947 // remat a definition with virtual register operand.
1948 VirtUseOps.insert(VirtUseOps.begin(), i);
1950 VirtUseOps.push_back(i);
1953 // Process all of the spilled uses and all non spilled reg references.
1954 SmallVector<int, 2> PotentialDeadStoreSlots;
1955 KilledMIRegs.clear();
1956 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1957 unsigned i = VirtUseOps[j];
1958 unsigned VirtReg = MI.getOperand(i).getReg();
1959 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1960 "Not a virtual register?");
1962 unsigned SubIdx = MI.getOperand(i).getSubReg();
1963 if (VRM->isAssignedReg(VirtReg)) {
1964 // This virtual register was assigned a physreg!
1965 unsigned Phys = VRM->getPhys(VirtReg);
1966 MRI->setPhysRegUsed(Phys);
1967 if (MI.getOperand(i).isDef())
1968 ReusedOperands.markClobbered(Phys);
1969 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1970 if (VRM->isImplicitlyDefined(VirtReg))
1971 // FIXME: Is this needed?
1972 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1973 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1977 // This virtual register is now known to be a spilled value.
1978 if (!MI.getOperand(i).isUse())
1979 continue; // Handle defs in the loop below (handle use&def here though)
1981 bool AvoidReload = MI.getOperand(i).isUndef();
1982 // Check if it is defined by an implicit def. It should not be spilled.
1983 // Note, this is for correctness reason. e.g.
1984 // 8 %reg1024<def> = IMPLICIT_DEF
1985 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1986 // The live range [12, 14) are not part of the r1024 live interval since
1987 // it's defined by an implicit def. It will not conflicts with live
1988 // interval of r1025. Now suppose both registers are spilled, you can
1989 // easily see a situation where both registers are reloaded before
1990 // the INSERT_SUBREG and both target registers that would overlap.
1991 bool DoReMat = VRM->isReMaterialized(VirtReg);
1992 int SSorRMId = DoReMat
1993 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1994 int ReuseSlot = SSorRMId;
1996 // Check to see if this stack slot is available.
1997 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1999 // If this is a sub-register use, make sure the reuse register is in the
2000 // right register class. For example, for x86 not all of the 32-bit
2001 // registers have accessible sub-registers.
2002 // Similarly so for EXTRACT_SUBREG. Consider this:
2004 // MOV32_mr fi#1, EDI
2006 // = EXTRACT_SUBREG fi#1
2007 // fi#1 is available in EDI, but it cannot be reused because it's not in
2008 // the right register file.
2009 if (PhysReg && !AvoidReload && SubIdx) {
2010 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2011 if (!RC->contains(PhysReg))
2015 if (PhysReg && !AvoidReload) {
2016 // This spilled operand might be part of a two-address operand. If this
2017 // is the case, then changing it will necessarily require changing the
2018 // def part of the instruction as well. However, in some cases, we
2019 // aren't allowed to modify the reused register. If none of these cases
2021 bool CanReuse = true;
2022 bool isTied = MI.isRegTiedToDefOperand(i);
2024 // Okay, we have a two address operand. We can reuse this physreg as
2025 // long as we are allowed to clobber the value and there isn't an
2026 // earlier def that has already clobbered the physreg.
2027 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2028 Spills.canClobberPhysReg(PhysReg);
2030 // If this is an asm, and PhysReg is used elsewhere as an earlyclobber
2031 // operand, we can't also use it as an input. (Outputs always come
2032 // before inputs, so we can stop looking at i.)
2033 if (MI.isInlineAsm()) {
2034 for (unsigned k=0; k<i; ++k) {
2035 MachineOperand &MOk = MI.getOperand(k);
2036 if (MOk.isReg() && MOk.getReg()==PhysReg && MOk.isEarlyClobber()) {
2044 // If this stack slot value is already available, reuse it!
2045 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2046 DEBUG(dbgs() << "Reusing RM#"
2047 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2049 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2050 DEBUG(dbgs() << " from physreg "
2051 << TRI->getName(PhysReg) << " for vreg"
2052 << VirtReg <<" instead of reloading into physreg "
2053 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2054 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2055 MI.getOperand(i).setReg(RReg);
2056 MI.getOperand(i).setSubReg(0);
2058 // The only technical detail we have is that we don't know that
2059 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2060 // later in the instruction. In particular, consider 'op V1, V2'.
2061 // If V1 is available in physreg R0, we would choose to reuse it
2062 // here, instead of reloading it into the register the allocator
2063 // indicated (say R1). However, V2 might have to be reloaded
2064 // later, and it might indicate that it needs to live in R0. When
2065 // this occurs, we need to have information available that
2066 // indicates it is safe to use R1 for the reload instead of R0.
2068 // To further complicate matters, we might conflict with an alias,
2069 // or R0 and R1 might not be compatible with each other. In this
2070 // case, we actually insert a reload for V1 in R1, ensuring that
2071 // we can get at R0 or its alias.
2072 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2073 VRM->getPhys(VirtReg), VirtReg);
2075 // Only mark it clobbered if this is a use&def operand.
2076 ReusedOperands.markClobbered(PhysReg);
2079 if (MI.getOperand(i).isKill() &&
2080 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2082 // The store of this spilled value is potentially dead, but we
2083 // won't know for certain until we've confirmed that the re-use
2084 // above is valid, which means waiting until the other operands
2085 // are processed. For now we just track the spill slot, we'll
2086 // remove it after the other operands are processed if valid.
2088 PotentialDeadStoreSlots.push_back(ReuseSlot);
2091 // Mark is isKill if it's there no other uses of the same virtual
2092 // register and it's not a two-address operand. IsKill will be
2093 // unset if reg is reused.
2094 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2095 MI.getOperand(i).setIsKill();
2096 KilledMIRegs.insert(VirtReg);
2102 // Otherwise we have a situation where we have a two-address instruction
2103 // whose mod/ref operand needs to be reloaded. This reload is already
2104 // available in some register "PhysReg", but if we used PhysReg as the
2105 // operand to our 2-addr instruction, the instruction would modify
2106 // PhysReg. This isn't cool if something later uses PhysReg and expects
2107 // to get its initial value.
2109 // To avoid this problem, and to avoid doing a load right after a store,
2110 // we emit a copy from PhysReg into the designated register for this
2113 // This case also applies to an earlyclobber'd PhysReg.
2114 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2115 assert(DesignatedReg && "Must map virtreg to physreg!");
2117 // Note that, if we reused a register for a previous operand, the
2118 // register we want to reload into might not actually be
2119 // available. If this occurs, use the register indicated by the
2121 if (ReusedOperands.hasReuses())
2122 DesignatedReg = ReusedOperands.
2123 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2124 MaybeDeadStores, RegKills, KillOps, *VRM);
2126 // If the mapped designated register is actually the physreg we have
2127 // incoming, we don't need to inserted a dead copy.
2128 if (DesignatedReg == PhysReg) {
2129 // If this stack slot value is already available, reuse it!
2130 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2131 DEBUG(dbgs() << "Reusing RM#"
2132 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2134 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2135 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2136 << " for vreg" << VirtReg
2137 << " instead of reloading into same physreg.\n");
2138 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2139 MI.getOperand(i).setReg(RReg);
2140 MI.getOperand(i).setSubReg(0);
2141 ReusedOperands.markClobbered(RReg);
2146 MRI->setPhysRegUsed(DesignatedReg);
2147 ReusedOperands.markClobbered(DesignatedReg);
2149 // Back-schedule reloads and remats.
2150 MachineBasicBlock::iterator InsertLoc =
2151 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2153 MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2154 TII->get(TargetOpcode::COPY),
2155 DesignatedReg).addReg(PhysReg);
2156 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2157 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2159 // This invalidates DesignatedReg.
2160 Spills.ClobberPhysReg(DesignatedReg);
2162 Spills.addAvailable(ReuseSlot, DesignatedReg);
2164 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2165 MI.getOperand(i).setReg(RReg);
2166 MI.getOperand(i).setSubReg(0);
2167 DEBUG(dbgs() << '\t' << *prior(MII));
2172 // Otherwise, reload it and remember that we have it.
2173 PhysReg = VRM->getPhys(VirtReg);
2174 assert(PhysReg && "Must map virtreg to physreg!");
2176 // Note that, if we reused a register for a previous operand, the
2177 // register we want to reload into might not actually be
2178 // available. If this occurs, use the register indicated by the
2180 if (ReusedOperands.hasReuses())
2181 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2182 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2184 MRI->setPhysRegUsed(PhysReg);
2185 ReusedOperands.markClobbered(PhysReg);
2189 // Back-schedule reloads and remats.
2190 MachineBasicBlock::iterator InsertLoc =
2191 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2195 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2197 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2198 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2199 MachineInstr *LoadMI = prior(InsertLoc);
2200 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2202 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2204 // This invalidates PhysReg.
2205 Spills.ClobberPhysReg(PhysReg);
2207 // Any stores to this stack slot are not dead anymore.
2209 MaybeDeadStores[SSorRMId] = NULL;
2210 Spills.addAvailable(SSorRMId, PhysReg);
2211 // Assumes this is the last use. IsKill will be unset if reg is reused
2212 // unless it's a two-address operand.
2213 if (!MI.isRegTiedToDefOperand(i) &&
2214 KilledMIRegs.count(VirtReg) == 0) {
2215 MI.getOperand(i).setIsKill();
2216 KilledMIRegs.insert(VirtReg);
2219 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2220 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2222 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2223 MI.getOperand(i).setReg(RReg);
2224 MI.getOperand(i).setSubReg(0);
2227 // Ok - now we can remove stores that have been confirmed dead.
2228 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2229 // This was the last use and the spilled value is still available
2230 // for reuse. That means the spill was unnecessary!
2231 int PDSSlot = PotentialDeadStoreSlots[j];
2232 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2234 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2235 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2236 VRM->RemoveMachineInstrFromMaps(DeadStore);
2237 MBB->erase(DeadStore);
2238 MaybeDeadStores[PDSSlot] = NULL;
2244 DEBUG(dbgs() << '\t' << MI);
2247 // If we have folded references to memory operands, make sure we clear all
2248 // physical registers that may contain the value of the spilled virtual
2251 // Copy the folded virts to a small vector, we may change MI2VirtMap.
2252 SmallVector<std::pair<unsigned, VirtRegMap::ModRef>, 4> FoldedVirts;
2254 for (std::pair<VirtRegMap::MI2VirtMapTy::const_iterator,
2255 VirtRegMap::MI2VirtMapTy::const_iterator> FVRange =
2256 VRM->getFoldedVirts(&MI);
2257 FVRange.first != FVRange.second; ++FVRange.first)
2258 FoldedVirts.push_back(FVRange.first->second);
2260 SmallSet<int, 2> FoldedSS;
2261 for (unsigned FVI = 0, FVE = FoldedVirts.size(); FVI != FVE; ++FVI) {
2262 unsigned VirtReg = FoldedVirts[FVI].first;
2263 VirtRegMap::ModRef MR = FoldedVirts[FVI].second;
2264 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2266 int SS = VRM->getStackSlot(VirtReg);
2267 if (SS == VirtRegMap::NO_STACK_SLOT)
2269 FoldedSS.insert(SS);
2270 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2272 // If this folded instruction is just a use, check to see if it's a
2273 // straight load from the virt reg slot.
2274 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2276 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2277 if (DestReg && FrameIdx == SS) {
2278 // If this spill slot is available, turn it into a copy (or nothing)
2279 // instead of leaving it as a load!
2280 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2281 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2282 if (DestReg != InReg) {
2283 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2284 MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2285 TII->get(TargetOpcode::COPY))
2286 .addReg(DestReg, RegState::Define, DefMO->getSubReg())
2287 .addReg(InReg, RegState::Kill);
2288 // Revisit the copy so we make sure to notice the effects of the
2289 // operation on the destreg (either needing to RA it if it's
2290 // virtual or needing to clobber any values if it's physical).
2292 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2295 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2296 // Unset last kill since it's being reused.
2297 InvalidateKill(InReg, TRI, RegKills, KillOps);
2298 Spills.disallowClobberPhysReg(InReg);
2301 InvalidateKills(MI, TRI, RegKills, KillOps);
2302 VRM->RemoveMachineInstrFromMaps(&MI);
2305 goto ProcessNextInst;
2308 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2309 SmallVector<MachineInstr*, 4> NewMIs;
2311 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)){
2312 MBB->insert(MII, NewMIs[0]);
2313 InvalidateKills(MI, TRI, RegKills, KillOps);
2314 VRM->RemoveMachineInstrFromMaps(&MI);
2317 --NextMII; // backtrack to the unfolded instruction.
2319 goto ProcessNextInst;
2324 // If this reference is not a use, any previous store is now dead.
2325 // Otherwise, the store to this stack slot is not dead anymore.
2326 MachineInstr* DeadStore = MaybeDeadStores[SS];
2328 bool isDead = !(MR & VirtRegMap::isRef);
2329 MachineInstr *NewStore = NULL;
2330 if (MR & VirtRegMap::isModRef) {
2331 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2332 SmallVector<MachineInstr*, 4> NewMIs;
2333 // We can reuse this physreg as long as we are allowed to clobber
2334 // the value and there isn't an earlier def that has already clobbered
2337 !ReusedOperands.isClobbered(PhysReg) &&
2338 Spills.canClobberPhysReg(PhysReg) &&
2339 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2340 MachineOperand *KillOpnd =
2341 DeadStore->findRegisterUseOperand(PhysReg, true);
2342 // Note, if the store is storing a sub-register, it's possible the
2343 // super-register is needed below.
2344 if (KillOpnd && !KillOpnd->getSubReg() &&
2345 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2346 MBB->insert(MII, NewMIs[0]);
2347 NewStore = NewMIs[1];
2348 MBB->insert(MII, NewStore);
2349 VRM->addSpillSlotUse(SS, NewStore);
2350 InvalidateKills(MI, TRI, RegKills, KillOps);
2351 VRM->RemoveMachineInstrFromMaps(&MI);
2355 --NextMII; // backtrack to the unfolded instruction.
2363 if (isDead) { // Previous store is dead.
2364 // If we get here, the store is dead, nuke it now.
2365 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2366 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2367 VRM->RemoveMachineInstrFromMaps(DeadStore);
2368 MBB->erase(DeadStore);
2373 MaybeDeadStores[SS] = NULL;
2375 // Treat this store as a spill merged into a copy. That makes the
2376 // stack slot value available.
2377 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2378 goto ProcessNextInst;
2382 // If the spill slot value is available, and this is a new definition of
2383 // the value, the value is not available anymore.
2384 if (MR & VirtRegMap::isMod) {
2385 // Notice that the value in this stack slot has been modified.
2386 Spills.ModifyStackSlotOrReMat(SS);
2388 // If this is *just* a mod of the value, check to see if this is just a
2389 // store to the spill slot (i.e. the spill got merged into the copy). If
2390 // so, realize that the vreg is available now, and add the store to the
2391 // MaybeDeadStore info.
2393 if (!(MR & VirtRegMap::isRef)) {
2394 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2395 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2396 "Src hasn't been allocated yet?");
2398 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2399 Spills, RegKills, KillOps, TRI)) {
2400 NextMII = llvm::next(MII);
2402 goto ProcessNextInst;
2405 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2406 // this as a potentially dead store in case there is a subsequent
2407 // store into the stack slot without a read from it.
2408 MaybeDeadStores[StackSlot] = &MI;
2410 // If the stack slot value was previously available in some other
2411 // register, change it now. Otherwise, make the register
2412 // available in PhysReg.
2413 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2419 // Process all of the spilled defs.
2420 SpilledMIRegs.clear();
2421 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2422 MachineOperand &MO = MI.getOperand(i);
2423 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2426 unsigned VirtReg = MO.getReg();
2427 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2428 // Check to see if this is a noop copy. If so, eliminate the
2429 // instruction before considering the dest reg to be changed.
2430 // Also check if it's copying from an "undef", if so, we can't
2431 // eliminate this or else the undef marker is lost and it will
2432 // confuses the scavenger. This is extremely rare.
2433 if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2434 MI.getNumOperands() == 2) {
2436 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2437 SmallVector<unsigned, 2> KillRegs;
2438 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2439 if (MO.isDead() && !KillRegs.empty()) {
2440 // Source register or an implicit super/sub-register use is killed.
2441 assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2442 // Last def is now dead.
2443 TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2445 VRM->RemoveMachineInstrFromMaps(&MI);
2448 Spills.disallowClobberPhysReg(VirtReg);
2449 goto ProcessNextInst;
2452 // If it's not a no-op copy, it clobbers the value in the destreg.
2453 Spills.ClobberPhysReg(VirtReg);
2454 ReusedOperands.markClobbered(VirtReg);
2456 // Check to see if this instruction is a load from a stack slot into
2457 // a register. If so, this provides the stack slot value in the reg.
2459 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2460 assert(DestReg == VirtReg && "Unknown load situation!");
2462 // If it is a folded reference, then it's not safe to clobber.
2463 bool Folded = FoldedSS.count(FrameIdx);
2464 // Otherwise, if it wasn't available, remember that it is now!
2465 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2466 goto ProcessNextInst;
2472 unsigned SubIdx = MO.getSubReg();
2473 bool DoReMat = VRM->isReMaterialized(VirtReg);
2475 ReMatDefs.insert(&MI);
2477 // The only vregs left are stack slot definitions.
2478 int StackSlot = VRM->getStackSlot(VirtReg);
2479 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2481 // If this def is part of a two-address operand, make sure to execute
2482 // the store from the correct physical register.
2485 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2486 PhysReg = MI.getOperand(TiedOp).getReg();
2488 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2489 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2490 "Can't find corresponding super-register!");
2494 PhysReg = VRM->getPhys(VirtReg);
2495 if (ReusedOperands.isClobbered(PhysReg)) {
2496 // Another def has taken the assigned physreg. It must have been a
2497 // use&def which got it due to reuse. Undo the reuse!
2498 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2499 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2503 assert(PhysReg && "VR not assigned a physical register?");
2504 MRI->setPhysRegUsed(PhysReg);
2505 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2506 ReusedOperands.markClobbered(RReg);
2507 MI.getOperand(i).setReg(RReg);
2508 MI.getOperand(i).setSubReg(0);
2510 if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
2511 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2512 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2513 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2514 NextMII = llvm::next(MII);
2516 // Check to see if this is a noop copy. If so, eliminate the
2517 // instruction before considering the dest reg to be changed.
2518 if (MI.isIdentityCopy()) {
2520 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2521 InvalidateKills(MI, TRI, RegKills, KillOps);
2522 VRM->RemoveMachineInstrFromMaps(&MI);
2525 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2526 goto ProcessNextInst;
2531 // Delete dead instructions without side effects.
2532 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2533 InvalidateKills(MI, TRI, RegKills, KillOps);
2534 VRM->RemoveMachineInstrFromMaps(&MI);
2539 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2540 if (!Erased && !BackTracked) {
2541 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2542 UpdateKills(*II, TRI, RegKills, KillOps);
2549 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2550 switch (RewriterOpt) {
2551 default: llvm_unreachable("Unreachable!");
2553 return new LocalRewriter();
2555 return new TrivialRewriter();