1 //===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #define DEBUG_TYPE "virtregrewriter"
11 #include "VirtRegRewriter.h"
12 #include "llvm/Support/Compiler.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Target/TargetLowering.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/STLExtras.h"
22 STATISTIC(NumDSE , "Number of dead stores elided");
23 STATISTIC(NumDSS , "Number of dead spill slots removed");
24 STATISTIC(NumCommutes, "Number of instructions commuted");
25 STATISTIC(NumDRM , "Number of re-materializable defs elided");
26 STATISTIC(NumStores , "Number of stores added");
27 STATISTIC(NumPSpills , "Number of physical register spills");
28 STATISTIC(NumOmitted , "Number of reloads omited");
29 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
30 STATISTIC(NumCopified, "Number of available reloads turned into copies");
31 STATISTIC(NumReMats , "Number of re-materialization");
32 STATISTIC(NumLoads , "Number of loads added");
33 STATISTIC(NumReused , "Number of values reused");
34 STATISTIC(NumDCE , "Number of copies elided");
35 STATISTIC(NumSUnfold , "Number of stores unfolded");
36 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
39 enum RewriterName { local, trivial };
42 static cl::opt<RewriterName>
43 RewriterOpt("rewriter",
44 cl::desc("Rewriter to use: (default: local)"),
46 cl::values(clEnumVal(local, "local rewriter"),
47 clEnumVal(trivial, "trivial rewriter"),
52 ScheduleSpills("schedule-spills",
53 cl::desc("Schedule spill code"),
56 VirtRegRewriter::~VirtRegRewriter() {}
60 /// This class is intended for use with the new spilling framework only. It
61 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
63 struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
65 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
67 DEBUG(errs() << "********** REWRITE MACHINE CODE **********\n");
68 DEBUG(errs() << "********** Function: "
69 << MF.getFunction()->getName() << '\n');
70 DEBUG(errs() << "**** Machine Instrs"
71 << "(NOTE! Does not include spills and reloads!) ****\n");
74 MachineRegisterInfo *mri = &MF.getRegInfo();
78 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
79 liItr != liEnd; ++liItr) {
81 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
82 if (VRM.hasPhys(liItr->first)) {
83 unsigned preg = VRM.getPhys(liItr->first);
84 mri->replaceRegWith(liItr->first, preg);
85 mri->setPhysRegUsed(preg);
90 if (!liItr->second->empty()) {
91 mri->setPhysRegUsed(liItr->first);
97 DEBUG(errs() << "**** Post Machine Instrs ****\n");
107 // ************************************************************************ //
111 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
112 /// from top down, keep track of which spill slots or remat are available in
115 /// Note that not all physregs are created equal here. In particular, some
116 /// physregs are reloads that we are allowed to clobber or ignore at any time.
117 /// Other physregs are values that the register allocated program is using
118 /// that we cannot CHANGE, but we can read if we like. We keep track of this
119 /// on a per-stack-slot / remat id basis as the low bit in the value of the
120 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
121 /// this bit and addAvailable sets it if.
122 class VISIBILITY_HIDDEN AvailableSpills {
123 const TargetRegisterInfo *TRI;
124 const TargetInstrInfo *TII;
126 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
127 // or remat'ed virtual register values that are still available, due to
128 // being loaded or stored to, but not invalidated yet.
129 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
131 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
132 // indicating which stack slot values are currently held by a physreg. This
133 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
134 // physreg is modified.
135 std::multimap<unsigned, int> PhysRegsAvailable;
137 void disallowClobberPhysRegOnly(unsigned PhysReg);
139 void ClobberPhysRegOnly(unsigned PhysReg);
141 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
142 : TRI(tri), TII(tii) {
145 /// clear - Reset the state.
147 SpillSlotsOrReMatsAvailable.clear();
148 PhysRegsAvailable.clear();
151 const TargetRegisterInfo *getRegInfo() const { return TRI; }
153 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
154 /// available in a physical register, return that PhysReg, otherwise
156 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
157 std::map<int, unsigned>::const_iterator I =
158 SpillSlotsOrReMatsAvailable.find(Slot);
159 if (I != SpillSlotsOrReMatsAvailable.end()) {
160 return I->second >> 1; // Remove the CanClobber bit.
165 /// addAvailable - Mark that the specified stack slot / remat is available
166 /// in the specified physreg. If CanClobber is true, the physreg can be
167 /// modified at any time without changing the semantics of the program.
168 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
169 // If this stack slot is thought to be available in some other physreg,
170 // remove its record.
171 ModifyStackSlotOrReMat(SlotOrReMat);
173 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
174 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
175 (unsigned)CanClobber;
177 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
178 DEBUG(errs() << "Remembering RM#"
179 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
181 DEBUG(errs() << "Remembering SS#" << SlotOrReMat);
182 DEBUG(errs() << " in physreg " << TRI->getName(Reg) << "\n");
185 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
186 /// the value of the specified stackslot register if it desires. The
187 /// specified stack slot must be available in a physreg for this query to
189 bool canClobberPhysRegForSS(int SlotOrReMat) const {
190 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
191 "Value not available!");
192 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
195 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
196 /// physical register where values for some stack slot(s) might be
198 bool canClobberPhysReg(unsigned PhysReg) const {
199 std::multimap<unsigned, int>::const_iterator I =
200 PhysRegsAvailable.lower_bound(PhysReg);
201 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
202 int SlotOrReMat = I->second;
204 if (!canClobberPhysRegForSS(SlotOrReMat))
210 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
211 /// stackslot register. The register is still available but is no longer
212 /// allowed to be modifed.
213 void disallowClobberPhysReg(unsigned PhysReg);
215 /// ClobberPhysReg - This is called when the specified physreg changes
216 /// value. We use this to invalidate any info about stuff that lives in
217 /// it and any of its aliases.
218 void ClobberPhysReg(unsigned PhysReg);
220 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
221 /// slot changes. This removes information about which register the
222 /// previous value for this slot lives in (as the previous value is dead
224 void ModifyStackSlotOrReMat(int SlotOrReMat);
226 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
227 /// into the specified MBB. Add available physical registers as potential
228 /// live-in's. If they are reused in the MBB, they will be added to the
229 /// live-in set to make register scavenger and post-allocation scheduler.
230 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
231 std::vector<MachineOperand*> &KillOps);
236 // ************************************************************************ //
238 // Given a location where a reload of a spilled register or a remat of
239 // a constant is to be inserted, attempt to find a safe location to
240 // insert the load at an earlier point in the basic-block, to hide
241 // latency of the load and to avoid address-generation interlock
243 static MachineBasicBlock::iterator
244 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
245 MachineBasicBlock::iterator const Begin,
247 const TargetRegisterInfo *TRI,
250 const TargetInstrInfo *TII,
251 const MachineFunction &MF)
256 // Spill backscheduling is of primary interest to addresses, so
257 // don't do anything if the register isn't in the register class
258 // used for pointers.
260 const TargetLowering *TL = MF.getTarget().getTargetLowering();
262 if (!TL->isTypeLegal(TL->getPointerTy()))
263 // Believe it or not, this is true on PIC16.
266 const TargetRegisterClass *ptrRegClass =
267 TL->getRegClassFor(TL->getPointerTy());
268 if (!ptrRegClass->contains(PhysReg))
271 // Scan upwards through the preceding instructions. If an instruction doesn't
272 // reference the stack slot or the register we're loading, we can
273 // backschedule the reload up past it.
274 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
275 while (NewInsertLoc != Begin) {
276 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
277 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
278 MachineOperand &Op = Prev->getOperand(i);
279 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
282 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
283 Prev->findRegisterDefOperand(PhysReg))
285 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
286 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
287 Prev->findRegisterDefOperand(*Alias))
293 // If we made it to the beginning of the block, turn around and move back
294 // down just past any existing reloads. They're likely to be reloads/remats
295 // for instructions earlier than what our current reload/remat is for, so
296 // they should be scheduled earlier.
297 if (NewInsertLoc == Begin) {
299 while (InsertLoc != NewInsertLoc &&
300 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
301 TII->isTriviallyReMaterializable(NewInsertLoc)))
310 // ReusedOp - For each reused operand, we keep track of a bit of information,
311 // in case we need to rollback upon processing a new operand. See comments
314 // The MachineInstr operand that reused an available value.
317 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
318 unsigned StackSlotOrReMat;
320 // PhysRegReused - The physical register the value was available in.
321 unsigned PhysRegReused;
323 // AssignedPhysReg - The physreg that was assigned for use by the reload.
324 unsigned AssignedPhysReg;
326 // VirtReg - The virtual register itself.
329 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
331 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
332 AssignedPhysReg(apr), VirtReg(vreg) {}
335 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
336 /// is reused instead of reloaded.
337 class VISIBILITY_HIDDEN ReuseInfo {
339 std::vector<ReusedOp> Reuses;
340 BitVector PhysRegsClobbered;
342 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
343 PhysRegsClobbered.resize(tri->getNumRegs());
346 bool hasReuses() const {
347 return !Reuses.empty();
350 /// addReuse - If we choose to reuse a virtual register that is already
351 /// available instead of reloading it, remember that we did so.
352 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
353 unsigned PhysRegReused, unsigned AssignedPhysReg,
355 // If the reload is to the assigned register anyway, no undo will be
357 if (PhysRegReused == AssignedPhysReg) return;
359 // Otherwise, remember this.
360 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
361 AssignedPhysReg, VirtReg));
364 void markClobbered(unsigned PhysReg) {
365 PhysRegsClobbered.set(PhysReg);
368 bool isClobbered(unsigned PhysReg) const {
369 return PhysRegsClobbered.test(PhysReg);
372 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
373 /// is some other operand that is using the specified register, either pick
374 /// a new register to use, or evict the previous reload and use this reg.
375 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
376 MachineFunction &MF, MachineInstr *MI,
377 AvailableSpills &Spills,
378 std::vector<MachineInstr*> &MaybeDeadStores,
379 SmallSet<unsigned, 8> &Rejected,
381 std::vector<MachineOperand*> &KillOps,
384 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
385 /// 'Rejected' set to remember which registers have been considered and
386 /// rejected for the reload. This avoids infinite looping in case like
389 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
390 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
392 /// sees r1 is taken by t2, tries t2's reload register r0
393 /// sees r0 is taken by t3, tries t3's reload register r1
394 /// sees r1 is taken by t2, tries t2's reload register r0 ...
395 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
396 AvailableSpills &Spills,
397 std::vector<MachineInstr*> &MaybeDeadStores,
399 std::vector<MachineOperand*> &KillOps,
401 SmallSet<unsigned, 8> Rejected;
402 MachineFunction &MF = *MI->getParent()->getParent();
403 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
404 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
405 Rejected, RegKills, KillOps, VRM);
411 // ****************** //
412 // Utility Functions //
413 // ****************** //
415 /// findSinglePredSuccessor - Return via reference a vector of machine basic
416 /// blocks each of which is a successor of the specified BB and has no other
418 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
419 SmallVectorImpl<MachineBasicBlock *> &Succs) {
420 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
421 SE = MBB->succ_end(); SI != SE; ++SI) {
422 MachineBasicBlock *SuccMBB = *SI;
423 if (SuccMBB->pred_size() == 1)
424 Succs.push_back(SuccMBB);
428 /// InvalidateKill - Invalidate register kill information for a specific
429 /// register. This also unsets the kills marker on the last kill operand.
430 static void InvalidateKill(unsigned Reg,
431 const TargetRegisterInfo* TRI,
433 std::vector<MachineOperand*> &KillOps) {
435 KillOps[Reg]->setIsKill(false);
436 // KillOps[Reg] might be a def of a super-register.
437 unsigned KReg = KillOps[Reg]->getReg();
438 KillOps[KReg] = NULL;
439 RegKills.reset(KReg);
440 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
442 KillOps[*SR]->setIsKill(false);
450 /// InvalidateKills - MI is going to be deleted. If any of its operands are
451 /// marked kill, then invalidate the information.
452 static void InvalidateKills(MachineInstr &MI,
453 const TargetRegisterInfo* TRI,
455 std::vector<MachineOperand*> &KillOps,
456 SmallVector<unsigned, 2> *KillRegs = NULL) {
457 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
458 MachineOperand &MO = MI.getOperand(i);
459 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
461 unsigned Reg = MO.getReg();
462 if (TargetRegisterInfo::isVirtualRegister(Reg))
465 KillRegs->push_back(Reg);
466 assert(Reg < KillOps.size());
467 if (KillOps[Reg] == &MO) {
470 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
480 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
481 /// (since it's spill instruction is removed), mark it isDead. Also checks if
482 /// the def MI has other definition operands that are not dead. Returns it by
484 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
485 MachineInstr &NewDef, unsigned Reg,
487 // Due to remat, it's possible this reg isn't being reused. That is,
488 // the def of this reg (by prev MI) is now dead.
489 MachineInstr *DefMI = I;
490 MachineOperand *DefOp = NULL;
491 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
492 MachineOperand &MO = DefMI->getOperand(i);
493 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
495 if (MO.getReg() == Reg)
497 else if (!MO.isDead())
503 bool FoundUse = false, Done = false;
504 MachineBasicBlock::iterator E = &NewDef;
506 for (; !Done && I != E; ++I) {
507 MachineInstr *NMI = I;
508 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
509 MachineOperand &MO = NMI->getOperand(j);
510 if (!MO.isReg() || MO.getReg() != Reg)
514 Done = true; // Stop after scanning all the operands of this MI.
525 /// UpdateKills - Track and update kill info. If a MI reads a register that is
526 /// marked kill, then it must be due to register reuse. Transfer the kill info
528 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
530 std::vector<MachineOperand*> &KillOps) {
531 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
532 MachineOperand &MO = MI.getOperand(i);
533 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
535 unsigned Reg = MO.getReg();
539 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
540 // That can't be right. Register is killed but not re-defined and it's
541 // being reused. Let's fix that.
542 KillOps[Reg]->setIsKill(false);
543 // KillOps[Reg] might be a def of a super-register.
544 unsigned KReg = KillOps[Reg]->getReg();
545 KillOps[KReg] = NULL;
546 RegKills.reset(KReg);
548 // Must be a def of a super-register. Its other sub-regsters are no
549 // longer killed as well.
550 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
555 if (!MI.isRegTiedToDefOperand(i))
556 // Unless it's a two-address operand, this is the new kill.
562 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
569 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
570 const MachineOperand &MO = MI.getOperand(i);
571 if (!MO.isReg() || !MO.isDef())
573 unsigned Reg = MO.getReg();
576 // It also defines (or partially define) aliases.
577 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
584 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
586 static void ReMaterialize(MachineBasicBlock &MBB,
587 MachineBasicBlock::iterator &MII,
588 unsigned DestReg, unsigned Reg,
589 const TargetInstrInfo *TII,
590 const TargetRegisterInfo *TRI,
592 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
594 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
595 assert(TID.getNumDefs() == 1 &&
596 "Don't know how to remat instructions that define > 1 values!");
598 TII->reMaterialize(MBB, MII, DestReg,
599 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
600 MachineInstr *NewMI = prior(MII);
601 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
602 MachineOperand &MO = NewMI->getOperand(i);
603 if (!MO.isReg() || MO.getReg() == 0)
605 unsigned VirtReg = MO.getReg();
606 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
609 unsigned SubIdx = MO.getSubReg();
610 unsigned Phys = VRM.getPhys(VirtReg);
612 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
619 /// findSuperReg - Find the SubReg's super-register of given register class
620 /// where its SubIdx sub-register is SubReg.
621 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
622 unsigned SubIdx, const TargetRegisterInfo *TRI) {
623 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
626 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
632 // ******************************** //
633 // Available Spills Implementation //
634 // ******************************** //
636 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
637 /// stackslot register. The register is still available but is no longer
638 /// allowed to be modifed.
639 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
640 std::multimap<unsigned, int>::iterator I =
641 PhysRegsAvailable.lower_bound(PhysReg);
642 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
643 int SlotOrReMat = I->second;
645 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
646 "Bidirectional map mismatch!");
647 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
648 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
649 << " copied, it is available for use but can no longer be modified\n");
653 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
654 /// stackslot register and its aliases. The register and its aliases may
655 /// still available but is no longer allowed to be modifed.
656 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
657 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
658 disallowClobberPhysRegOnly(*AS);
659 disallowClobberPhysRegOnly(PhysReg);
662 /// ClobberPhysRegOnly - This is called when the specified physreg changes
663 /// value. We use this to invalidate any info about stuff we thing lives in it.
664 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
665 std::multimap<unsigned, int>::iterator I =
666 PhysRegsAvailable.lower_bound(PhysReg);
667 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
668 int SlotOrReMat = I->second;
669 PhysRegsAvailable.erase(I++);
670 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
671 "Bidirectional map mismatch!");
672 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
673 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
674 << " clobbered, invalidating ");
675 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
676 DEBUG(errs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
678 DEBUG(errs() << "SS#" << SlotOrReMat << "\n");
682 /// ClobberPhysReg - This is called when the specified physreg changes
683 /// value. We use this to invalidate any info about stuff we thing lives in
684 /// it and any of its aliases.
685 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
686 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
687 ClobberPhysRegOnly(*AS);
688 ClobberPhysRegOnly(PhysReg);
691 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
692 /// into the specified MBB. Add available physical registers as potential
693 /// live-in's. If they are reused in the MBB, they will be added to the
694 /// live-in set to make register scavenger and post-allocation scheduler.
695 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
697 std::vector<MachineOperand*> &KillOps) {
698 std::set<unsigned> NotAvailable;
699 for (std::multimap<unsigned, int>::iterator
700 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
702 unsigned Reg = I->first;
703 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
704 // FIXME: A temporary workaround. We can't reuse available value if it's
705 // not safe to move the def of the virtual register's class. e.g.
706 // X86::RFP* register classes. Do not add it as a live-in.
707 if (!TII->isSafeToMoveRegClassDefs(RC))
708 // This is no longer available.
709 NotAvailable.insert(Reg);
712 InvalidateKill(Reg, TRI, RegKills, KillOps);
715 // Skip over the same register.
716 std::multimap<unsigned, int>::iterator NI = next(I);
717 while (NI != E && NI->first == Reg) {
723 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
724 E = NotAvailable.end(); I != E; ++I) {
726 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
728 ClobberPhysReg(*SubRegs);
732 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
733 /// slot changes. This removes information about which register the previous
734 /// value for this slot lives in (as the previous value is dead now).
735 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
736 std::map<int, unsigned>::iterator It =
737 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
738 if (It == SpillSlotsOrReMatsAvailable.end()) return;
739 unsigned Reg = It->second >> 1;
740 SpillSlotsOrReMatsAvailable.erase(It);
742 // This register may hold the value of multiple stack slots, only remove this
743 // stack slot from the set of values the register contains.
744 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
746 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
747 "Map inverse broken!");
748 if (I->second == SlotOrReMat) break;
750 PhysRegsAvailable.erase(I);
753 // ************************** //
754 // Reuse Info Implementation //
755 // ************************** //
757 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
758 /// is some other operand that is using the specified register, either pick
759 /// a new register to use, or evict the previous reload and use this reg.
760 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
763 MachineInstr *MI, AvailableSpills &Spills,
764 std::vector<MachineInstr*> &MaybeDeadStores,
765 SmallSet<unsigned, 8> &Rejected,
767 std::vector<MachineOperand*> &KillOps,
769 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
770 const TargetRegisterInfo *TRI = Spills.getRegInfo();
772 if (Reuses.empty()) return PhysReg; // This is most often empty.
774 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
775 ReusedOp &Op = Reuses[ro];
776 // If we find some other reuse that was supposed to use this register
777 // exactly for its reload, we can change this reload to use ITS reload
778 // register. That is, unless its reload register has already been
779 // considered and subsequently rejected because it has also been reused
780 // by another operand.
781 if (Op.PhysRegReused == PhysReg &&
782 Rejected.count(Op.AssignedPhysReg) == 0 &&
783 RC->contains(Op.AssignedPhysReg)) {
784 // Yup, use the reload register that we didn't use before.
785 unsigned NewReg = Op.AssignedPhysReg;
786 Rejected.insert(PhysReg);
787 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
788 RegKills, KillOps, VRM);
790 // Otherwise, we might also have a problem if a previously reused
791 // value aliases the new register. If so, codegen the previous reload
793 unsigned PRRU = Op.PhysRegReused;
794 if (TRI->areAliases(PRRU, PhysReg)) {
795 // Okay, we found out that an alias of a reused register
796 // was used. This isn't good because it means we have
797 // to undo a previous reuse.
798 MachineBasicBlock *MBB = MI->getParent();
799 const TargetRegisterClass *AliasRC =
800 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
802 // Copy Op out of the vector and remove it, we're going to insert an
803 // explicit load for it.
805 Reuses.erase(Reuses.begin()+ro);
807 // Ok, we're going to try to reload the assigned physreg into the
808 // slot that we were supposed to in the first place. However, that
809 // register could hold a reuse. Check to see if it conflicts or
810 // would prefer us to use a different register.
811 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
812 MF, MI, Spills, MaybeDeadStores,
813 Rejected, RegKills, KillOps, VRM);
815 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
816 int SSorRMId = DoReMat
817 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
819 // Back-schedule reloads and remats.
820 MachineBasicBlock::iterator InsertLoc =
821 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
822 DoReMat, SSorRMId, TII, MF);
825 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
828 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
829 NewOp.StackSlotOrReMat, AliasRC);
830 MachineInstr *LoadMI = prior(InsertLoc);
831 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
832 // Any stores to this stack slot are not dead anymore.
833 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
836 Spills.ClobberPhysReg(NewPhysReg);
837 Spills.ClobberPhysReg(NewOp.PhysRegReused);
839 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
840 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
841 MI->getOperand(NewOp.Operand).setReg(RReg);
842 MI->getOperand(NewOp.Operand).setSubReg(0);
844 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
845 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
846 DEBUG(errs() << '\t' << *prior(InsertLoc));
848 DEBUG(errs() << "Reuse undone!\n");
851 // Finally, PhysReg is now available, go ahead and use it.
859 // ************************************************************************ //
861 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
862 /// stack slot mod/ref. It also checks if it's possible to unfold the
863 /// instruction by having it define a specified physical register instead.
864 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
865 const TargetInstrInfo *TII,
866 const TargetRegisterInfo *TRI,
868 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
872 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
873 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
874 unsigned VirtReg = I->second.first;
875 VirtRegMap::ModRef MR = I->second.second;
876 if (MR & VirtRegMap::isModRef)
877 if (VRM.getStackSlot(VirtReg) == SS) {
878 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
885 // Does the instruction uses a register that overlaps the scratch register?
886 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
887 MachineOperand &MO = MI.getOperand(i);
888 if (!MO.isReg() || MO.getReg() == 0)
890 unsigned Reg = MO.getReg();
891 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
892 if (!VRM.hasPhys(Reg))
894 Reg = VRM.getPhys(Reg);
896 if (TRI->regsOverlap(PhysReg, Reg))
902 /// FindFreeRegister - Find a free register of a given register class by looking
903 /// at (at most) the last two machine instructions.
904 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
905 MachineBasicBlock &MBB,
906 const TargetRegisterClass *RC,
907 const TargetRegisterInfo *TRI,
908 BitVector &AllocatableRegs) {
909 BitVector Defs(TRI->getNumRegs());
910 BitVector Uses(TRI->getNumRegs());
911 SmallVector<unsigned, 4> LocalUses;
912 SmallVector<unsigned, 4> Kills;
914 // Take a look at 2 instructions at most.
915 for (unsigned Count = 0; Count < 2; ++Count) {
916 if (MII == MBB.begin())
918 MachineInstr *PrevMI = prior(MII);
919 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
920 MachineOperand &MO = PrevMI->getOperand(i);
921 if (!MO.isReg() || MO.getReg() == 0)
923 unsigned Reg = MO.getReg();
926 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
929 LocalUses.push_back(Reg);
930 if (MO.isKill() && AllocatableRegs[Reg])
931 Kills.push_back(Reg);
935 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
936 unsigned Kill = Kills[i];
937 if (!Defs[Kill] && !Uses[Kill] &&
938 TRI->getPhysicalRegisterRegClass(Kill) == RC)
941 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
942 unsigned Reg = LocalUses[i];
944 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
955 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
956 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
957 MachineOperand &MO = MI->getOperand(i);
958 if (MO.isReg() && MO.getReg() == VirtReg)
965 bool operator()(const std::pair<MachineInstr*, int> &A,
966 const std::pair<MachineInstr*, int> &B) {
967 return A.second < B.second;
972 // ***************************** //
973 // Local Spiller Implementation //
974 // ***************************** //
978 class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
979 MachineRegisterInfo *RegInfo;
980 const TargetRegisterInfo *TRI;
981 const TargetInstrInfo *TII;
982 BitVector AllocatableRegs;
983 DenseMap<MachineInstr*, unsigned> DistanceMap;
986 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
987 LiveIntervals* LIs) {
988 RegInfo = &MF.getRegInfo();
989 TRI = MF.getTarget().getRegisterInfo();
990 TII = MF.getTarget().getInstrInfo();
991 AllocatableRegs = TRI->getAllocatableSet(MF);
992 DEBUG(errs() << "\n**** Local spiller rewriting function '"
993 << MF.getFunction()->getName() << "':\n");
994 DEBUG(errs() << "**** Machine Instrs (NOTE! Does not include spills and"
995 " reloads!) ****\n");
998 // Spills - Keep track of which spilled values are available in physregs
999 // so that we can choose to reuse the physregs instead of emitting
1000 // reloads. This is usually refreshed per basic block.
1001 AvailableSpills Spills(TRI, TII);
1003 // Keep track of kill information.
1004 BitVector RegKills(TRI->getNumRegs());
1005 std::vector<MachineOperand*> KillOps;
1006 KillOps.resize(TRI->getNumRegs(), NULL);
1008 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1009 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1010 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1012 // Traverse the basic blocks depth first.
1013 MachineBasicBlock *Entry = MF.begin();
1014 SmallPtrSet<MachineBasicBlock*,16> Visited;
1015 for (df_ext_iterator<MachineBasicBlock*,
1016 SmallPtrSet<MachineBasicBlock*,16> >
1017 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1019 MachineBasicBlock *MBB = *DFI;
1020 if (!EarlyVisited.count(MBB))
1021 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1023 // If this MBB is the only predecessor of a successor. Keep the
1024 // availability information and visit it next.
1026 // Keep visiting single predecessor successor as long as possible.
1027 SinglePredSuccs.clear();
1028 findSinglePredSuccessor(MBB, SinglePredSuccs);
1029 if (SinglePredSuccs.empty())
1032 // FIXME: More than one successors, each of which has MBB has
1033 // the only predecessor.
1034 MBB = SinglePredSuccs[0];
1035 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1036 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1037 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1042 // Clear the availability info.
1046 DEBUG(errs() << "**** Post Machine Instrs ****\n");
1049 // Mark unused spill slots.
1050 MachineFrameInfo *MFI = MF.getFrameInfo();
1051 int SS = VRM.getLowSpillSlot();
1052 if (SS != VirtRegMap::NO_STACK_SLOT)
1053 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1054 if (!VRM.isSpillSlotUsed(SS)) {
1055 MFI->RemoveStackObject(SS);
1064 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1065 /// a scratch register is available.
1066 /// xorq %r12<kill>, %r13
1067 /// addq %rax, -184(%rbp)
1068 /// addq %r13, -184(%rbp)
1070 /// xorq %r12<kill>, %r13
1071 /// movq -184(%rbp), %r12
1074 /// movq %r12, -184(%rbp)
1075 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1076 MachineBasicBlock &MBB,
1077 MachineBasicBlock::iterator &MII,
1078 std::vector<MachineInstr*> &MaybeDeadStores,
1079 AvailableSpills &Spills,
1080 BitVector &RegKills,
1081 std::vector<MachineOperand*> &KillOps,
1084 MachineBasicBlock::iterator NextMII = next(MII);
1085 if (NextMII == MBB.end())
1088 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1091 // Now let's see if the last couple of instructions happens to have freed up
1093 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1094 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1098 MachineFunction &MF = *MBB.getParent();
1099 TRI = MF.getTarget().getRegisterInfo();
1100 MachineInstr &MI = *MII;
1101 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1104 // If the next instruction also folds the same SS modref and can be unfoled,
1105 // then it's worthwhile to issue a load from SS into the free register and
1106 // then unfold these instructions.
1107 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1110 // Back-schedule reloads and remats.
1111 MachineBasicBlock::iterator InsertLoc =
1112 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
1114 // Load from SS to the spare physical register.
1115 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1116 // This invalidates Phys.
1117 Spills.ClobberPhysReg(PhysReg);
1118 // Remember it's available.
1119 Spills.addAvailable(SS, PhysReg);
1120 MaybeDeadStores[SS] = NULL;
1122 // Unfold current MI.
1123 SmallVector<MachineInstr*, 4> NewMIs;
1124 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1125 llvm_unreachable("Unable unfold the load / store folding instruction!");
1126 assert(NewMIs.size() == 1);
1127 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1128 VRM.transferRestorePts(&MI, NewMIs[0]);
1129 MII = MBB.insert(MII, NewMIs[0]);
1130 InvalidateKills(MI, TRI, RegKills, KillOps);
1131 VRM.RemoveMachineInstrFromMaps(&MI);
1135 // Unfold next instructions that fold the same SS.
1137 MachineInstr &NextMI = *NextMII;
1138 NextMII = next(NextMII);
1140 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1141 llvm_unreachable("Unable unfold the load / store folding instruction!");
1142 assert(NewMIs.size() == 1);
1143 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1144 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1145 MBB.insert(NextMII, NewMIs[0]);
1146 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1147 VRM.RemoveMachineInstrFromMaps(&NextMI);
1150 if (NextMII == MBB.end())
1152 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1154 // Store the value back into SS.
1155 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1156 MachineInstr *StoreMI = prior(NextMII);
1157 VRM.addSpillSlotUse(SS, StoreMI);
1158 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1163 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1164 /// instruction. e.g.
1166 /// movl %eax, -32(%ebp)
1167 /// movl -36(%ebp), %eax
1168 /// orl %eax, -32(%ebp)
1171 /// orl -36(%ebp), %eax
1172 /// mov %eax, -32(%ebp)
1173 /// This enables unfolding optimization for a subsequent instruction which will
1174 /// also eliminate the newly introduced store instruction.
1175 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1176 MachineBasicBlock::iterator &MII,
1177 std::vector<MachineInstr*> &MaybeDeadStores,
1178 AvailableSpills &Spills,
1179 BitVector &RegKills,
1180 std::vector<MachineOperand*> &KillOps,
1182 MachineFunction &MF = *MBB.getParent();
1183 MachineInstr &MI = *MII;
1184 unsigned UnfoldedOpc = 0;
1185 unsigned UnfoldPR = 0;
1186 unsigned UnfoldVR = 0;
1187 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1188 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1189 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1190 // Only transform a MI that folds a single register.
1193 UnfoldVR = I->second.first;
1194 VirtRegMap::ModRef MR = I->second.second;
1195 // MI2VirtMap be can updated which invalidate the iterator.
1196 // Increment the iterator first.
1198 if (VRM.isAssignedReg(UnfoldVR))
1200 // If this reference is not a use, any previous store is now dead.
1201 // Otherwise, the store to this stack slot is not dead anymore.
1202 FoldedSS = VRM.getStackSlot(UnfoldVR);
1203 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1204 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1205 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1206 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1209 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1218 // Look for other unfolding opportunities.
1219 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1220 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1223 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1224 MachineOperand &MO = MI.getOperand(i);
1225 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1227 unsigned VirtReg = MO.getReg();
1228 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1230 if (VRM.isAssignedReg(VirtReg)) {
1231 unsigned PhysReg = VRM.getPhys(VirtReg);
1232 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1234 } else if (VRM.isReMaterialized(VirtReg))
1236 int SS = VRM.getStackSlot(VirtReg);
1237 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1239 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1243 if (VRM.hasPhys(VirtReg)) {
1244 PhysReg = VRM.getPhys(VirtReg);
1245 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1249 // Ok, we'll need to reload the value into a register which makes
1250 // it impossible to perform the store unfolding optimization later.
1251 // Let's see if it is possible to fold the load if the store is
1252 // unfolded. This allows us to perform the store unfolding
1254 SmallVector<MachineInstr*, 4> NewMIs;
1255 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1256 assert(NewMIs.size() == 1);
1257 MachineInstr *NewMI = NewMIs.back();
1259 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1261 SmallVector<unsigned, 1> Ops;
1263 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1265 VRM.addSpillSlotUse(SS, FoldedMI);
1266 if (!VRM.hasPhys(UnfoldVR))
1267 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1268 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1269 MII = MBB.insert(MII, FoldedMI);
1270 InvalidateKills(MI, TRI, RegKills, KillOps);
1271 VRM.RemoveMachineInstrFromMaps(&MI);
1273 MF.DeleteMachineInstr(NewMI);
1276 MF.DeleteMachineInstr(NewMI);
1283 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1284 /// where SrcReg is r1 and it is tied to r0. Return true if after
1285 /// commuting this instruction it will be r0 = op r2, r1.
1286 static bool CommuteChangesDestination(MachineInstr *DefMI,
1287 const TargetInstrDesc &TID,
1289 const TargetInstrInfo *TII,
1291 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1293 if (!DefMI->getOperand(1).isReg() ||
1294 DefMI->getOperand(1).getReg() != SrcReg)
1297 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1299 unsigned SrcIdx1, SrcIdx2;
1300 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1302 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1309 /// CommuteToFoldReload -
1312 /// r1 = op r1, r2<kill>
1315 /// If op is commutable and r2 is killed, then we can xform these to
1316 /// r2 = op r2, fi#1
1318 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1319 MachineBasicBlock::iterator &MII,
1320 unsigned VirtReg, unsigned SrcReg, int SS,
1321 AvailableSpills &Spills,
1322 BitVector &RegKills,
1323 std::vector<MachineOperand*> &KillOps,
1324 const TargetRegisterInfo *TRI,
1326 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1329 MachineFunction &MF = *MBB.getParent();
1330 MachineInstr &MI = *MII;
1331 MachineBasicBlock::iterator DefMII = prior(MII);
1332 MachineInstr *DefMI = DefMII;
1333 const TargetInstrDesc &TID = DefMI->getDesc();
1335 if (DefMII != MBB.begin() &&
1336 TID.isCommutable() &&
1337 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1338 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1339 unsigned NewReg = NewDstMO.getReg();
1340 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1342 MachineInstr *ReloadMI = prior(DefMII);
1344 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1345 if (DestReg != SrcReg || FrameIdx != SS)
1347 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1351 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1353 assert(DefMI->getOperand(DefIdx).isReg() &&
1354 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1356 // Now commute def instruction.
1357 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1360 SmallVector<unsigned, 1> Ops;
1361 Ops.push_back(NewDstIdx);
1362 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1363 // Not needed since foldMemoryOperand returns new MI.
1364 MF.DeleteMachineInstr(CommutedMI);
1368 VRM.addSpillSlotUse(SS, FoldedMI);
1369 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1370 // Insert new def MI and spill MI.
1371 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1372 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1374 MachineInstr *StoreMI = MII;
1375 VRM.addSpillSlotUse(SS, StoreMI);
1376 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1377 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1379 // Delete all 3 old instructions.
1380 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1381 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1382 MBB.erase(ReloadMI);
1383 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1384 VRM.RemoveMachineInstrFromMaps(DefMI);
1386 InvalidateKills(MI, TRI, RegKills, KillOps);
1387 VRM.RemoveMachineInstrFromMaps(&MI);
1390 // If NewReg was previously holding value of some SS, it's now clobbered.
1391 // This has to be done now because it's a physical register. When this
1392 // instruction is re-visited, it's ignored.
1393 Spills.ClobberPhysReg(NewReg);
1402 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1403 /// the last store to the same slot is now dead. If so, remove the last store.
1404 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1405 MachineBasicBlock::iterator &MII,
1406 int Idx, unsigned PhysReg, int StackSlot,
1407 const TargetRegisterClass *RC,
1408 bool isAvailable, MachineInstr *&LastStore,
1409 AvailableSpills &Spills,
1410 SmallSet<MachineInstr*, 4> &ReMatDefs,
1411 BitVector &RegKills,
1412 std::vector<MachineOperand*> &KillOps,
1415 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1416 MachineInstr *StoreMI = next(MII);
1417 VRM.addSpillSlotUse(StackSlot, StoreMI);
1418 DEBUG(errs() << "Store:\t" << *StoreMI);
1420 // If there is a dead store to this stack slot, nuke it now.
1422 DEBUG(errs() << "Removed dead store:\t" << *LastStore);
1424 SmallVector<unsigned, 2> KillRegs;
1425 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1426 MachineBasicBlock::iterator PrevMII = LastStore;
1427 bool CheckDef = PrevMII != MBB.begin();
1430 VRM.RemoveMachineInstrFromMaps(LastStore);
1431 MBB.erase(LastStore);
1433 // Look at defs of killed registers on the store. Mark the defs
1434 // as dead since the store has been deleted and they aren't
1436 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1437 bool HasOtherDef = false;
1438 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1439 MachineInstr *DeadDef = PrevMII;
1440 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1441 // FIXME: This assumes a remat def does not have side effects.
1442 VRM.RemoveMachineInstrFromMaps(DeadDef);
1451 LastStore = next(MII);
1453 // If the stack slot value was previously available in some other
1454 // register, change it now. Otherwise, make the register available,
1456 Spills.ModifyStackSlotOrReMat(StackSlot);
1457 Spills.ClobberPhysReg(PhysReg);
1458 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1462 /// TransferDeadness - A identity copy definition is dead and it's being
1463 /// removed. Find the last def or use and mark it as dead / kill.
1464 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1465 unsigned Reg, BitVector &RegKills,
1466 std::vector<MachineOperand*> &KillOps,
1468 SmallPtrSet<MachineInstr*, 4> Seens;
1469 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1470 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1471 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1472 MachineInstr *UDMI = &*RI;
1473 if (UDMI->getParent() != MBB)
1475 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1476 if (DI == DistanceMap.end() || DI->second > CurDist)
1478 if (Seens.insert(UDMI))
1479 Refs.push_back(std::make_pair(UDMI, DI->second));
1484 std::sort(Refs.begin(), Refs.end(), RefSorter());
1486 while (!Refs.empty()) {
1487 MachineInstr *LastUDMI = Refs.back().first;
1490 MachineOperand *LastUD = NULL;
1491 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1492 MachineOperand &MO = LastUDMI->getOperand(i);
1493 if (!MO.isReg() || MO.getReg() != Reg)
1495 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1497 if (LastUDMI->isRegTiedToDefOperand(i))
1500 if (LastUD->isDef()) {
1501 // If the instruction has no side effect, delete it and propagate
1502 // backward further. Otherwise, mark is dead and we are done.
1503 if (!TII->isDeadInstruction(LastUDMI)) {
1504 LastUD->setIsDead();
1507 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1508 MBB->erase(LastUDMI);
1510 LastUD->setIsKill();
1512 KillOps[Reg] = LastUD;
1518 /// rewriteMBB - Keep track of which spills are available even after the
1519 /// register allocator is done with them. If possible, avid reloading vregs.
1520 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1522 AvailableSpills &Spills, BitVector &RegKills,
1523 std::vector<MachineOperand*> &KillOps) {
1525 DEBUG(errs() << "\n**** Local spiller rewriting MBB '"
1526 << MBB.getBasicBlock()->getName() << "':\n");
1528 MachineFunction &MF = *MBB.getParent();
1530 // MaybeDeadStores - When we need to write a value back into a stack slot,
1531 // keep track of the inserted store. If the stack slot value is never read
1532 // (because the value was used from some available register, for example), and
1533 // subsequently stored to, the original store is dead. This map keeps track
1534 // of inserted stores that are not used. If we see a subsequent store to the
1535 // same stack slot, the original store is deleted.
1536 std::vector<MachineInstr*> MaybeDeadStores;
1537 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1539 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1540 SmallSet<MachineInstr*, 4> ReMatDefs;
1543 SmallSet<unsigned, 2> KilledMIRegs;
1546 KillOps.resize(TRI->getNumRegs(), NULL);
1549 DistanceMap.clear();
1550 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1552 MachineBasicBlock::iterator NextMII = next(MII);
1554 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1555 bool Erased = false;
1556 bool BackTracked = false;
1557 if (OptimizeByUnfold(MBB, MII,
1558 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1559 NextMII = next(MII);
1561 MachineInstr &MI = *MII;
1563 if (VRM.hasEmergencySpills(&MI)) {
1564 // Spill physical register(s) in the rare case the allocator has run out
1565 // of registers to allocate.
1566 SmallSet<int, 4> UsedSS;
1567 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1568 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1569 unsigned PhysReg = EmSpills[i];
1570 const TargetRegisterClass *RC =
1571 TRI->getPhysicalRegisterRegClass(PhysReg);
1572 assert(RC && "Unable to determine register class!");
1573 int SS = VRM.getEmergencySpillSlot(RC);
1574 if (UsedSS.count(SS))
1575 llvm_unreachable("Need to spill more than one physical registers!");
1577 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1578 MachineInstr *StoreMI = prior(MII);
1579 VRM.addSpillSlotUse(SS, StoreMI);
1581 // Back-schedule reloads and remats.
1582 MachineBasicBlock::iterator InsertLoc =
1583 ComputeReloadLoc(next(MII), MBB.begin(), PhysReg, TRI, false,
1586 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1588 MachineInstr *LoadMI = prior(InsertLoc);
1589 VRM.addSpillSlotUse(SS, LoadMI);
1591 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1593 NextMII = next(MII);
1596 // Insert restores here if asked to.
1597 if (VRM.isRestorePt(&MI)) {
1598 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1599 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1600 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1601 if (!VRM.getPreSplitReg(VirtReg))
1602 continue; // Split interval spilled again.
1603 unsigned Phys = VRM.getPhys(VirtReg);
1604 RegInfo->setPhysRegUsed(Phys);
1606 // Check if the value being restored if available. If so, it must be
1607 // from a predecessor BB that fallthrough into this BB. We do not
1613 // ... # r1 not clobbered
1616 bool DoReMat = VRM.isReMaterialized(VirtReg);
1617 int SSorRMId = DoReMat
1618 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1619 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1620 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1621 if (InReg == Phys) {
1622 // If the value is already available in the expected register, save
1623 // a reload / remat.
1625 DEBUG(errs() << "Reusing RM#"
1626 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1628 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1629 DEBUG(errs() << " from physreg "
1630 << TRI->getName(InReg) << " for vreg"
1631 << VirtReg <<" instead of reloading into physreg "
1632 << TRI->getName(Phys) << '\n');
1635 } else if (InReg && InReg != Phys) {
1637 DEBUG(errs() << "Reusing RM#"
1638 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1640 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1641 DEBUG(errs() << " from physreg "
1642 << TRI->getName(InReg) << " for vreg"
1643 << VirtReg <<" by copying it into physreg "
1644 << TRI->getName(Phys) << '\n');
1646 // If the reloaded / remat value is available in another register,
1647 // copy it to the desired register.
1649 // Back-schedule reloads and remats.
1650 MachineBasicBlock::iterator InsertLoc =
1651 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1654 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
1656 // This invalidates Phys.
1657 Spills.ClobberPhysReg(Phys);
1658 // Remember it's available.
1659 Spills.addAvailable(SSorRMId, Phys);
1662 MachineInstr *CopyMI = prior(InsertLoc);
1663 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1664 KillOpnd->setIsKill();
1665 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1667 DEBUG(errs() << '\t' << *CopyMI);
1672 // Back-schedule reloads and remats.
1673 MachineBasicBlock::iterator InsertLoc =
1674 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1677 if (VRM.isReMaterialized(VirtReg)) {
1678 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
1680 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1681 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1682 MachineInstr *LoadMI = prior(InsertLoc);
1683 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1685 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1688 // This invalidates Phys.
1689 Spills.ClobberPhysReg(Phys);
1690 // Remember it's available.
1691 Spills.addAvailable(SSorRMId, Phys);
1693 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1694 DEBUG(errs() << '\t' << *prior(MII));
1698 // Insert spills here if asked to.
1699 if (VRM.isSpillPt(&MI)) {
1700 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1701 VRM.getSpillPtSpills(&MI);
1702 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1703 unsigned VirtReg = SpillRegs[i].first;
1704 bool isKill = SpillRegs[i].second;
1705 if (!VRM.getPreSplitReg(VirtReg))
1706 continue; // Split interval spilled again.
1707 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1708 unsigned Phys = VRM.getPhys(VirtReg);
1709 int StackSlot = VRM.getStackSlot(VirtReg);
1710 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1711 MachineInstr *StoreMI = next(MII);
1712 VRM.addSpillSlotUse(StackSlot, StoreMI);
1713 DEBUG(errs() << "Store:\t" << *StoreMI);
1714 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1716 NextMII = next(MII);
1719 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1721 ReuseInfo ReusedOperands(MI, TRI);
1722 SmallVector<unsigned, 4> VirtUseOps;
1723 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1724 MachineOperand &MO = MI.getOperand(i);
1725 if (!MO.isReg() || MO.getReg() == 0)
1726 continue; // Ignore non-register operands.
1728 unsigned VirtReg = MO.getReg();
1729 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1730 // Ignore physregs for spilling, but remember that it is used by this
1732 RegInfo->setPhysRegUsed(VirtReg);
1736 // We want to process implicit virtual register uses first.
1737 if (MO.isImplicit())
1738 // If the virtual register is implicitly defined, emit a implicit_def
1739 // before so scavenger knows it's "defined".
1740 // FIXME: This is a horrible hack done the by register allocator to
1741 // remat a definition with virtual register operand.
1742 VirtUseOps.insert(VirtUseOps.begin(), i);
1744 VirtUseOps.push_back(i);
1747 // Process all of the spilled uses and all non spilled reg references.
1748 SmallVector<int, 2> PotentialDeadStoreSlots;
1749 KilledMIRegs.clear();
1750 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1751 unsigned i = VirtUseOps[j];
1752 MachineOperand &MO = MI.getOperand(i);
1753 unsigned VirtReg = MO.getReg();
1754 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1755 "Not a virtual register?");
1757 unsigned SubIdx = MO.getSubReg();
1758 if (VRM.isAssignedReg(VirtReg)) {
1759 // This virtual register was assigned a physreg!
1760 unsigned Phys = VRM.getPhys(VirtReg);
1761 RegInfo->setPhysRegUsed(Phys);
1763 ReusedOperands.markClobbered(Phys);
1764 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1765 MI.getOperand(i).setReg(RReg);
1766 MI.getOperand(i).setSubReg(0);
1767 if (VRM.isImplicitlyDefined(VirtReg))
1768 // FIXME: Is this needed?
1769 BuildMI(MBB, &MI, MI.getDebugLoc(),
1770 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1774 // This virtual register is now known to be a spilled value.
1776 continue; // Handle defs in the loop below (handle use&def here though)
1778 bool AvoidReload = MO.isUndef();
1779 // Check if it is defined by an implicit def. It should not be spilled.
1780 // Note, this is for correctness reason. e.g.
1781 // 8 %reg1024<def> = IMPLICIT_DEF
1782 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1783 // The live range [12, 14) are not part of the r1024 live interval since
1784 // it's defined by an implicit def. It will not conflicts with live
1785 // interval of r1025. Now suppose both registers are spilled, you can
1786 // easily see a situation where both registers are reloaded before
1787 // the INSERT_SUBREG and both target registers that would overlap.
1788 bool DoReMat = VRM.isReMaterialized(VirtReg);
1789 int SSorRMId = DoReMat
1790 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1791 int ReuseSlot = SSorRMId;
1793 // Check to see if this stack slot is available.
1794 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1796 // If this is a sub-register use, make sure the reuse register is in the
1797 // right register class. For example, for x86 not all of the 32-bit
1798 // registers have accessible sub-registers.
1799 // Similarly so for EXTRACT_SUBREG. Consider this:
1801 // MOV32_mr fi#1, EDI
1803 // = EXTRACT_SUBREG fi#1
1804 // fi#1 is available in EDI, but it cannot be reused because it's not in
1805 // the right register file.
1806 if (PhysReg && !AvoidReload &&
1807 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1808 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1809 if (!RC->contains(PhysReg))
1813 if (PhysReg && !AvoidReload) {
1814 // This spilled operand might be part of a two-address operand. If this
1815 // is the case, then changing it will necessarily require changing the
1816 // def part of the instruction as well. However, in some cases, we
1817 // aren't allowed to modify the reused register. If none of these cases
1819 bool CanReuse = true;
1820 bool isTied = MI.isRegTiedToDefOperand(i);
1822 // Okay, we have a two address operand. We can reuse this physreg as
1823 // long as we are allowed to clobber the value and there isn't an
1824 // earlier def that has already clobbered the physreg.
1825 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1826 Spills.canClobberPhysReg(PhysReg);
1830 // If this stack slot value is already available, reuse it!
1831 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1832 DEBUG(errs() << "Reusing RM#"
1833 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1835 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1836 DEBUG(errs() << " from physreg "
1837 << TRI->getName(PhysReg) << " for vreg"
1838 << VirtReg <<" instead of reloading into physreg "
1839 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
1840 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1841 MI.getOperand(i).setReg(RReg);
1842 MI.getOperand(i).setSubReg(0);
1844 // The only technical detail we have is that we don't know that
1845 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1846 // later in the instruction. In particular, consider 'op V1, V2'.
1847 // If V1 is available in physreg R0, we would choose to reuse it
1848 // here, instead of reloading it into the register the allocator
1849 // indicated (say R1). However, V2 might have to be reloaded
1850 // later, and it might indicate that it needs to live in R0. When
1851 // this occurs, we need to have information available that
1852 // indicates it is safe to use R1 for the reload instead of R0.
1854 // To further complicate matters, we might conflict with an alias,
1855 // or R0 and R1 might not be compatible with each other. In this
1856 // case, we actually insert a reload for V1 in R1, ensuring that
1857 // we can get at R0 or its alias.
1858 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1859 VRM.getPhys(VirtReg), VirtReg);
1861 // Only mark it clobbered if this is a use&def operand.
1862 ReusedOperands.markClobbered(PhysReg);
1865 if (MI.getOperand(i).isKill() &&
1866 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1868 // The store of this spilled value is potentially dead, but we
1869 // won't know for certain until we've confirmed that the re-use
1870 // above is valid, which means waiting until the other operands
1871 // are processed. For now we just track the spill slot, we'll
1872 // remove it after the other operands are processed if valid.
1874 PotentialDeadStoreSlots.push_back(ReuseSlot);
1877 // Mark is isKill if it's there no other uses of the same virtual
1878 // register and it's not a two-address operand. IsKill will be
1879 // unset if reg is reused.
1880 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1881 MI.getOperand(i).setIsKill();
1882 KilledMIRegs.insert(VirtReg);
1888 // Otherwise we have a situation where we have a two-address instruction
1889 // whose mod/ref operand needs to be reloaded. This reload is already
1890 // available in some register "PhysReg", but if we used PhysReg as the
1891 // operand to our 2-addr instruction, the instruction would modify
1892 // PhysReg. This isn't cool if something later uses PhysReg and expects
1893 // to get its initial value.
1895 // To avoid this problem, and to avoid doing a load right after a store,
1896 // we emit a copy from PhysReg into the designated register for this
1898 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1899 assert(DesignatedReg && "Must map virtreg to physreg!");
1901 // Note that, if we reused a register for a previous operand, the
1902 // register we want to reload into might not actually be
1903 // available. If this occurs, use the register indicated by the
1905 if (ReusedOperands.hasReuses())
1906 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1908 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1910 // If the mapped designated register is actually the physreg we have
1911 // incoming, we don't need to inserted a dead copy.
1912 if (DesignatedReg == PhysReg) {
1913 // If this stack slot value is already available, reuse it!
1914 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1915 DEBUG(errs() << "Reusing RM#"
1916 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1918 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1919 DEBUG(errs() << " from physreg " << TRI->getName(PhysReg)
1920 << " for vreg" << VirtReg
1921 << " instead of reloading into same physreg.\n");
1922 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1923 MI.getOperand(i).setReg(RReg);
1924 MI.getOperand(i).setSubReg(0);
1925 ReusedOperands.markClobbered(RReg);
1930 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1931 RegInfo->setPhysRegUsed(DesignatedReg);
1932 ReusedOperands.markClobbered(DesignatedReg);
1934 // Back-schedule reloads and remats.
1935 MachineBasicBlock::iterator InsertLoc =
1936 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
1939 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
1941 MachineInstr *CopyMI = prior(InsertLoc);
1942 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1944 // This invalidates DesignatedReg.
1945 Spills.ClobberPhysReg(DesignatedReg);
1947 Spills.addAvailable(ReuseSlot, DesignatedReg);
1949 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1950 MI.getOperand(i).setReg(RReg);
1951 MI.getOperand(i).setSubReg(0);
1952 DEBUG(errs() << '\t' << *prior(MII));
1957 // Otherwise, reload it and remember that we have it.
1958 PhysReg = VRM.getPhys(VirtReg);
1959 assert(PhysReg && "Must map virtreg to physreg!");
1961 // Note that, if we reused a register for a previous operand, the
1962 // register we want to reload into might not actually be
1963 // available. If this occurs, use the register indicated by the
1965 if (ReusedOperands.hasReuses())
1966 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
1967 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1969 RegInfo->setPhysRegUsed(PhysReg);
1970 ReusedOperands.markClobbered(PhysReg);
1974 // Back-schedule reloads and remats.
1975 MachineBasicBlock::iterator InsertLoc =
1976 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
1980 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
1982 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1983 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
1984 MachineInstr *LoadMI = prior(InsertLoc);
1985 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1987 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1989 // This invalidates PhysReg.
1990 Spills.ClobberPhysReg(PhysReg);
1992 // Any stores to this stack slot are not dead anymore.
1994 MaybeDeadStores[SSorRMId] = NULL;
1995 Spills.addAvailable(SSorRMId, PhysReg);
1996 // Assumes this is the last use. IsKill will be unset if reg is reused
1997 // unless it's a two-address operand.
1998 if (!MI.isRegTiedToDefOperand(i) &&
1999 KilledMIRegs.count(VirtReg) == 0) {
2000 MI.getOperand(i).setIsKill();
2001 KilledMIRegs.insert(VirtReg);
2004 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2005 DEBUG(errs() << '\t' << *prior(InsertLoc));
2007 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2008 MI.getOperand(i).setReg(RReg);
2009 MI.getOperand(i).setSubReg(0);
2012 // Ok - now we can remove stores that have been confirmed dead.
2013 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2014 // This was the last use and the spilled value is still available
2015 // for reuse. That means the spill was unnecessary!
2016 int PDSSlot = PotentialDeadStoreSlots[j];
2017 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2019 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2020 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2021 VRM.RemoveMachineInstrFromMaps(DeadStore);
2022 MBB.erase(DeadStore);
2023 MaybeDeadStores[PDSSlot] = NULL;
2029 DEBUG(errs() << '\t' << MI);
2032 // If we have folded references to memory operands, make sure we clear all
2033 // physical registers that may contain the value of the spilled virtual
2035 SmallSet<int, 2> FoldedSS;
2036 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2037 unsigned VirtReg = I->second.first;
2038 VirtRegMap::ModRef MR = I->second.second;
2039 DEBUG(errs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2041 // MI2VirtMap be can updated which invalidate the iterator.
2042 // Increment the iterator first.
2044 int SS = VRM.getStackSlot(VirtReg);
2045 if (SS == VirtRegMap::NO_STACK_SLOT)
2047 FoldedSS.insert(SS);
2048 DEBUG(errs() << " - StackSlot: " << SS << "\n");
2050 // If this folded instruction is just a use, check to see if it's a
2051 // straight load from the virt reg slot.
2052 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2054 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2055 if (DestReg && FrameIdx == SS) {
2056 // If this spill slot is available, turn it into a copy (or nothing)
2057 // instead of leaving it as a load!
2058 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2059 DEBUG(errs() << "Promoted Load To Copy: " << MI);
2060 if (DestReg != InReg) {
2061 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2062 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2063 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2064 unsigned SubIdx = DefMO->getSubReg();
2065 // Revisit the copy so we make sure to notice the effects of the
2066 // operation on the destreg (either needing to RA it if it's
2067 // virtual or needing to clobber any values if it's physical).
2069 --NextMII; // backtrack to the copy.
2070 // Propagate the sub-register index over.
2072 DefMO = NextMII->findRegisterDefOperand(DestReg);
2073 DefMO->setSubReg(SubIdx);
2077 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2078 KillOpnd->setIsKill();
2082 DEBUG(errs() << "Removing now-noop copy: " << MI);
2083 // Unset last kill since it's being reused.
2084 InvalidateKill(InReg, TRI, RegKills, KillOps);
2085 Spills.disallowClobberPhysReg(InReg);
2088 InvalidateKills(MI, TRI, RegKills, KillOps);
2089 VRM.RemoveMachineInstrFromMaps(&MI);
2092 goto ProcessNextInst;
2095 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2096 SmallVector<MachineInstr*, 4> NewMIs;
2098 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2099 MBB.insert(MII, NewMIs[0]);
2100 InvalidateKills(MI, TRI, RegKills, KillOps);
2101 VRM.RemoveMachineInstrFromMaps(&MI);
2104 --NextMII; // backtrack to the unfolded instruction.
2106 goto ProcessNextInst;
2111 // If this reference is not a use, any previous store is now dead.
2112 // Otherwise, the store to this stack slot is not dead anymore.
2113 MachineInstr* DeadStore = MaybeDeadStores[SS];
2115 bool isDead = !(MR & VirtRegMap::isRef);
2116 MachineInstr *NewStore = NULL;
2117 if (MR & VirtRegMap::isModRef) {
2118 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2119 SmallVector<MachineInstr*, 4> NewMIs;
2120 // We can reuse this physreg as long as we are allowed to clobber
2121 // the value and there isn't an earlier def that has already clobbered
2124 !ReusedOperands.isClobbered(PhysReg) &&
2125 Spills.canClobberPhysReg(PhysReg) &&
2126 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2127 MachineOperand *KillOpnd =
2128 DeadStore->findRegisterUseOperand(PhysReg, true);
2129 // Note, if the store is storing a sub-register, it's possible the
2130 // super-register is needed below.
2131 if (KillOpnd && !KillOpnd->getSubReg() &&
2132 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2133 MBB.insert(MII, NewMIs[0]);
2134 NewStore = NewMIs[1];
2135 MBB.insert(MII, NewStore);
2136 VRM.addSpillSlotUse(SS, NewStore);
2137 InvalidateKills(MI, TRI, RegKills, KillOps);
2138 VRM.RemoveMachineInstrFromMaps(&MI);
2142 --NextMII; // backtrack to the unfolded instruction.
2150 if (isDead) { // Previous store is dead.
2151 // If we get here, the store is dead, nuke it now.
2152 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2153 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2154 VRM.RemoveMachineInstrFromMaps(DeadStore);
2155 MBB.erase(DeadStore);
2160 MaybeDeadStores[SS] = NULL;
2162 // Treat this store as a spill merged into a copy. That makes the
2163 // stack slot value available.
2164 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2165 goto ProcessNextInst;
2169 // If the spill slot value is available, and this is a new definition of
2170 // the value, the value is not available anymore.
2171 if (MR & VirtRegMap::isMod) {
2172 // Notice that the value in this stack slot has been modified.
2173 Spills.ModifyStackSlotOrReMat(SS);
2175 // If this is *just* a mod of the value, check to see if this is just a
2176 // store to the spill slot (i.e. the spill got merged into the copy). If
2177 // so, realize that the vreg is available now, and add the store to the
2178 // MaybeDeadStore info.
2180 if (!(MR & VirtRegMap::isRef)) {
2181 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2182 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2183 "Src hasn't been allocated yet?");
2185 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2186 Spills, RegKills, KillOps, TRI, VRM)) {
2187 NextMII = next(MII);
2189 goto ProcessNextInst;
2192 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2193 // this as a potentially dead store in case there is a subsequent
2194 // store into the stack slot without a read from it.
2195 MaybeDeadStores[StackSlot] = &MI;
2197 // If the stack slot value was previously available in some other
2198 // register, change it now. Otherwise, make the register
2199 // available in PhysReg.
2200 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2206 // Process all of the spilled defs.
2207 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2208 MachineOperand &MO = MI.getOperand(i);
2209 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2212 unsigned VirtReg = MO.getReg();
2213 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2214 // Check to see if this is a noop copy. If so, eliminate the
2215 // instruction before considering the dest reg to be changed.
2216 // Also check if it's copying from an "undef", if so, we can't
2217 // eliminate this or else the undef marker is lost and it will
2218 // confuses the scavenger. This is extremely rare.
2219 unsigned Src, Dst, SrcSR, DstSR;
2220 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2221 !MI.findRegisterUseOperand(Src)->isUndef()) {
2223 DEBUG(errs() << "Removing now-noop copy: " << MI);
2224 SmallVector<unsigned, 2> KillRegs;
2225 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2226 if (MO.isDead() && !KillRegs.empty()) {
2227 // Source register or an implicit super/sub-register use is killed.
2228 assert(KillRegs[0] == Dst ||
2229 TRI->isSubRegister(KillRegs[0], Dst) ||
2230 TRI->isSuperRegister(KillRegs[0], Dst));
2231 // Last def is now dead.
2232 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2234 VRM.RemoveMachineInstrFromMaps(&MI);
2237 Spills.disallowClobberPhysReg(VirtReg);
2238 goto ProcessNextInst;
2241 // If it's not a no-op copy, it clobbers the value in the destreg.
2242 Spills.ClobberPhysReg(VirtReg);
2243 ReusedOperands.markClobbered(VirtReg);
2245 // Check to see if this instruction is a load from a stack slot into
2246 // a register. If so, this provides the stack slot value in the reg.
2248 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2249 assert(DestReg == VirtReg && "Unknown load situation!");
2251 // If it is a folded reference, then it's not safe to clobber.
2252 bool Folded = FoldedSS.count(FrameIdx);
2253 // Otherwise, if it wasn't available, remember that it is now!
2254 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2255 goto ProcessNextInst;
2261 unsigned SubIdx = MO.getSubReg();
2262 bool DoReMat = VRM.isReMaterialized(VirtReg);
2264 ReMatDefs.insert(&MI);
2266 // The only vregs left are stack slot definitions.
2267 int StackSlot = VRM.getStackSlot(VirtReg);
2268 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2270 // If this def is part of a two-address operand, make sure to execute
2271 // the store from the correct physical register.
2274 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2275 PhysReg = MI.getOperand(TiedOp).getReg();
2277 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2278 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2279 "Can't find corresponding super-register!");
2283 PhysReg = VRM.getPhys(VirtReg);
2284 if (ReusedOperands.isClobbered(PhysReg)) {
2285 // Another def has taken the assigned physreg. It must have been a
2286 // use&def which got it due to reuse. Undo the reuse!
2287 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2288 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2292 assert(PhysReg && "VR not assigned a physical register?");
2293 RegInfo->setPhysRegUsed(PhysReg);
2294 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2295 ReusedOperands.markClobbered(RReg);
2296 MI.getOperand(i).setReg(RReg);
2297 MI.getOperand(i).setSubReg(0);
2300 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2301 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2302 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2303 NextMII = next(MII);
2305 // Check to see if this is a noop copy. If so, eliminate the
2306 // instruction before considering the dest reg to be changed.
2308 unsigned Src, Dst, SrcSR, DstSR;
2309 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2311 DEBUG(errs() << "Removing now-noop copy: " << MI);
2312 InvalidateKills(MI, TRI, RegKills, KillOps);
2313 VRM.RemoveMachineInstrFromMaps(&MI);
2316 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2317 goto ProcessNextInst;
2323 // Delete dead instructions without side effects.
2324 if (!Erased && !BackTracked && TII->isDeadInstruction(&MI)) {
2325 InvalidateKills(MI, TRI, RegKills, KillOps);
2326 VRM.RemoveMachineInstrFromMaps(&MI);
2331 DistanceMap.insert(std::make_pair(&MI, Dist++));
2332 if (!Erased && !BackTracked) {
2333 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2334 UpdateKills(*II, TRI, RegKills, KillOps);
2345 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2346 switch (RewriterOpt) {
2347 default: llvm_unreachable("Unreachable!");
2349 return new LocalRewriter();
2351 return new TrivialRewriter();