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/Function.h"
13 #include "llvm/CodeGen/MachineFrameInfo.h"
14 #include "llvm/CodeGen/MachineInstrBuilder.h"
15 #include "llvm/CodeGen/MachineRegisterInfo.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/raw_ostream.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/Statistic.h"
27 STATISTIC(NumDSE , "Number of dead stores elided");
28 STATISTIC(NumDSS , "Number of dead spill slots removed");
29 STATISTIC(NumCommutes, "Number of instructions commuted");
30 STATISTIC(NumDRM , "Number of re-materializable defs elided");
31 STATISTIC(NumStores , "Number of stores added");
32 STATISTIC(NumPSpills , "Number of physical register spills");
33 STATISTIC(NumOmitted , "Number of reloads omited");
34 STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
35 STATISTIC(NumCopified, "Number of available reloads turned into copies");
36 STATISTIC(NumReMats , "Number of re-materialization");
37 STATISTIC(NumLoads , "Number of loads added");
38 STATISTIC(NumReused , "Number of values reused");
39 STATISTIC(NumDCE , "Number of copies elided");
40 STATISTIC(NumSUnfold , "Number of stores unfolded");
41 STATISTIC(NumModRefUnfold, "Number of modref unfolded");
44 enum RewriterName { local, trivial };
47 static cl::opt<RewriterName>
48 RewriterOpt("rewriter",
49 cl::desc("Rewriter to use: (default: local)"),
51 cl::values(clEnumVal(local, "local rewriter"),
52 clEnumVal(trivial, "trivial rewriter"),
57 ScheduleSpills("schedule-spills",
58 cl::desc("Schedule spill code"),
61 VirtRegRewriter::~VirtRegRewriter() {}
65 /// This class is intended for use with the new spilling framework only. It
66 /// rewrites vreg def/uses to use the assigned preg, but does not insert any
68 struct TrivialRewriter : public VirtRegRewriter {
70 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
72 DEBUG(errs() << "********** REWRITE MACHINE CODE **********\n");
73 DEBUG(errs() << "********** Function: "
74 << MF.getFunction()->getName() << '\n');
75 DEBUG(errs() << "**** Machine Instrs"
76 << "(NOTE! Does not include spills and reloads!) ****\n");
79 MachineRegisterInfo *mri = &MF.getRegInfo();
83 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
84 liItr != liEnd; ++liItr) {
86 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
87 if (VRM.hasPhys(liItr->first)) {
88 unsigned preg = VRM.getPhys(liItr->first);
89 mri->replaceRegWith(liItr->first, preg);
90 mri->setPhysRegUsed(preg);
95 if (!liItr->second->empty()) {
96 mri->setPhysRegUsed(liItr->first);
102 DEBUG(errs() << "**** Post Machine Instrs ****\n");
112 // ************************************************************************ //
116 /// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
117 /// from top down, keep track of which spill slots or remat are available in
120 /// Note that not all physregs are created equal here. In particular, some
121 /// physregs are reloads that we are allowed to clobber or ignore at any time.
122 /// Other physregs are values that the register allocated program is using
123 /// that we cannot CHANGE, but we can read if we like. We keep track of this
124 /// on a per-stack-slot / remat id basis as the low bit in the value of the
125 /// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
126 /// this bit and addAvailable sets it if.
127 class AvailableSpills {
128 const TargetRegisterInfo *TRI;
129 const TargetInstrInfo *TII;
131 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
132 // or remat'ed virtual register values that are still available, due to
133 // being loaded or stored to, but not invalidated yet.
134 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
136 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
137 // indicating which stack slot values are currently held by a physreg. This
138 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
139 // physreg is modified.
140 std::multimap<unsigned, int> PhysRegsAvailable;
142 void disallowClobberPhysRegOnly(unsigned PhysReg);
144 void ClobberPhysRegOnly(unsigned PhysReg);
146 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
147 : TRI(tri), TII(tii) {
150 /// clear - Reset the state.
152 SpillSlotsOrReMatsAvailable.clear();
153 PhysRegsAvailable.clear();
156 const TargetRegisterInfo *getRegInfo() const { return TRI; }
158 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
159 /// available in a physical register, return that PhysReg, otherwise
161 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
162 std::map<int, unsigned>::const_iterator I =
163 SpillSlotsOrReMatsAvailable.find(Slot);
164 if (I != SpillSlotsOrReMatsAvailable.end()) {
165 return I->second >> 1; // Remove the CanClobber bit.
170 /// addAvailable - Mark that the specified stack slot / remat is available
171 /// in the specified physreg. If CanClobber is true, the physreg can be
172 /// modified at any time without changing the semantics of the program.
173 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
174 // If this stack slot is thought to be available in some other physreg,
175 // remove its record.
176 ModifyStackSlotOrReMat(SlotOrReMat);
178 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
179 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
180 (unsigned)CanClobber;
182 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
183 DEBUG(errs() << "Remembering RM#"
184 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
186 DEBUG(errs() << "Remembering SS#" << SlotOrReMat);
187 DEBUG(errs() << " in physreg " << TRI->getName(Reg) << "\n");
190 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
191 /// the value of the specified stackslot register if it desires. The
192 /// specified stack slot must be available in a physreg for this query to
194 bool canClobberPhysRegForSS(int SlotOrReMat) const {
195 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
196 "Value not available!");
197 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
200 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
201 /// physical register where values for some stack slot(s) might be
203 bool canClobberPhysReg(unsigned PhysReg) const {
204 std::multimap<unsigned, int>::const_iterator I =
205 PhysRegsAvailable.lower_bound(PhysReg);
206 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
207 int SlotOrReMat = I->second;
209 if (!canClobberPhysRegForSS(SlotOrReMat))
215 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
216 /// stackslot register. The register is still available but is no longer
217 /// allowed to be modifed.
218 void disallowClobberPhysReg(unsigned PhysReg);
220 /// ClobberPhysReg - This is called when the specified physreg changes
221 /// value. We use this to invalidate any info about stuff that lives in
222 /// it and any of its aliases.
223 void ClobberPhysReg(unsigned PhysReg);
225 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
226 /// slot changes. This removes information about which register the
227 /// previous value for this slot lives in (as the previous value is dead
229 void ModifyStackSlotOrReMat(int SlotOrReMat);
231 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
232 /// into the specified MBB. Add available physical registers as potential
233 /// live-in's. If they are reused in the MBB, they will be added to the
234 /// live-in set to make register scavenger and post-allocation scheduler.
235 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
236 std::vector<MachineOperand*> &KillOps);
241 // ************************************************************************ //
243 // Given a location where a reload of a spilled register or a remat of
244 // a constant is to be inserted, attempt to find a safe location to
245 // insert the load at an earlier point in the basic-block, to hide
246 // latency of the load and to avoid address-generation interlock
248 static MachineBasicBlock::iterator
249 ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
250 MachineBasicBlock::iterator const Begin,
252 const TargetRegisterInfo *TRI,
255 const TargetInstrInfo *TII,
256 const MachineFunction &MF)
261 // Spill backscheduling is of primary interest to addresses, so
262 // don't do anything if the register isn't in the register class
263 // used for pointers.
265 const TargetLowering *TL = MF.getTarget().getTargetLowering();
267 if (!TL->isTypeLegal(TL->getPointerTy()))
268 // Believe it or not, this is true on PIC16.
271 const TargetRegisterClass *ptrRegClass =
272 TL->getRegClassFor(TL->getPointerTy());
273 if (!ptrRegClass->contains(PhysReg))
276 // Scan upwards through the preceding instructions. If an instruction doesn't
277 // reference the stack slot or the register we're loading, we can
278 // backschedule the reload up past it.
279 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
280 while (NewInsertLoc != Begin) {
281 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
282 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
283 MachineOperand &Op = Prev->getOperand(i);
284 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
287 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
288 Prev->findRegisterDefOperand(PhysReg))
290 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
291 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
292 Prev->findRegisterDefOperand(*Alias))
298 // If we made it to the beginning of the block, turn around and move back
299 // down just past any existing reloads. They're likely to be reloads/remats
300 // for instructions earlier than what our current reload/remat is for, so
301 // they should be scheduled earlier.
302 if (NewInsertLoc == Begin) {
304 while (InsertLoc != NewInsertLoc &&
305 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
306 TII->isTriviallyReMaterializable(NewInsertLoc)))
315 // ReusedOp - For each reused operand, we keep track of a bit of information,
316 // in case we need to rollback upon processing a new operand. See comments
319 // The MachineInstr operand that reused an available value.
322 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
323 unsigned StackSlotOrReMat;
325 // PhysRegReused - The physical register the value was available in.
326 unsigned PhysRegReused;
328 // AssignedPhysReg - The physreg that was assigned for use by the reload.
329 unsigned AssignedPhysReg;
331 // VirtReg - The virtual register itself.
334 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
336 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
337 AssignedPhysReg(apr), VirtReg(vreg) {}
340 /// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
341 /// is reused instead of reloaded.
344 std::vector<ReusedOp> Reuses;
345 BitVector PhysRegsClobbered;
347 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
348 PhysRegsClobbered.resize(tri->getNumRegs());
351 bool hasReuses() const {
352 return !Reuses.empty();
355 /// addReuse - If we choose to reuse a virtual register that is already
356 /// available instead of reloading it, remember that we did so.
357 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
358 unsigned PhysRegReused, unsigned AssignedPhysReg,
360 // If the reload is to the assigned register anyway, no undo will be
362 if (PhysRegReused == AssignedPhysReg) return;
364 // Otherwise, remember this.
365 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
366 AssignedPhysReg, VirtReg));
369 void markClobbered(unsigned PhysReg) {
370 PhysRegsClobbered.set(PhysReg);
373 bool isClobbered(unsigned PhysReg) const {
374 return PhysRegsClobbered.test(PhysReg);
377 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
378 /// is some other operand that is using the specified register, either pick
379 /// a new register to use, or evict the previous reload and use this reg.
380 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
381 MachineFunction &MF, MachineInstr *MI,
382 AvailableSpills &Spills,
383 std::vector<MachineInstr*> &MaybeDeadStores,
384 SmallSet<unsigned, 8> &Rejected,
386 std::vector<MachineOperand*> &KillOps,
389 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
390 /// 'Rejected' set to remember which registers have been considered and
391 /// rejected for the reload. This avoids infinite looping in case like
394 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
395 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
397 /// sees r1 is taken by t2, tries t2's reload register r0
398 /// sees r0 is taken by t3, tries t3's reload register r1
399 /// sees r1 is taken by t2, tries t2's reload register r0 ...
400 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
401 AvailableSpills &Spills,
402 std::vector<MachineInstr*> &MaybeDeadStores,
404 std::vector<MachineOperand*> &KillOps,
406 SmallSet<unsigned, 8> Rejected;
407 MachineFunction &MF = *MI->getParent()->getParent();
408 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
409 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
410 Rejected, RegKills, KillOps, VRM);
416 // ****************** //
417 // Utility Functions //
418 // ****************** //
420 /// findSinglePredSuccessor - Return via reference a vector of machine basic
421 /// blocks each of which is a successor of the specified BB and has no other
423 static void findSinglePredSuccessor(MachineBasicBlock *MBB,
424 SmallVectorImpl<MachineBasicBlock *> &Succs) {
425 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
426 SE = MBB->succ_end(); SI != SE; ++SI) {
427 MachineBasicBlock *SuccMBB = *SI;
428 if (SuccMBB->pred_size() == 1)
429 Succs.push_back(SuccMBB);
433 /// InvalidateKill - Invalidate register kill information for a specific
434 /// register. This also unsets the kills marker on the last kill operand.
435 static void InvalidateKill(unsigned Reg,
436 const TargetRegisterInfo* TRI,
438 std::vector<MachineOperand*> &KillOps) {
440 KillOps[Reg]->setIsKill(false);
441 // KillOps[Reg] might be a def of a super-register.
442 unsigned KReg = KillOps[Reg]->getReg();
443 KillOps[KReg] = NULL;
444 RegKills.reset(KReg);
445 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
447 KillOps[*SR]->setIsKill(false);
455 /// InvalidateKills - MI is going to be deleted. If any of its operands are
456 /// marked kill, then invalidate the information.
457 static void InvalidateKills(MachineInstr &MI,
458 const TargetRegisterInfo* TRI,
460 std::vector<MachineOperand*> &KillOps,
461 SmallVector<unsigned, 2> *KillRegs = NULL) {
462 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
463 MachineOperand &MO = MI.getOperand(i);
464 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
466 unsigned Reg = MO.getReg();
467 if (TargetRegisterInfo::isVirtualRegister(Reg))
470 KillRegs->push_back(Reg);
471 assert(Reg < KillOps.size());
472 if (KillOps[Reg] == &MO) {
475 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
485 /// InvalidateRegDef - If the def operand of the specified def MI is now dead
486 /// (since its spill instruction is removed), mark it isDead. Also checks if
487 /// the def MI has other definition operands that are not dead. Returns it by
489 static bool InvalidateRegDef(MachineBasicBlock::iterator I,
490 MachineInstr &NewDef, unsigned Reg,
492 const TargetRegisterInfo *TRI) {
493 // Due to remat, it's possible this reg isn't being reused. That is,
494 // the def of this reg (by prev MI) is now dead.
495 MachineInstr *DefMI = I;
496 MachineOperand *DefOp = NULL;
497 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
498 MachineOperand &MO = DefMI->getOperand(i);
499 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
501 if (MO.getReg() == Reg)
503 else if (!MO.isDead())
509 bool FoundUse = false, Done = false;
510 MachineBasicBlock::iterator E = &NewDef;
512 for (; !Done && I != E; ++I) {
513 MachineInstr *NMI = I;
514 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
515 MachineOperand &MO = NMI->getOperand(j);
516 if (!MO.isReg() || MO.getReg() == 0 ||
517 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
521 Done = true; // Stop after scanning all the operands of this MI.
532 /// UpdateKills - Track and update kill info. If a MI reads a register that is
533 /// marked kill, then it must be due to register reuse. Transfer the kill info
535 static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
537 std::vector<MachineOperand*> &KillOps) {
538 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
539 MachineOperand &MO = MI.getOperand(i);
540 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
542 unsigned Reg = MO.getReg();
546 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
547 // That can't be right. Register is killed but not re-defined and it's
548 // being reused. Let's fix that.
549 KillOps[Reg]->setIsKill(false);
550 // KillOps[Reg] might be a def of a super-register.
551 unsigned KReg = KillOps[Reg]->getReg();
552 KillOps[KReg] = NULL;
553 RegKills.reset(KReg);
555 // Must be a def of a super-register. Its other sub-regsters are no
556 // longer killed as well.
557 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
562 // Check for subreg kills as well.
568 // = d4 <avoiding reload>
569 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
571 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
572 KillOps[SReg]->setIsKill(false);
573 unsigned KReg = KillOps[SReg]->getReg();
574 KillOps[KReg] = NULL;
575 RegKills.reset(KReg);
577 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
578 KillOps[*SSR] = NULL;
579 RegKills.reset(*SSR);
588 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
595 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
596 const MachineOperand &MO = MI.getOperand(i);
597 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
599 unsigned Reg = MO.getReg();
602 // It also defines (or partially define) aliases.
603 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
607 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
614 /// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
616 static void ReMaterialize(MachineBasicBlock &MBB,
617 MachineBasicBlock::iterator &MII,
618 unsigned DestReg, unsigned Reg,
619 const TargetInstrInfo *TII,
620 const TargetRegisterInfo *TRI,
622 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
624 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
625 assert(TID.getNumDefs() == 1 &&
626 "Don't know how to remat instructions that define > 1 values!");
628 TII->reMaterialize(MBB, MII, DestReg,
629 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
630 MachineInstr *NewMI = prior(MII);
631 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
632 MachineOperand &MO = NewMI->getOperand(i);
633 if (!MO.isReg() || MO.getReg() == 0)
635 unsigned VirtReg = MO.getReg();
636 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
639 unsigned SubIdx = MO.getSubReg();
640 unsigned Phys = VRM.getPhys(VirtReg);
641 assert(Phys && "Virtual register is not assigned a register?");
642 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
649 /// findSuperReg - Find the SubReg's super-register of given register class
650 /// where its SubIdx sub-register is SubReg.
651 static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
652 unsigned SubIdx, const TargetRegisterInfo *TRI) {
653 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
656 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
662 // ******************************** //
663 // Available Spills Implementation //
664 // ******************************** //
666 /// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
667 /// stackslot register. The register is still available but is no longer
668 /// allowed to be modifed.
669 void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
670 std::multimap<unsigned, int>::iterator I =
671 PhysRegsAvailable.lower_bound(PhysReg);
672 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
673 int SlotOrReMat = I->second;
675 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
676 "Bidirectional map mismatch!");
677 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
678 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
679 << " copied, it is available for use but can no longer be modified\n");
683 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
684 /// stackslot register and its aliases. The register and its aliases may
685 /// still available but is no longer allowed to be modifed.
686 void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
687 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
688 disallowClobberPhysRegOnly(*AS);
689 disallowClobberPhysRegOnly(PhysReg);
692 /// ClobberPhysRegOnly - This is called when the specified physreg changes
693 /// value. We use this to invalidate any info about stuff we thing lives in it.
694 void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
695 std::multimap<unsigned, int>::iterator I =
696 PhysRegsAvailable.lower_bound(PhysReg);
697 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
698 int SlotOrReMat = I->second;
699 PhysRegsAvailable.erase(I++);
700 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
701 "Bidirectional map mismatch!");
702 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
703 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
704 << " clobbered, invalidating ");
705 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
706 DEBUG(errs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
708 DEBUG(errs() << "SS#" << SlotOrReMat << "\n");
712 /// ClobberPhysReg - This is called when the specified physreg changes
713 /// value. We use this to invalidate any info about stuff we thing lives in
714 /// it and any of its aliases.
715 void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
716 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
717 ClobberPhysRegOnly(*AS);
718 ClobberPhysRegOnly(PhysReg);
721 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
722 /// into the specified MBB. Add available physical registers as potential
723 /// live-in's. If they are reused in the MBB, they will be added to the
724 /// live-in set to make register scavenger and post-allocation scheduler.
725 void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
727 std::vector<MachineOperand*> &KillOps) {
728 std::set<unsigned> NotAvailable;
729 for (std::multimap<unsigned, int>::iterator
730 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
732 unsigned Reg = I->first;
733 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
734 // FIXME: A temporary workaround. We can't reuse available value if it's
735 // not safe to move the def of the virtual register's class. e.g.
736 // X86::RFP* register classes. Do not add it as a live-in.
737 if (!TII->isSafeToMoveRegClassDefs(RC))
738 // This is no longer available.
739 NotAvailable.insert(Reg);
742 InvalidateKill(Reg, TRI, RegKills, KillOps);
745 // Skip over the same register.
746 std::multimap<unsigned, int>::iterator NI = next(I);
747 while (NI != E && NI->first == Reg) {
753 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
754 E = NotAvailable.end(); I != E; ++I) {
756 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
758 ClobberPhysReg(*SubRegs);
762 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
763 /// slot changes. This removes information about which register the previous
764 /// value for this slot lives in (as the previous value is dead now).
765 void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
766 std::map<int, unsigned>::iterator It =
767 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
768 if (It == SpillSlotsOrReMatsAvailable.end()) return;
769 unsigned Reg = It->second >> 1;
770 SpillSlotsOrReMatsAvailable.erase(It);
772 // This register may hold the value of multiple stack slots, only remove this
773 // stack slot from the set of values the register contains.
774 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
776 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
777 "Map inverse broken!");
778 if (I->second == SlotOrReMat) break;
780 PhysRegsAvailable.erase(I);
783 // ************************** //
784 // Reuse Info Implementation //
785 // ************************** //
787 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
788 /// is some other operand that is using the specified register, either pick
789 /// a new register to use, or evict the previous reload and use this reg.
790 unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
793 MachineInstr *MI, AvailableSpills &Spills,
794 std::vector<MachineInstr*> &MaybeDeadStores,
795 SmallSet<unsigned, 8> &Rejected,
797 std::vector<MachineOperand*> &KillOps,
799 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
800 const TargetRegisterInfo *TRI = Spills.getRegInfo();
802 if (Reuses.empty()) return PhysReg; // This is most often empty.
804 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
805 ReusedOp &Op = Reuses[ro];
806 // If we find some other reuse that was supposed to use this register
807 // exactly for its reload, we can change this reload to use ITS reload
808 // register. That is, unless its reload register has already been
809 // considered and subsequently rejected because it has also been reused
810 // by another operand.
811 if (Op.PhysRegReused == PhysReg &&
812 Rejected.count(Op.AssignedPhysReg) == 0 &&
813 RC->contains(Op.AssignedPhysReg)) {
814 // Yup, use the reload register that we didn't use before.
815 unsigned NewReg = Op.AssignedPhysReg;
816 Rejected.insert(PhysReg);
817 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
818 RegKills, KillOps, VRM);
820 // Otherwise, we might also have a problem if a previously reused
821 // value aliases the new register. If so, codegen the previous reload
823 unsigned PRRU = Op.PhysRegReused;
824 if (TRI->regsOverlap(PRRU, PhysReg)) {
825 // Okay, we found out that an alias of a reused register
826 // was used. This isn't good because it means we have
827 // to undo a previous reuse.
828 MachineBasicBlock *MBB = MI->getParent();
829 const TargetRegisterClass *AliasRC =
830 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
832 // Copy Op out of the vector and remove it, we're going to insert an
833 // explicit load for it.
835 Reuses.erase(Reuses.begin()+ro);
837 // MI may be using only a sub-register of PhysRegUsed.
838 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
840 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
841 "A reuse cannot be a virtual register");
842 if (PRRU != RealPhysRegUsed) {
843 // What was the sub-register index?
844 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
846 "Operand physreg is not a sub-register of PhysRegUsed");
849 // Ok, we're going to try to reload the assigned physreg into the
850 // slot that we were supposed to in the first place. However, that
851 // register could hold a reuse. Check to see if it conflicts or
852 // would prefer us to use a different register.
853 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
854 MF, MI, Spills, MaybeDeadStores,
855 Rejected, RegKills, KillOps, VRM);
857 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
858 int SSorRMId = DoReMat
859 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
861 // Back-schedule reloads and remats.
862 MachineBasicBlock::iterator InsertLoc =
863 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
864 DoReMat, SSorRMId, TII, MF);
867 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
870 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
871 NewOp.StackSlotOrReMat, AliasRC);
872 MachineInstr *LoadMI = prior(InsertLoc);
873 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
874 // Any stores to this stack slot are not dead anymore.
875 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
878 Spills.ClobberPhysReg(NewPhysReg);
879 Spills.ClobberPhysReg(NewOp.PhysRegReused);
881 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
882 MI->getOperand(NewOp.Operand).setReg(RReg);
883 MI->getOperand(NewOp.Operand).setSubReg(0);
885 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
886 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
887 DEBUG(errs() << '\t' << *prior(InsertLoc));
889 DEBUG(errs() << "Reuse undone!\n");
892 // Finally, PhysReg is now available, go ahead and use it.
900 // ************************************************************************ //
902 /// FoldsStackSlotModRef - Return true if the specified MI folds the specified
903 /// stack slot mod/ref. It also checks if it's possible to unfold the
904 /// instruction by having it define a specified physical register instead.
905 static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
906 const TargetInstrInfo *TII,
907 const TargetRegisterInfo *TRI,
909 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
913 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
914 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
915 unsigned VirtReg = I->second.first;
916 VirtRegMap::ModRef MR = I->second.second;
917 if (MR & VirtRegMap::isModRef)
918 if (VRM.getStackSlot(VirtReg) == SS) {
919 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
926 // Does the instruction uses a register that overlaps the scratch register?
927 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
928 MachineOperand &MO = MI.getOperand(i);
929 if (!MO.isReg() || MO.getReg() == 0)
931 unsigned Reg = MO.getReg();
932 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
933 if (!VRM.hasPhys(Reg))
935 Reg = VRM.getPhys(Reg);
937 if (TRI->regsOverlap(PhysReg, Reg))
943 /// FindFreeRegister - Find a free register of a given register class by looking
944 /// at (at most) the last two machine instructions.
945 static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
946 MachineBasicBlock &MBB,
947 const TargetRegisterClass *RC,
948 const TargetRegisterInfo *TRI,
949 BitVector &AllocatableRegs) {
950 BitVector Defs(TRI->getNumRegs());
951 BitVector Uses(TRI->getNumRegs());
952 SmallVector<unsigned, 4> LocalUses;
953 SmallVector<unsigned, 4> Kills;
955 // Take a look at 2 instructions at most.
956 for (unsigned Count = 0; Count < 2; ++Count) {
957 if (MII == MBB.begin())
959 MachineInstr *PrevMI = prior(MII);
960 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
961 MachineOperand &MO = PrevMI->getOperand(i);
962 if (!MO.isReg() || MO.getReg() == 0)
964 unsigned Reg = MO.getReg();
967 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
970 LocalUses.push_back(Reg);
971 if (MO.isKill() && AllocatableRegs[Reg])
972 Kills.push_back(Reg);
976 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
977 unsigned Kill = Kills[i];
978 if (!Defs[Kill] && !Uses[Kill] &&
979 TRI->getPhysicalRegisterRegClass(Kill) == RC)
982 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
983 unsigned Reg = LocalUses[i];
985 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
996 void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
997 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
998 MachineOperand &MO = MI->getOperand(i);
999 if (MO.isReg() && MO.getReg() == VirtReg)
1006 bool operator()(const std::pair<MachineInstr*, int> &A,
1007 const std::pair<MachineInstr*, int> &B) {
1008 return A.second < B.second;
1013 // ***************************** //
1014 // Local Spiller Implementation //
1015 // ***************************** //
1019 class LocalRewriter : public VirtRegRewriter {
1020 MachineRegisterInfo *RegInfo;
1021 const TargetRegisterInfo *TRI;
1022 const TargetInstrInfo *TII;
1023 BitVector AllocatableRegs;
1024 DenseMap<MachineInstr*, unsigned> DistanceMap;
1027 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1028 LiveIntervals* LIs) {
1029 RegInfo = &MF.getRegInfo();
1030 TRI = MF.getTarget().getRegisterInfo();
1031 TII = MF.getTarget().getInstrInfo();
1032 AllocatableRegs = TRI->getAllocatableSet(MF);
1033 DEBUG(errs() << "\n**** Local spiller rewriting function '"
1034 << MF.getFunction()->getName() << "':\n");
1035 DEBUG(errs() << "**** Machine Instrs (NOTE! Does not include spills and"
1036 " reloads!) ****\n");
1039 // Spills - Keep track of which spilled values are available in physregs
1040 // so that we can choose to reuse the physregs instead of emitting
1041 // reloads. This is usually refreshed per basic block.
1042 AvailableSpills Spills(TRI, TII);
1044 // Keep track of kill information.
1045 BitVector RegKills(TRI->getNumRegs());
1046 std::vector<MachineOperand*> KillOps;
1047 KillOps.resize(TRI->getNumRegs(), NULL);
1049 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1050 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1051 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1053 // Traverse the basic blocks depth first.
1054 MachineBasicBlock *Entry = MF.begin();
1055 SmallPtrSet<MachineBasicBlock*,16> Visited;
1056 for (df_ext_iterator<MachineBasicBlock*,
1057 SmallPtrSet<MachineBasicBlock*,16> >
1058 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1060 MachineBasicBlock *MBB = *DFI;
1061 if (!EarlyVisited.count(MBB))
1062 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1064 // If this MBB is the only predecessor of a successor. Keep the
1065 // availability information and visit it next.
1067 // Keep visiting single predecessor successor as long as possible.
1068 SinglePredSuccs.clear();
1069 findSinglePredSuccessor(MBB, SinglePredSuccs);
1070 if (SinglePredSuccs.empty())
1073 // FIXME: More than one successors, each of which has MBB has
1074 // the only predecessor.
1075 MBB = SinglePredSuccs[0];
1076 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1077 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1078 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1083 // Clear the availability info.
1087 DEBUG(errs() << "**** Post Machine Instrs ****\n");
1090 // Mark unused spill slots.
1091 MachineFrameInfo *MFI = MF.getFrameInfo();
1092 int SS = VRM.getLowSpillSlot();
1093 if (SS != VirtRegMap::NO_STACK_SLOT)
1094 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1095 if (!VRM.isSpillSlotUsed(SS)) {
1096 MFI->RemoveStackObject(SS);
1105 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1106 /// a scratch register is available.
1107 /// xorq %r12<kill>, %r13
1108 /// addq %rax, -184(%rbp)
1109 /// addq %r13, -184(%rbp)
1111 /// xorq %r12<kill>, %r13
1112 /// movq -184(%rbp), %r12
1115 /// movq %r12, -184(%rbp)
1116 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1117 MachineBasicBlock &MBB,
1118 MachineBasicBlock::iterator &MII,
1119 std::vector<MachineInstr*> &MaybeDeadStores,
1120 AvailableSpills &Spills,
1121 BitVector &RegKills,
1122 std::vector<MachineOperand*> &KillOps,
1125 MachineBasicBlock::iterator NextMII = next(MII);
1126 if (NextMII == MBB.end())
1129 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1132 // Now let's see if the last couple of instructions happens to have freed up
1134 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1135 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1139 MachineFunction &MF = *MBB.getParent();
1140 TRI = MF.getTarget().getRegisterInfo();
1141 MachineInstr &MI = *MII;
1142 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1145 // If the next instruction also folds the same SS modref and can be unfoled,
1146 // then it's worthwhile to issue a load from SS into the free register and
1147 // then unfold these instructions.
1148 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1151 // Back-schedule reloads and remats.
1152 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
1154 // Load from SS to the spare physical register.
1155 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1156 // This invalidates Phys.
1157 Spills.ClobberPhysReg(PhysReg);
1158 // Remember it's available.
1159 Spills.addAvailable(SS, PhysReg);
1160 MaybeDeadStores[SS] = NULL;
1162 // Unfold current MI.
1163 SmallVector<MachineInstr*, 4> NewMIs;
1164 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1165 llvm_unreachable("Unable unfold the load / store folding instruction!");
1166 assert(NewMIs.size() == 1);
1167 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1168 VRM.transferRestorePts(&MI, NewMIs[0]);
1169 MII = MBB.insert(MII, NewMIs[0]);
1170 InvalidateKills(MI, TRI, RegKills, KillOps);
1171 VRM.RemoveMachineInstrFromMaps(&MI);
1175 // Unfold next instructions that fold the same SS.
1177 MachineInstr &NextMI = *NextMII;
1178 NextMII = next(NextMII);
1180 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1181 llvm_unreachable("Unable unfold the load / store folding instruction!");
1182 assert(NewMIs.size() == 1);
1183 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1184 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1185 MBB.insert(NextMII, NewMIs[0]);
1186 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1187 VRM.RemoveMachineInstrFromMaps(&NextMI);
1190 if (NextMII == MBB.end())
1192 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1194 // Store the value back into SS.
1195 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1196 MachineInstr *StoreMI = prior(NextMII);
1197 VRM.addSpillSlotUse(SS, StoreMI);
1198 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1203 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1204 /// instruction. e.g.
1206 /// movl %eax, -32(%ebp)
1207 /// movl -36(%ebp), %eax
1208 /// orl %eax, -32(%ebp)
1211 /// orl -36(%ebp), %eax
1212 /// mov %eax, -32(%ebp)
1213 /// This enables unfolding optimization for a subsequent instruction which will
1214 /// also eliminate the newly introduced store instruction.
1215 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1216 MachineBasicBlock::iterator &MII,
1217 std::vector<MachineInstr*> &MaybeDeadStores,
1218 AvailableSpills &Spills,
1219 BitVector &RegKills,
1220 std::vector<MachineOperand*> &KillOps,
1222 MachineFunction &MF = *MBB.getParent();
1223 MachineInstr &MI = *MII;
1224 unsigned UnfoldedOpc = 0;
1225 unsigned UnfoldPR = 0;
1226 unsigned UnfoldVR = 0;
1227 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1228 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1229 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1230 // Only transform a MI that folds a single register.
1233 UnfoldVR = I->second.first;
1234 VirtRegMap::ModRef MR = I->second.second;
1235 // MI2VirtMap be can updated which invalidate the iterator.
1236 // Increment the iterator first.
1238 if (VRM.isAssignedReg(UnfoldVR))
1240 // If this reference is not a use, any previous store is now dead.
1241 // Otherwise, the store to this stack slot is not dead anymore.
1242 FoldedSS = VRM.getStackSlot(UnfoldVR);
1243 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1244 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1245 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1246 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1249 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1258 // Look for other unfolding opportunities.
1259 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1260 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1263 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1264 MachineOperand &MO = MI.getOperand(i);
1265 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1267 unsigned VirtReg = MO.getReg();
1268 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1270 if (VRM.isAssignedReg(VirtReg)) {
1271 unsigned PhysReg = VRM.getPhys(VirtReg);
1272 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1274 } else if (VRM.isReMaterialized(VirtReg))
1276 int SS = VRM.getStackSlot(VirtReg);
1277 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1279 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1283 if (VRM.hasPhys(VirtReg)) {
1284 PhysReg = VRM.getPhys(VirtReg);
1285 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1289 // Ok, we'll need to reload the value into a register which makes
1290 // it impossible to perform the store unfolding optimization later.
1291 // Let's see if it is possible to fold the load if the store is
1292 // unfolded. This allows us to perform the store unfolding
1294 SmallVector<MachineInstr*, 4> NewMIs;
1295 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1296 assert(NewMIs.size() == 1);
1297 MachineInstr *NewMI = NewMIs.back();
1299 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1301 SmallVector<unsigned, 1> Ops;
1303 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1305 VRM.addSpillSlotUse(SS, FoldedMI);
1306 if (!VRM.hasPhys(UnfoldVR))
1307 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1308 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1309 MII = MBB.insert(MII, FoldedMI);
1310 InvalidateKills(MI, TRI, RegKills, KillOps);
1311 VRM.RemoveMachineInstrFromMaps(&MI);
1313 MF.DeleteMachineInstr(NewMI);
1316 MF.DeleteMachineInstr(NewMI);
1323 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1324 /// where SrcReg is r1 and it is tied to r0. Return true if after
1325 /// commuting this instruction it will be r0 = op r2, r1.
1326 static bool CommuteChangesDestination(MachineInstr *DefMI,
1327 const TargetInstrDesc &TID,
1329 const TargetInstrInfo *TII,
1331 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1333 if (!DefMI->getOperand(1).isReg() ||
1334 DefMI->getOperand(1).getReg() != SrcReg)
1337 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1339 unsigned SrcIdx1, SrcIdx2;
1340 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1342 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1349 /// CommuteToFoldReload -
1352 /// r1 = op r1, r2<kill>
1355 /// If op is commutable and r2 is killed, then we can xform these to
1356 /// r2 = op r2, fi#1
1358 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1359 MachineBasicBlock::iterator &MII,
1360 unsigned VirtReg, unsigned SrcReg, int SS,
1361 AvailableSpills &Spills,
1362 BitVector &RegKills,
1363 std::vector<MachineOperand*> &KillOps,
1364 const TargetRegisterInfo *TRI,
1366 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1369 MachineFunction &MF = *MBB.getParent();
1370 MachineInstr &MI = *MII;
1371 MachineBasicBlock::iterator DefMII = prior(MII);
1372 MachineInstr *DefMI = DefMII;
1373 const TargetInstrDesc &TID = DefMI->getDesc();
1375 if (DefMII != MBB.begin() &&
1376 TID.isCommutable() &&
1377 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1378 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1379 unsigned NewReg = NewDstMO.getReg();
1380 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1382 MachineInstr *ReloadMI = prior(DefMII);
1384 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1385 if (DestReg != SrcReg || FrameIdx != SS)
1387 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1391 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1393 assert(DefMI->getOperand(DefIdx).isReg() &&
1394 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1396 // Now commute def instruction.
1397 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1400 SmallVector<unsigned, 1> Ops;
1401 Ops.push_back(NewDstIdx);
1402 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1403 // Not needed since foldMemoryOperand returns new MI.
1404 MF.DeleteMachineInstr(CommutedMI);
1408 VRM.addSpillSlotUse(SS, FoldedMI);
1409 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1410 // Insert new def MI and spill MI.
1411 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1412 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1414 MachineInstr *StoreMI = MII;
1415 VRM.addSpillSlotUse(SS, StoreMI);
1416 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1417 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1419 // Delete all 3 old instructions.
1420 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1421 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1422 MBB.erase(ReloadMI);
1423 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1424 VRM.RemoveMachineInstrFromMaps(DefMI);
1426 InvalidateKills(MI, TRI, RegKills, KillOps);
1427 VRM.RemoveMachineInstrFromMaps(&MI);
1430 // If NewReg was previously holding value of some SS, it's now clobbered.
1431 // This has to be done now because it's a physical register. When this
1432 // instruction is re-visited, it's ignored.
1433 Spills.ClobberPhysReg(NewReg);
1442 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1443 /// the last store to the same slot is now dead. If so, remove the last store.
1444 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1445 MachineBasicBlock::iterator &MII,
1446 int Idx, unsigned PhysReg, int StackSlot,
1447 const TargetRegisterClass *RC,
1448 bool isAvailable, MachineInstr *&LastStore,
1449 AvailableSpills &Spills,
1450 SmallSet<MachineInstr*, 4> &ReMatDefs,
1451 BitVector &RegKills,
1452 std::vector<MachineOperand*> &KillOps,
1455 MachineBasicBlock::iterator oldNextMII = next(MII);
1456 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1457 MachineInstr *StoreMI = prior(oldNextMII);
1458 VRM.addSpillSlotUse(StackSlot, StoreMI);
1459 DEBUG(errs() << "Store:\t" << *StoreMI);
1461 // If there is a dead store to this stack slot, nuke it now.
1463 DEBUG(errs() << "Removed dead store:\t" << *LastStore);
1465 SmallVector<unsigned, 2> KillRegs;
1466 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1467 MachineBasicBlock::iterator PrevMII = LastStore;
1468 bool CheckDef = PrevMII != MBB.begin();
1471 VRM.RemoveMachineInstrFromMaps(LastStore);
1472 MBB.erase(LastStore);
1474 // Look at defs of killed registers on the store. Mark the defs
1475 // as dead since the store has been deleted and they aren't
1477 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1478 bool HasOtherDef = false;
1479 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1480 MachineInstr *DeadDef = PrevMII;
1481 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1482 // FIXME: This assumes a remat def does not have side effects.
1483 VRM.RemoveMachineInstrFromMaps(DeadDef);
1492 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1493 // the last of multiple instructions is the actual store.
1494 LastStore = prior(oldNextMII);
1496 // If the stack slot value was previously available in some other
1497 // register, change it now. Otherwise, make the register available,
1499 Spills.ModifyStackSlotOrReMat(StackSlot);
1500 Spills.ClobberPhysReg(PhysReg);
1501 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1505 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1506 /// effect and all of its defs are dead.
1507 static bool isSafeToDelete(MachineInstr &MI) {
1508 const TargetInstrDesc &TID = MI.getDesc();
1509 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1510 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1511 TID.hasUnmodeledSideEffects())
1513 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1514 MachineOperand &MO = MI.getOperand(i);
1515 if (!MO.isReg() || !MO.getReg())
1517 if (MO.isDef() && !MO.isDead())
1519 if (MO.isUse() && MO.isKill())
1520 // FIXME: We can't remove kill markers or else the scavenger will assert.
1521 // An alternative is to add a ADD pseudo instruction to replace kill
1528 /// TransferDeadness - A identity copy definition is dead and it's being
1529 /// removed. Find the last def or use and mark it as dead / kill.
1530 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1531 unsigned Reg, BitVector &RegKills,
1532 std::vector<MachineOperand*> &KillOps,
1534 SmallPtrSet<MachineInstr*, 4> Seens;
1535 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1536 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1537 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1538 MachineInstr *UDMI = &*RI;
1539 if (UDMI->getParent() != MBB)
1541 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1542 if (DI == DistanceMap.end() || DI->second > CurDist)
1544 if (Seens.insert(UDMI))
1545 Refs.push_back(std::make_pair(UDMI, DI->second));
1550 std::sort(Refs.begin(), Refs.end(), RefSorter());
1552 while (!Refs.empty()) {
1553 MachineInstr *LastUDMI = Refs.back().first;
1556 MachineOperand *LastUD = NULL;
1557 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1558 MachineOperand &MO = LastUDMI->getOperand(i);
1559 if (!MO.isReg() || MO.getReg() != Reg)
1561 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1563 if (LastUDMI->isRegTiedToDefOperand(i))
1566 if (LastUD->isDef()) {
1567 // If the instruction has no side effect, delete it and propagate
1568 // backward further. Otherwise, mark is dead and we are done.
1569 if (!isSafeToDelete(*LastUDMI)) {
1570 LastUD->setIsDead();
1573 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1574 MBB->erase(LastUDMI);
1576 LastUD->setIsKill();
1578 KillOps[Reg] = LastUD;
1584 /// rewriteMBB - Keep track of which spills are available even after the
1585 /// register allocator is done with them. If possible, avid reloading vregs.
1586 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1588 AvailableSpills &Spills, BitVector &RegKills,
1589 std::vector<MachineOperand*> &KillOps) {
1591 DEBUG(errs() << "\n**** Local spiller rewriting MBB '"
1592 << MBB.getBasicBlock()->getName() << "':\n");
1594 MachineFunction &MF = *MBB.getParent();
1596 // MaybeDeadStores - When we need to write a value back into a stack slot,
1597 // keep track of the inserted store. If the stack slot value is never read
1598 // (because the value was used from some available register, for example), and
1599 // subsequently stored to, the original store is dead. This map keeps track
1600 // of inserted stores that are not used. If we see a subsequent store to the
1601 // same stack slot, the original store is deleted.
1602 std::vector<MachineInstr*> MaybeDeadStores;
1603 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1605 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1606 SmallSet<MachineInstr*, 4> ReMatDefs;
1609 SmallSet<unsigned, 2> KilledMIRegs;
1612 KillOps.resize(TRI->getNumRegs(), NULL);
1615 DistanceMap.clear();
1616 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1618 MachineBasicBlock::iterator NextMII = next(MII);
1620 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1621 bool Erased = false;
1622 bool BackTracked = false;
1623 if (OptimizeByUnfold(MBB, MII,
1624 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1625 NextMII = next(MII);
1627 MachineInstr &MI = *MII;
1629 if (VRM.hasEmergencySpills(&MI)) {
1630 // Spill physical register(s) in the rare case the allocator has run out
1631 // of registers to allocate.
1632 SmallSet<int, 4> UsedSS;
1633 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1634 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1635 unsigned PhysReg = EmSpills[i];
1636 const TargetRegisterClass *RC =
1637 TRI->getPhysicalRegisterRegClass(PhysReg);
1638 assert(RC && "Unable to determine register class!");
1639 int SS = VRM.getEmergencySpillSlot(RC);
1640 if (UsedSS.count(SS))
1641 llvm_unreachable("Need to spill more than one physical registers!");
1643 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1644 MachineInstr *StoreMI = prior(MII);
1645 VRM.addSpillSlotUse(SS, StoreMI);
1647 // Back-schedule reloads and remats.
1648 MachineBasicBlock::iterator InsertLoc =
1649 ComputeReloadLoc(next(MII), MBB.begin(), PhysReg, TRI, false,
1652 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1654 MachineInstr *LoadMI = prior(InsertLoc);
1655 VRM.addSpillSlotUse(SS, LoadMI);
1657 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1659 NextMII = next(MII);
1662 // Insert restores here if asked to.
1663 if (VRM.isRestorePt(&MI)) {
1664 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1665 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1666 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1667 if (!VRM.getPreSplitReg(VirtReg))
1668 continue; // Split interval spilled again.
1669 unsigned Phys = VRM.getPhys(VirtReg);
1670 RegInfo->setPhysRegUsed(Phys);
1672 // Check if the value being restored if available. If so, it must be
1673 // from a predecessor BB that fallthrough into this BB. We do not
1679 // ... # r1 not clobbered
1682 bool DoReMat = VRM.isReMaterialized(VirtReg);
1683 int SSorRMId = DoReMat
1684 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1685 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1686 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1687 if (InReg == Phys) {
1688 // If the value is already available in the expected register, save
1689 // a reload / remat.
1691 DEBUG(errs() << "Reusing RM#"
1692 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1694 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1695 DEBUG(errs() << " from physreg "
1696 << TRI->getName(InReg) << " for vreg"
1697 << VirtReg <<" instead of reloading into physreg "
1698 << TRI->getName(Phys) << '\n');
1701 } else if (InReg && InReg != Phys) {
1703 DEBUG(errs() << "Reusing RM#"
1704 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1706 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1707 DEBUG(errs() << " from physreg "
1708 << TRI->getName(InReg) << " for vreg"
1709 << VirtReg <<" by copying it into physreg "
1710 << TRI->getName(Phys) << '\n');
1712 // If the reloaded / remat value is available in another register,
1713 // copy it to the desired register.
1715 // Back-schedule reloads and remats.
1716 MachineBasicBlock::iterator InsertLoc =
1717 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1720 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
1722 // This invalidates Phys.
1723 Spills.ClobberPhysReg(Phys);
1724 // Remember it's available.
1725 Spills.addAvailable(SSorRMId, Phys);
1728 MachineInstr *CopyMI = prior(InsertLoc);
1729 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
1730 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1731 KillOpnd->setIsKill();
1732 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1734 DEBUG(errs() << '\t' << *CopyMI);
1739 // Back-schedule reloads and remats.
1740 MachineBasicBlock::iterator InsertLoc =
1741 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1744 if (VRM.isReMaterialized(VirtReg)) {
1745 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
1747 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1748 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1749 MachineInstr *LoadMI = prior(InsertLoc);
1750 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1752 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
1755 // This invalidates Phys.
1756 Spills.ClobberPhysReg(Phys);
1757 // Remember it's available.
1758 Spills.addAvailable(SSorRMId, Phys);
1760 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1761 DEBUG(errs() << '\t' << *prior(MII));
1765 // Insert spills here if asked to.
1766 if (VRM.isSpillPt(&MI)) {
1767 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1768 VRM.getSpillPtSpills(&MI);
1769 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1770 unsigned VirtReg = SpillRegs[i].first;
1771 bool isKill = SpillRegs[i].second;
1772 if (!VRM.getPreSplitReg(VirtReg))
1773 continue; // Split interval spilled again.
1774 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1775 unsigned Phys = VRM.getPhys(VirtReg);
1776 int StackSlot = VRM.getStackSlot(VirtReg);
1777 MachineBasicBlock::iterator oldNextMII = next(MII);
1778 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1779 MachineInstr *StoreMI = prior(oldNextMII);
1780 VRM.addSpillSlotUse(StackSlot, StoreMI);
1781 DEBUG(errs() << "Store:\t" << *StoreMI);
1782 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1784 NextMII = next(MII);
1787 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1789 ReuseInfo ReusedOperands(MI, TRI);
1790 SmallVector<unsigned, 4> VirtUseOps;
1791 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1792 MachineOperand &MO = MI.getOperand(i);
1793 if (!MO.isReg() || MO.getReg() == 0)
1794 continue; // Ignore non-register operands.
1796 unsigned VirtReg = MO.getReg();
1797 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1798 // Ignore physregs for spilling, but remember that it is used by this
1800 RegInfo->setPhysRegUsed(VirtReg);
1804 // We want to process implicit virtual register uses first.
1805 if (MO.isImplicit())
1806 // If the virtual register is implicitly defined, emit a implicit_def
1807 // before so scavenger knows it's "defined".
1808 // FIXME: This is a horrible hack done the by register allocator to
1809 // remat a definition with virtual register operand.
1810 VirtUseOps.insert(VirtUseOps.begin(), i);
1812 VirtUseOps.push_back(i);
1815 // Process all of the spilled uses and all non spilled reg references.
1816 SmallVector<int, 2> PotentialDeadStoreSlots;
1817 KilledMIRegs.clear();
1818 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1819 unsigned i = VirtUseOps[j];
1820 MachineOperand &MO = MI.getOperand(i);
1821 unsigned VirtReg = MO.getReg();
1822 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1823 "Not a virtual register?");
1825 unsigned SubIdx = MO.getSubReg();
1826 if (VRM.isAssignedReg(VirtReg)) {
1827 // This virtual register was assigned a physreg!
1828 unsigned Phys = VRM.getPhys(VirtReg);
1829 RegInfo->setPhysRegUsed(Phys);
1831 ReusedOperands.markClobbered(Phys);
1832 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1833 MI.getOperand(i).setReg(RReg);
1834 MI.getOperand(i).setSubReg(0);
1835 if (VRM.isImplicitlyDefined(VirtReg))
1836 // FIXME: Is this needed?
1837 BuildMI(MBB, &MI, MI.getDebugLoc(),
1838 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1842 // This virtual register is now known to be a spilled value.
1844 continue; // Handle defs in the loop below (handle use&def here though)
1846 bool AvoidReload = MO.isUndef();
1847 // Check if it is defined by an implicit def. It should not be spilled.
1848 // Note, this is for correctness reason. e.g.
1849 // 8 %reg1024<def> = IMPLICIT_DEF
1850 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1851 // The live range [12, 14) are not part of the r1024 live interval since
1852 // it's defined by an implicit def. It will not conflicts with live
1853 // interval of r1025. Now suppose both registers are spilled, you can
1854 // easily see a situation where both registers are reloaded before
1855 // the INSERT_SUBREG and both target registers that would overlap.
1856 bool DoReMat = VRM.isReMaterialized(VirtReg);
1857 int SSorRMId = DoReMat
1858 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1859 int ReuseSlot = SSorRMId;
1861 // Check to see if this stack slot is available.
1862 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1864 // If this is a sub-register use, make sure the reuse register is in the
1865 // right register class. For example, for x86 not all of the 32-bit
1866 // registers have accessible sub-registers.
1867 // Similarly so for EXTRACT_SUBREG. Consider this:
1869 // MOV32_mr fi#1, EDI
1871 // = EXTRACT_SUBREG fi#1
1872 // fi#1 is available in EDI, but it cannot be reused because it's not in
1873 // the right register file.
1874 if (PhysReg && !AvoidReload &&
1875 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1876 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1877 if (!RC->contains(PhysReg))
1881 if (PhysReg && !AvoidReload) {
1882 // This spilled operand might be part of a two-address operand. If this
1883 // is the case, then changing it will necessarily require changing the
1884 // def part of the instruction as well. However, in some cases, we
1885 // aren't allowed to modify the reused register. If none of these cases
1887 bool CanReuse = true;
1888 bool isTied = MI.isRegTiedToDefOperand(i);
1890 // Okay, we have a two address operand. We can reuse this physreg as
1891 // long as we are allowed to clobber the value and there isn't an
1892 // earlier def that has already clobbered the physreg.
1893 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1894 Spills.canClobberPhysReg(PhysReg);
1898 // If this stack slot value is already available, reuse it!
1899 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1900 DEBUG(errs() << "Reusing RM#"
1901 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1903 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1904 DEBUG(errs() << " from physreg "
1905 << TRI->getName(PhysReg) << " for vreg"
1906 << VirtReg <<" instead of reloading into physreg "
1907 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
1908 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1909 MI.getOperand(i).setReg(RReg);
1910 MI.getOperand(i).setSubReg(0);
1912 // The only technical detail we have is that we don't know that
1913 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1914 // later in the instruction. In particular, consider 'op V1, V2'.
1915 // If V1 is available in physreg R0, we would choose to reuse it
1916 // here, instead of reloading it into the register the allocator
1917 // indicated (say R1). However, V2 might have to be reloaded
1918 // later, and it might indicate that it needs to live in R0. When
1919 // this occurs, we need to have information available that
1920 // indicates it is safe to use R1 for the reload instead of R0.
1922 // To further complicate matters, we might conflict with an alias,
1923 // or R0 and R1 might not be compatible with each other. In this
1924 // case, we actually insert a reload for V1 in R1, ensuring that
1925 // we can get at R0 or its alias.
1926 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1927 VRM.getPhys(VirtReg), VirtReg);
1929 // Only mark it clobbered if this is a use&def operand.
1930 ReusedOperands.markClobbered(PhysReg);
1933 if (MI.getOperand(i).isKill() &&
1934 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1936 // The store of this spilled value is potentially dead, but we
1937 // won't know for certain until we've confirmed that the re-use
1938 // above is valid, which means waiting until the other operands
1939 // are processed. For now we just track the spill slot, we'll
1940 // remove it after the other operands are processed if valid.
1942 PotentialDeadStoreSlots.push_back(ReuseSlot);
1945 // Mark is isKill if it's there no other uses of the same virtual
1946 // register and it's not a two-address operand. IsKill will be
1947 // unset if reg is reused.
1948 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1949 MI.getOperand(i).setIsKill();
1950 KilledMIRegs.insert(VirtReg);
1956 // Otherwise we have a situation where we have a two-address instruction
1957 // whose mod/ref operand needs to be reloaded. This reload is already
1958 // available in some register "PhysReg", but if we used PhysReg as the
1959 // operand to our 2-addr instruction, the instruction would modify
1960 // PhysReg. This isn't cool if something later uses PhysReg and expects
1961 // to get its initial value.
1963 // To avoid this problem, and to avoid doing a load right after a store,
1964 // we emit a copy from PhysReg into the designated register for this
1966 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1967 assert(DesignatedReg && "Must map virtreg to physreg!");
1969 // Note that, if we reused a register for a previous operand, the
1970 // register we want to reload into might not actually be
1971 // available. If this occurs, use the register indicated by the
1973 if (ReusedOperands.hasReuses())
1974 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1976 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1978 // If the mapped designated register is actually the physreg we have
1979 // incoming, we don't need to inserted a dead copy.
1980 if (DesignatedReg == PhysReg) {
1981 // If this stack slot value is already available, reuse it!
1982 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1983 DEBUG(errs() << "Reusing RM#"
1984 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
1986 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1987 DEBUG(errs() << " from physreg " << TRI->getName(PhysReg)
1988 << " for vreg" << VirtReg
1989 << " instead of reloading into same physreg.\n");
1990 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1991 MI.getOperand(i).setReg(RReg);
1992 MI.getOperand(i).setSubReg(0);
1993 ReusedOperands.markClobbered(RReg);
1998 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1999 RegInfo->setPhysRegUsed(DesignatedReg);
2000 ReusedOperands.markClobbered(DesignatedReg);
2002 // Back-schedule reloads and remats.
2003 MachineBasicBlock::iterator InsertLoc =
2004 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
2007 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2009 MachineInstr *CopyMI = prior(InsertLoc);
2010 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
2011 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2013 // This invalidates DesignatedReg.
2014 Spills.ClobberPhysReg(DesignatedReg);
2016 Spills.addAvailable(ReuseSlot, DesignatedReg);
2018 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2019 MI.getOperand(i).setReg(RReg);
2020 MI.getOperand(i).setSubReg(0);
2021 DEBUG(errs() << '\t' << *prior(MII));
2026 // Otherwise, reload it and remember that we have it.
2027 PhysReg = VRM.getPhys(VirtReg);
2028 assert(PhysReg && "Must map virtreg to physreg!");
2030 // Note that, if we reused a register for a previous operand, the
2031 // register we want to reload into might not actually be
2032 // available. If this occurs, use the register indicated by the
2034 if (ReusedOperands.hasReuses())
2035 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2036 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2038 RegInfo->setPhysRegUsed(PhysReg);
2039 ReusedOperands.markClobbered(PhysReg);
2043 // Back-schedule reloads and remats.
2044 MachineBasicBlock::iterator InsertLoc =
2045 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2049 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
2051 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
2052 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2053 MachineInstr *LoadMI = prior(InsertLoc);
2054 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2056 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
2058 // This invalidates PhysReg.
2059 Spills.ClobberPhysReg(PhysReg);
2061 // Any stores to this stack slot are not dead anymore.
2063 MaybeDeadStores[SSorRMId] = NULL;
2064 Spills.addAvailable(SSorRMId, PhysReg);
2065 // Assumes this is the last use. IsKill will be unset if reg is reused
2066 // unless it's a two-address operand.
2067 if (!MI.isRegTiedToDefOperand(i) &&
2068 KilledMIRegs.count(VirtReg) == 0) {
2069 MI.getOperand(i).setIsKill();
2070 KilledMIRegs.insert(VirtReg);
2073 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2074 DEBUG(errs() << '\t' << *prior(InsertLoc));
2076 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2077 MI.getOperand(i).setReg(RReg);
2078 MI.getOperand(i).setSubReg(0);
2081 // Ok - now we can remove stores that have been confirmed dead.
2082 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2083 // This was the last use and the spilled value is still available
2084 // for reuse. That means the spill was unnecessary!
2085 int PDSSlot = PotentialDeadStoreSlots[j];
2086 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2088 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2089 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2090 VRM.RemoveMachineInstrFromMaps(DeadStore);
2091 MBB.erase(DeadStore);
2092 MaybeDeadStores[PDSSlot] = NULL;
2098 DEBUG(errs() << '\t' << MI);
2101 // If we have folded references to memory operands, make sure we clear all
2102 // physical registers that may contain the value of the spilled virtual
2104 SmallSet<int, 2> FoldedSS;
2105 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2106 unsigned VirtReg = I->second.first;
2107 VirtRegMap::ModRef MR = I->second.second;
2108 DEBUG(errs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2110 // MI2VirtMap be can updated which invalidate the iterator.
2111 // Increment the iterator first.
2113 int SS = VRM.getStackSlot(VirtReg);
2114 if (SS == VirtRegMap::NO_STACK_SLOT)
2116 FoldedSS.insert(SS);
2117 DEBUG(errs() << " - StackSlot: " << SS << "\n");
2119 // If this folded instruction is just a use, check to see if it's a
2120 // straight load from the virt reg slot.
2121 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2123 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2124 if (DestReg && FrameIdx == SS) {
2125 // If this spill slot is available, turn it into a copy (or nothing)
2126 // instead of leaving it as a load!
2127 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2128 DEBUG(errs() << "Promoted Load To Copy: " << MI);
2129 if (DestReg != InReg) {
2130 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2131 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2132 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2133 unsigned SubIdx = DefMO->getSubReg();
2134 // Revisit the copy so we make sure to notice the effects of the
2135 // operation on the destreg (either needing to RA it if it's
2136 // virtual or needing to clobber any values if it's physical).
2138 --NextMII; // backtrack to the copy.
2139 NextMII->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
2140 // Propagate the sub-register index over.
2142 DefMO = NextMII->findRegisterDefOperand(DestReg);
2143 DefMO->setSubReg(SubIdx);
2147 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2148 KillOpnd->setIsKill();
2152 DEBUG(errs() << "Removing now-noop copy: " << MI);
2153 // Unset last kill since it's being reused.
2154 InvalidateKill(InReg, TRI, RegKills, KillOps);
2155 Spills.disallowClobberPhysReg(InReg);
2158 InvalidateKills(MI, TRI, RegKills, KillOps);
2159 VRM.RemoveMachineInstrFromMaps(&MI);
2162 goto ProcessNextInst;
2165 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2166 SmallVector<MachineInstr*, 4> NewMIs;
2168 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2169 MBB.insert(MII, NewMIs[0]);
2170 InvalidateKills(MI, TRI, RegKills, KillOps);
2171 VRM.RemoveMachineInstrFromMaps(&MI);
2174 --NextMII; // backtrack to the unfolded instruction.
2176 goto ProcessNextInst;
2181 // If this reference is not a use, any previous store is now dead.
2182 // Otherwise, the store to this stack slot is not dead anymore.
2183 MachineInstr* DeadStore = MaybeDeadStores[SS];
2185 bool isDead = !(MR & VirtRegMap::isRef);
2186 MachineInstr *NewStore = NULL;
2187 if (MR & VirtRegMap::isModRef) {
2188 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2189 SmallVector<MachineInstr*, 4> NewMIs;
2190 // We can reuse this physreg as long as we are allowed to clobber
2191 // the value and there isn't an earlier def that has already clobbered
2194 !ReusedOperands.isClobbered(PhysReg) &&
2195 Spills.canClobberPhysReg(PhysReg) &&
2196 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2197 MachineOperand *KillOpnd =
2198 DeadStore->findRegisterUseOperand(PhysReg, true);
2199 // Note, if the store is storing a sub-register, it's possible the
2200 // super-register is needed below.
2201 if (KillOpnd && !KillOpnd->getSubReg() &&
2202 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2203 MBB.insert(MII, NewMIs[0]);
2204 NewStore = NewMIs[1];
2205 MBB.insert(MII, NewStore);
2206 VRM.addSpillSlotUse(SS, NewStore);
2207 InvalidateKills(MI, TRI, RegKills, KillOps);
2208 VRM.RemoveMachineInstrFromMaps(&MI);
2212 --NextMII; // backtrack to the unfolded instruction.
2220 if (isDead) { // Previous store is dead.
2221 // If we get here, the store is dead, nuke it now.
2222 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
2223 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2224 VRM.RemoveMachineInstrFromMaps(DeadStore);
2225 MBB.erase(DeadStore);
2230 MaybeDeadStores[SS] = NULL;
2232 // Treat this store as a spill merged into a copy. That makes the
2233 // stack slot value available.
2234 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2235 goto ProcessNextInst;
2239 // If the spill slot value is available, and this is a new definition of
2240 // the value, the value is not available anymore.
2241 if (MR & VirtRegMap::isMod) {
2242 // Notice that the value in this stack slot has been modified.
2243 Spills.ModifyStackSlotOrReMat(SS);
2245 // If this is *just* a mod of the value, check to see if this is just a
2246 // store to the spill slot (i.e. the spill got merged into the copy). If
2247 // so, realize that the vreg is available now, and add the store to the
2248 // MaybeDeadStore info.
2250 if (!(MR & VirtRegMap::isRef)) {
2251 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2252 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2253 "Src hasn't been allocated yet?");
2255 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2256 Spills, RegKills, KillOps, TRI, VRM)) {
2257 NextMII = next(MII);
2259 goto ProcessNextInst;
2262 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2263 // this as a potentially dead store in case there is a subsequent
2264 // store into the stack slot without a read from it.
2265 MaybeDeadStores[StackSlot] = &MI;
2267 // If the stack slot value was previously available in some other
2268 // register, change it now. Otherwise, make the register
2269 // available in PhysReg.
2270 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2276 // Process all of the spilled defs.
2277 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2278 MachineOperand &MO = MI.getOperand(i);
2279 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2282 unsigned VirtReg = MO.getReg();
2283 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2284 // Check to see if this is a noop copy. If so, eliminate the
2285 // instruction before considering the dest reg to be changed.
2286 // Also check if it's copying from an "undef", if so, we can't
2287 // eliminate this or else the undef marker is lost and it will
2288 // confuses the scavenger. This is extremely rare.
2289 unsigned Src, Dst, SrcSR, DstSR;
2290 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2291 !MI.findRegisterUseOperand(Src)->isUndef()) {
2293 DEBUG(errs() << "Removing now-noop copy: " << MI);
2294 SmallVector<unsigned, 2> KillRegs;
2295 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2296 if (MO.isDead() && !KillRegs.empty()) {
2297 // Source register or an implicit super/sub-register use is killed.
2298 assert(KillRegs[0] == Dst ||
2299 TRI->isSubRegister(KillRegs[0], Dst) ||
2300 TRI->isSuperRegister(KillRegs[0], Dst));
2301 // Last def is now dead.
2302 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
2304 VRM.RemoveMachineInstrFromMaps(&MI);
2307 Spills.disallowClobberPhysReg(VirtReg);
2308 goto ProcessNextInst;
2311 // If it's not a no-op copy, it clobbers the value in the destreg.
2312 Spills.ClobberPhysReg(VirtReg);
2313 ReusedOperands.markClobbered(VirtReg);
2315 // Check to see if this instruction is a load from a stack slot into
2316 // a register. If so, this provides the stack slot value in the reg.
2318 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2319 assert(DestReg == VirtReg && "Unknown load situation!");
2321 // If it is a folded reference, then it's not safe to clobber.
2322 bool Folded = FoldedSS.count(FrameIdx);
2323 // Otherwise, if it wasn't available, remember that it is now!
2324 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2325 goto ProcessNextInst;
2331 unsigned SubIdx = MO.getSubReg();
2332 bool DoReMat = VRM.isReMaterialized(VirtReg);
2334 ReMatDefs.insert(&MI);
2336 // The only vregs left are stack slot definitions.
2337 int StackSlot = VRM.getStackSlot(VirtReg);
2338 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2340 // If this def is part of a two-address operand, make sure to execute
2341 // the store from the correct physical register.
2344 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2345 PhysReg = MI.getOperand(TiedOp).getReg();
2347 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2348 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2349 "Can't find corresponding super-register!");
2353 PhysReg = VRM.getPhys(VirtReg);
2354 if (ReusedOperands.isClobbered(PhysReg)) {
2355 // Another def has taken the assigned physreg. It must have been a
2356 // use&def which got it due to reuse. Undo the reuse!
2357 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2358 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2362 assert(PhysReg && "VR not assigned a physical register?");
2363 RegInfo->setPhysRegUsed(PhysReg);
2364 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2365 ReusedOperands.markClobbered(RReg);
2366 MI.getOperand(i).setReg(RReg);
2367 MI.getOperand(i).setSubReg(0);
2370 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2371 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2372 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2373 NextMII = next(MII);
2375 // Check to see if this is a noop copy. If so, eliminate the
2376 // instruction before considering the dest reg to be changed.
2378 unsigned Src, Dst, SrcSR, DstSR;
2379 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2381 DEBUG(errs() << "Removing now-noop copy: " << MI);
2382 InvalidateKills(MI, TRI, RegKills, KillOps);
2383 VRM.RemoveMachineInstrFromMaps(&MI);
2386 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2387 goto ProcessNextInst;
2393 // Delete dead instructions without side effects.
2394 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2395 InvalidateKills(MI, TRI, RegKills, KillOps);
2396 VRM.RemoveMachineInstrFromMaps(&MI);
2401 DistanceMap.insert(std::make_pair(&MI, Dist++));
2402 if (!Erased && !BackTracked) {
2403 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2404 UpdateKills(*II, TRI, RegKills, KillOps);
2415 llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2416 switch (RewriterOpt) {
2417 default: llvm_unreachable("Unreachable!");
2419 return new LocalRewriter();
2421 return new TrivialRewriter();