1
//===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
#define DEBUG_TYPE "virtregrewriter"
11
#include "VirtRegRewriter.h"
12
#include "VirtRegMap.h"
13
#include "llvm/Function.h"
14
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
15
#include "llvm/CodeGen/MachineFrameInfo.h"
16
#include "llvm/CodeGen/MachineInstrBuilder.h"
17
#include "llvm/CodeGen/MachineRegisterInfo.h"
18
#include "llvm/Support/CommandLine.h"
19
#include "llvm/Support/Debug.h"
20
#include "llvm/Support/ErrorHandling.h"
21
#include "llvm/Support/raw_ostream.h"
22
#include "llvm/Target/TargetInstrInfo.h"
23
#include "llvm/Target/TargetLowering.h"
24
#include "llvm/ADT/DepthFirstIterator.h"
25
#include "llvm/ADT/Statistic.h"
29
STATISTIC(NumDSE , "Number of dead stores elided");
30
STATISTIC(NumDSS , "Number of dead spill slots removed");
31
STATISTIC(NumCommutes, "Number of instructions commuted");
32
STATISTIC(NumDRM , "Number of re-materializable defs elided");
33
STATISTIC(NumStores , "Number of stores added");
34
STATISTIC(NumPSpills , "Number of physical register spills");
35
STATISTIC(NumOmitted , "Number of reloads omited");
36
STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
37
STATISTIC(NumCopified, "Number of available reloads turned into copies");
38
STATISTIC(NumReMats , "Number of re-materialization");
39
STATISTIC(NumLoads , "Number of loads added");
40
STATISTIC(NumReused , "Number of values reused");
41
STATISTIC(NumDCE , "Number of copies elided");
42
STATISTIC(NumSUnfold , "Number of stores unfolded");
43
STATISTIC(NumModRefUnfold, "Number of modref unfolded");
46
enum RewriterName { local, trivial };
49
static cl::opt<RewriterName>
50
RewriterOpt("rewriter",
51
cl::desc("Rewriter to use (default=local)"),
53
cl::values(clEnumVal(local, "local rewriter"),
54
clEnumVal(trivial, "trivial rewriter"),
59
ScheduleSpills("schedule-spills",
60
cl::desc("Schedule spill code"),
63
VirtRegRewriter::~VirtRegRewriter() {}
65
/// substitutePhysReg - Replace virtual register in MachineOperand with a
66
/// physical register. Do the right thing with the sub-register index.
67
/// Note that operands may be added, so the MO reference is no longer valid.
68
static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
69
const TargetRegisterInfo &TRI) {
71
MO.substPhysReg(Reg, TRI);
73
// Any kill flags apply to the full virtual register, so they also apply to
74
// the full physical register.
75
// We assume that partial defs have already been decorated with a super-reg
76
// <imp-def> operand by LiveIntervals.
77
MachineInstr &MI = *MO.getParent();
78
if (MO.isUse() && !MO.isUndef() &&
79
(MO.isKill() || MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
80
MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
88
/// This class is intended for use with the new spilling framework only. It
89
/// rewrites vreg def/uses to use the assigned preg, but does not insert any
91
struct TrivialRewriter : public VirtRegRewriter {
93
bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
95
DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
96
DEBUG(dbgs() << "********** Function: "
97
<< MF.getFunction()->getName() << '\n');
98
DEBUG(dbgs() << "**** Machine Instrs"
99
<< "(NOTE! Does not include spills and reloads!) ****\n");
102
MachineRegisterInfo *mri = &MF.getRegInfo();
103
const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
105
bool changed = false;
107
for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
108
liItr != liEnd; ++liItr) {
110
const LiveInterval *li = liItr->second;
111
unsigned reg = li->reg;
113
if (TargetRegisterInfo::isPhysicalRegister(reg)) {
115
mri->setPhysRegUsed(reg);
118
if (!VRM.hasPhys(reg))
120
unsigned pReg = VRM.getPhys(reg);
121
mri->setPhysRegUsed(pReg);
122
// Copy the register use-list before traversing it.
123
SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
124
for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
125
E = mri->reg_end(); I != E; ++I)
126
reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
127
for (unsigned N=0; N != reglist.size(); ++N)
128
substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
130
changed |= !reglist.empty();
134
DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
144
// ************************************************************************ //
148
/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
149
/// from top down, keep track of which spill slots or remat are available in
152
/// Note that not all physregs are created equal here. In particular, some
153
/// physregs are reloads that we are allowed to clobber or ignore at any time.
154
/// Other physregs are values that the register allocated program is using
155
/// that we cannot CHANGE, but we can read if we like. We keep track of this
156
/// on a per-stack-slot / remat id basis as the low bit in the value of the
157
/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
158
/// this bit and addAvailable sets it if.
159
class AvailableSpills {
160
const TargetRegisterInfo *TRI;
161
const TargetInstrInfo *TII;
163
// SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
164
// or remat'ed virtual register values that are still available, due to
165
// being loaded or stored to, but not invalidated yet.
166
std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
168
// PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
169
// indicating which stack slot values are currently held by a physreg. This
170
// is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
171
// physreg is modified.
172
std::multimap<unsigned, int> PhysRegsAvailable;
174
void disallowClobberPhysRegOnly(unsigned PhysReg);
176
void ClobberPhysRegOnly(unsigned PhysReg);
178
AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
179
: TRI(tri), TII(tii) {
182
/// clear - Reset the state.
184
SpillSlotsOrReMatsAvailable.clear();
185
PhysRegsAvailable.clear();
188
const TargetRegisterInfo *getRegInfo() const { return TRI; }
190
/// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
191
/// available in a physical register, return that PhysReg, otherwise
193
unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
194
std::map<int, unsigned>::const_iterator I =
195
SpillSlotsOrReMatsAvailable.find(Slot);
196
if (I != SpillSlotsOrReMatsAvailable.end()) {
197
return I->second >> 1; // Remove the CanClobber bit.
202
/// addAvailable - Mark that the specified stack slot / remat is available
203
/// in the specified physreg. If CanClobber is true, the physreg can be
204
/// modified at any time without changing the semantics of the program.
205
void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
206
// If this stack slot is thought to be available in some other physreg,
207
// remove its record.
208
ModifyStackSlotOrReMat(SlotOrReMat);
210
PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
211
SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
212
(unsigned)CanClobber;
214
if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
215
DEBUG(dbgs() << "Remembering RM#"
216
<< SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
218
DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
219
DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
222
/// canClobberPhysRegForSS - Return true if the spiller is allowed to change
223
/// the value of the specified stackslot register if it desires. The
224
/// specified stack slot must be available in a physreg for this query to
226
bool canClobberPhysRegForSS(int SlotOrReMat) const {
227
assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
228
"Value not available!");
229
return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
232
/// canClobberPhysReg - Return true if the spiller is allowed to clobber the
233
/// physical register where values for some stack slot(s) might be
235
bool canClobberPhysReg(unsigned PhysReg) const {
236
std::multimap<unsigned, int>::const_iterator I =
237
PhysRegsAvailable.lower_bound(PhysReg);
238
while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
239
int SlotOrReMat = I->second;
241
if (!canClobberPhysRegForSS(SlotOrReMat))
247
/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
248
/// stackslot register. The register is still available but is no longer
249
/// allowed to be modifed.
250
void disallowClobberPhysReg(unsigned PhysReg);
252
/// ClobberPhysReg - This is called when the specified physreg changes
253
/// value. We use this to invalidate any info about stuff that lives in
254
/// it and any of its aliases.
255
void ClobberPhysReg(unsigned PhysReg);
257
/// ModifyStackSlotOrReMat - This method is called when the value in a stack
258
/// slot changes. This removes information about which register the
259
/// previous value for this slot lives in (as the previous value is dead
261
void ModifyStackSlotOrReMat(int SlotOrReMat);
263
/// AddAvailableRegsToLiveIn - Availability information is being kept coming
264
/// into the specified MBB. Add available physical registers as potential
265
/// live-in's. If they are reused in the MBB, they will be added to the
266
/// live-in set to make register scavenger and post-allocation scheduler.
267
void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
268
std::vector<MachineOperand*> &KillOps);
273
// ************************************************************************ //
275
// Given a location where a reload of a spilled register or a remat of
276
// a constant is to be inserted, attempt to find a safe location to
277
// insert the load at an earlier point in the basic-block, to hide
278
// latency of the load and to avoid address-generation interlock
280
static MachineBasicBlock::iterator
281
ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
282
MachineBasicBlock::iterator const Begin,
284
const TargetRegisterInfo *TRI,
287
const TargetInstrInfo *TII,
288
const MachineFunction &MF)
293
// Spill backscheduling is of primary interest to addresses, so
294
// don't do anything if the register isn't in the register class
295
// used for pointers.
297
const TargetLowering *TL = MF.getTarget().getTargetLowering();
299
if (!TL->isTypeLegal(TL->getPointerTy()))
300
// Believe it or not, this is true on PIC16.
303
const TargetRegisterClass *ptrRegClass =
304
TL->getRegClassFor(TL->getPointerTy());
305
if (!ptrRegClass->contains(PhysReg))
308
// Scan upwards through the preceding instructions. If an instruction doesn't
309
// reference the stack slot or the register we're loading, we can
310
// backschedule the reload up past it.
311
MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
312
while (NewInsertLoc != Begin) {
313
MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
314
for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
315
MachineOperand &Op = Prev->getOperand(i);
316
if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
319
if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
320
Prev->findRegisterDefOperand(PhysReg))
322
for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
323
if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
324
Prev->findRegisterDefOperand(*Alias))
330
// If we made it to the beginning of the block, turn around and move back
331
// down just past any existing reloads. They're likely to be reloads/remats
332
// for instructions earlier than what our current reload/remat is for, so
333
// they should be scheduled earlier.
334
if (NewInsertLoc == Begin) {
336
while (InsertLoc != NewInsertLoc &&
337
(TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
338
TII->isTriviallyReMaterializable(NewInsertLoc)))
347
// ReusedOp - For each reused operand, we keep track of a bit of information,
348
// in case we need to rollback upon processing a new operand. See comments
351
// The MachineInstr operand that reused an available value.
354
// StackSlotOrReMat - The spill slot or remat id of the value being reused.
355
unsigned StackSlotOrReMat;
357
// PhysRegReused - The physical register the value was available in.
358
unsigned PhysRegReused;
360
// AssignedPhysReg - The physreg that was assigned for use by the reload.
361
unsigned AssignedPhysReg;
363
// VirtReg - The virtual register itself.
366
ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
368
: Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
369
AssignedPhysReg(apr), VirtReg(vreg) {}
372
/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
373
/// is reused instead of reloaded.
376
std::vector<ReusedOp> Reuses;
377
BitVector PhysRegsClobbered;
379
ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
380
PhysRegsClobbered.resize(tri->getNumRegs());
383
bool hasReuses() const {
384
return !Reuses.empty();
387
/// addReuse - If we choose to reuse a virtual register that is already
388
/// available instead of reloading it, remember that we did so.
389
void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
390
unsigned PhysRegReused, unsigned AssignedPhysReg,
392
// If the reload is to the assigned register anyway, no undo will be
394
if (PhysRegReused == AssignedPhysReg) return;
396
// Otherwise, remember this.
397
Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
398
AssignedPhysReg, VirtReg));
401
void markClobbered(unsigned PhysReg) {
402
PhysRegsClobbered.set(PhysReg);
405
bool isClobbered(unsigned PhysReg) const {
406
return PhysRegsClobbered.test(PhysReg);
409
/// GetRegForReload - We are about to emit a reload into PhysReg. If there
410
/// is some other operand that is using the specified register, either pick
411
/// a new register to use, or evict the previous reload and use this reg.
412
unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
413
MachineFunction &MF, MachineInstr *MI,
414
AvailableSpills &Spills,
415
std::vector<MachineInstr*> &MaybeDeadStores,
416
SmallSet<unsigned, 8> &Rejected,
418
std::vector<MachineOperand*> &KillOps,
421
/// GetRegForReload - Helper for the above GetRegForReload(). Add a
422
/// 'Rejected' set to remember which registers have been considered and
423
/// rejected for the reload. This avoids infinite looping in case like
426
/// t2 <- assigned r0 for use by the reload but ended up reuse r1
427
/// t3 <- assigned r1 for use by the reload but ended up reuse r0
429
/// sees r1 is taken by t2, tries t2's reload register r0
430
/// sees r0 is taken by t3, tries t3's reload register r1
431
/// sees r1 is taken by t2, tries t2's reload register r0 ...
432
unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
433
AvailableSpills &Spills,
434
std::vector<MachineInstr*> &MaybeDeadStores,
436
std::vector<MachineOperand*> &KillOps,
438
SmallSet<unsigned, 8> Rejected;
439
MachineFunction &MF = *MI->getParent()->getParent();
440
const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
441
return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
442
Rejected, RegKills, KillOps, VRM);
448
// ****************** //
449
// Utility Functions //
450
// ****************** //
452
/// findSinglePredSuccessor - Return via reference a vector of machine basic
453
/// blocks each of which is a successor of the specified BB and has no other
455
static void findSinglePredSuccessor(MachineBasicBlock *MBB,
456
SmallVectorImpl<MachineBasicBlock *> &Succs){
457
for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
458
SE = MBB->succ_end(); SI != SE; ++SI) {
459
MachineBasicBlock *SuccMBB = *SI;
460
if (SuccMBB->pred_size() == 1)
461
Succs.push_back(SuccMBB);
465
/// InvalidateKill - Invalidate register kill information for a specific
466
/// register. This also unsets the kills marker on the last kill operand.
467
static void InvalidateKill(unsigned Reg,
468
const TargetRegisterInfo* TRI,
470
std::vector<MachineOperand*> &KillOps) {
472
KillOps[Reg]->setIsKill(false);
473
// KillOps[Reg] might be a def of a super-register.
474
unsigned KReg = KillOps[Reg]->getReg();
475
KillOps[KReg] = NULL;
476
RegKills.reset(KReg);
477
for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
479
KillOps[*SR]->setIsKill(false);
487
/// InvalidateKills - MI is going to be deleted. If any of its operands are
488
/// marked kill, then invalidate the information.
489
static void InvalidateKills(MachineInstr &MI,
490
const TargetRegisterInfo* TRI,
492
std::vector<MachineOperand*> &KillOps,
493
SmallVector<unsigned, 2> *KillRegs = NULL) {
494
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
495
MachineOperand &MO = MI.getOperand(i);
496
if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
498
unsigned Reg = MO.getReg();
499
if (TargetRegisterInfo::isVirtualRegister(Reg))
502
KillRegs->push_back(Reg);
503
assert(Reg < KillOps.size());
504
if (KillOps[Reg] == &MO) {
507
for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
517
/// InvalidateRegDef - If the def operand of the specified def MI is now dead
518
/// (since its spill instruction is removed), mark it isDead. Also checks if
519
/// the def MI has other definition operands that are not dead. Returns it by
521
static bool InvalidateRegDef(MachineBasicBlock::iterator I,
522
MachineInstr &NewDef, unsigned Reg,
524
const TargetRegisterInfo *TRI) {
525
// Due to remat, it's possible this reg isn't being reused. That is,
526
// the def of this reg (by prev MI) is now dead.
527
MachineInstr *DefMI = I;
528
MachineOperand *DefOp = NULL;
529
for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
530
MachineOperand &MO = DefMI->getOperand(i);
531
if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
533
if (MO.getReg() == Reg)
535
else if (!MO.isDead())
541
bool FoundUse = false, Done = false;
542
MachineBasicBlock::iterator E = &NewDef;
544
for (; !Done && I != E; ++I) {
545
MachineInstr *NMI = I;
546
for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
547
MachineOperand &MO = NMI->getOperand(j);
548
if (!MO.isReg() || MO.getReg() == 0 ||
549
(MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
553
Done = true; // Stop after scanning all the operands of this MI.
564
/// UpdateKills - Track and update kill info. If a MI reads a register that is
565
/// marked kill, then it must be due to register reuse. Transfer the kill info
567
static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
569
std::vector<MachineOperand*> &KillOps) {
570
// These do not affect kill info at all.
571
if (MI.isDebugValue())
573
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
574
MachineOperand &MO = MI.getOperand(i);
575
if (!MO.isReg() || !MO.isUse() || MO.isUndef())
577
unsigned Reg = MO.getReg();
581
if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
582
// That can't be right. Register is killed but not re-defined and it's
583
// being reused. Let's fix that.
584
KillOps[Reg]->setIsKill(false);
585
// KillOps[Reg] might be a def of a super-register.
586
unsigned KReg = KillOps[Reg]->getReg();
587
KillOps[KReg] = NULL;
588
RegKills.reset(KReg);
590
// Must be a def of a super-register. Its other sub-regsters are no
591
// longer killed as well.
592
for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
597
// Check for subreg kills as well.
603
// = d4 <avoiding reload>
604
for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
606
if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
607
KillOps[SReg]->setIsKill(false);
608
unsigned KReg = KillOps[SReg]->getReg();
609
KillOps[KReg] = NULL;
610
RegKills.reset(KReg);
612
for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
613
KillOps[*SSR] = NULL;
614
RegKills.reset(*SSR);
623
for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
630
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
631
const MachineOperand &MO = MI.getOperand(i);
632
if (!MO.isReg() || !MO.getReg() || !MO.isDef())
634
unsigned Reg = MO.getReg();
637
// It also defines (or partially define) aliases.
638
for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
642
for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
649
/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
651
static void ReMaterialize(MachineBasicBlock &MBB,
652
MachineBasicBlock::iterator &MII,
653
unsigned DestReg, unsigned Reg,
654
const TargetInstrInfo *TII,
655
const TargetRegisterInfo *TRI,
657
MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
659
const TargetInstrDesc &TID = ReMatDefMI->getDesc();
660
assert(TID.getNumDefs() == 1 &&
661
"Don't know how to remat instructions that define > 1 values!");
663
TII->reMaterialize(MBB, MII, DestReg, 0, ReMatDefMI, *TRI);
664
MachineInstr *NewMI = prior(MII);
665
for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
666
MachineOperand &MO = NewMI->getOperand(i);
667
if (!MO.isReg() || MO.getReg() == 0)
669
unsigned VirtReg = MO.getReg();
670
if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
673
unsigned Phys = VRM.getPhys(VirtReg);
674
assert(Phys && "Virtual register is not assigned a register?");
675
substitutePhysReg(MO, Phys, *TRI);
680
/// findSuperReg - Find the SubReg's super-register of given register class
681
/// where its SubIdx sub-register is SubReg.
682
static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
683
unsigned SubIdx, const TargetRegisterInfo *TRI) {
684
for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
687
if (TRI->getSubReg(Reg, SubIdx) == SubReg)
693
// ******************************** //
694
// Available Spills Implementation //
695
// ******************************** //
697
/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
698
/// stackslot register. The register is still available but is no longer
699
/// allowed to be modifed.
700
void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
701
std::multimap<unsigned, int>::iterator I =
702
PhysRegsAvailable.lower_bound(PhysReg);
703
while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
704
int SlotOrReMat = I->second;
706
assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
707
"Bidirectional map mismatch!");
708
SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
709
DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
710
<< " copied, it is available for use but can no longer be modified\n");
714
/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
715
/// stackslot register and its aliases. The register and its aliases may
716
/// still available but is no longer allowed to be modifed.
717
void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
718
for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
719
disallowClobberPhysRegOnly(*AS);
720
disallowClobberPhysRegOnly(PhysReg);
723
/// ClobberPhysRegOnly - This is called when the specified physreg changes
724
/// value. We use this to invalidate any info about stuff we thing lives in it.
725
void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
726
std::multimap<unsigned, int>::iterator I =
727
PhysRegsAvailable.lower_bound(PhysReg);
728
while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
729
int SlotOrReMat = I->second;
730
PhysRegsAvailable.erase(I++);
731
assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
732
"Bidirectional map mismatch!");
733
SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
734
DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
735
<< " clobbered, invalidating ");
736
if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
737
DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
739
DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
743
/// ClobberPhysReg - This is called when the specified physreg changes
744
/// value. We use this to invalidate any info about stuff we thing lives in
745
/// it and any of its aliases.
746
void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
747
for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
748
ClobberPhysRegOnly(*AS);
749
ClobberPhysRegOnly(PhysReg);
752
/// AddAvailableRegsToLiveIn - Availability information is being kept coming
753
/// into the specified MBB. Add available physical registers as potential
754
/// live-in's. If they are reused in the MBB, they will be added to the
755
/// live-in set to make register scavenger and post-allocation scheduler.
756
void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
758
std::vector<MachineOperand*> &KillOps) {
759
std::set<unsigned> NotAvailable;
760
for (std::multimap<unsigned, int>::iterator
761
I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
763
unsigned Reg = I->first;
764
const TargetRegisterClass* RC = TRI->getMinimalPhysRegClass(Reg);
765
// FIXME: A temporary workaround. We can't reuse available value if it's
766
// not safe to move the def of the virtual register's class. e.g.
767
// X86::RFP* register classes. Do not add it as a live-in.
768
if (!TII->isSafeToMoveRegClassDefs(RC))
769
// This is no longer available.
770
NotAvailable.insert(Reg);
773
InvalidateKill(Reg, TRI, RegKills, KillOps);
776
// Skip over the same register.
777
std::multimap<unsigned, int>::iterator NI = llvm::next(I);
778
while (NI != E && NI->first == Reg) {
784
for (std::set<unsigned>::iterator I = NotAvailable.begin(),
785
E = NotAvailable.end(); I != E; ++I) {
787
for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
789
ClobberPhysReg(*SubRegs);
793
/// ModifyStackSlotOrReMat - This method is called when the value in a stack
794
/// slot changes. This removes information about which register the previous
795
/// value for this slot lives in (as the previous value is dead now).
796
void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
797
std::map<int, unsigned>::iterator It =
798
SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
799
if (It == SpillSlotsOrReMatsAvailable.end()) return;
800
unsigned Reg = It->second >> 1;
801
SpillSlotsOrReMatsAvailable.erase(It);
803
// This register may hold the value of multiple stack slots, only remove this
804
// stack slot from the set of values the register contains.
805
std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
807
assert(I != PhysRegsAvailable.end() && I->first == Reg &&
808
"Map inverse broken!");
809
if (I->second == SlotOrReMat) break;
811
PhysRegsAvailable.erase(I);
814
// ************************** //
815
// Reuse Info Implementation //
816
// ************************** //
818
/// GetRegForReload - We are about to emit a reload into PhysReg. If there
819
/// is some other operand that is using the specified register, either pick
820
/// a new register to use, or evict the previous reload and use this reg.
821
unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
824
MachineInstr *MI, AvailableSpills &Spills,
825
std::vector<MachineInstr*> &MaybeDeadStores,
826
SmallSet<unsigned, 8> &Rejected,
828
std::vector<MachineOperand*> &KillOps,
830
const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
831
const TargetRegisterInfo *TRI = Spills.getRegInfo();
833
if (Reuses.empty()) return PhysReg; // This is most often empty.
835
for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
836
ReusedOp &Op = Reuses[ro];
837
// If we find some other reuse that was supposed to use this register
838
// exactly for its reload, we can change this reload to use ITS reload
839
// register. That is, unless its reload register has already been
840
// considered and subsequently rejected because it has also been reused
841
// by another operand.
842
if (Op.PhysRegReused == PhysReg &&
843
Rejected.count(Op.AssignedPhysReg) == 0 &&
844
RC->contains(Op.AssignedPhysReg)) {
845
// Yup, use the reload register that we didn't use before.
846
unsigned NewReg = Op.AssignedPhysReg;
847
Rejected.insert(PhysReg);
848
return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores,
849
Rejected, RegKills, KillOps, VRM);
851
// Otherwise, we might also have a problem if a previously reused
852
// value aliases the new register. If so, codegen the previous reload
854
unsigned PRRU = Op.PhysRegReused;
855
if (TRI->regsOverlap(PRRU, PhysReg)) {
856
// Okay, we found out that an alias of a reused register
857
// was used. This isn't good because it means we have
858
// to undo a previous reuse.
859
MachineBasicBlock *MBB = MI->getParent();
860
const TargetRegisterClass *AliasRC =
861
MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
863
// Copy Op out of the vector and remove it, we're going to insert an
864
// explicit load for it.
866
Reuses.erase(Reuses.begin()+ro);
868
// MI may be using only a sub-register of PhysRegUsed.
869
unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
871
assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
872
"A reuse cannot be a virtual register");
873
if (PRRU != RealPhysRegUsed) {
874
// What was the sub-register index?
875
SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
877
"Operand physreg is not a sub-register of PhysRegUsed");
880
// Ok, we're going to try to reload the assigned physreg into the
881
// slot that we were supposed to in the first place. However, that
882
// register could hold a reuse. Check to see if it conflicts or
883
// would prefer us to use a different register.
884
unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
885
MF, MI, Spills, MaybeDeadStores,
886
Rejected, RegKills, KillOps, VRM);
888
bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
889
int SSorRMId = DoReMat
890
? VRM.getReMatId(NewOp.VirtReg) : (int) NewOp.StackSlotOrReMat;
892
// Back-schedule reloads and remats.
893
MachineBasicBlock::iterator InsertLoc =
894
ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
895
DoReMat, SSorRMId, TII, MF);
898
ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
901
TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
902
NewOp.StackSlotOrReMat, AliasRC, TRI);
903
MachineInstr *LoadMI = prior(InsertLoc);
904
VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
905
// Any stores to this stack slot are not dead anymore.
906
MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
909
Spills.ClobberPhysReg(NewPhysReg);
910
Spills.ClobberPhysReg(NewOp.PhysRegReused);
912
unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
913
MI->getOperand(NewOp.Operand).setReg(RReg);
914
MI->getOperand(NewOp.Operand).setSubReg(0);
916
Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
917
UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
918
DEBUG(dbgs() << '\t' << *prior(InsertLoc));
920
DEBUG(dbgs() << "Reuse undone!\n");
923
// Finally, PhysReg is now available, go ahead and use it.
931
// ************************************************************************ //
933
/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
934
/// stack slot mod/ref. It also checks if it's possible to unfold the
935
/// instruction by having it define a specified physical register instead.
936
static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
937
const TargetInstrInfo *TII,
938
const TargetRegisterInfo *TRI,
940
if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
944
VirtRegMap::MI2VirtMapTy::const_iterator I, End;
945
for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
946
unsigned VirtReg = I->second.first;
947
VirtRegMap::ModRef MR = I->second.second;
948
if (MR & VirtRegMap::isModRef)
949
if (VRM.getStackSlot(VirtReg) == SS) {
950
Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
957
// Does the instruction uses a register that overlaps the scratch register?
958
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
959
MachineOperand &MO = MI.getOperand(i);
960
if (!MO.isReg() || MO.getReg() == 0)
962
unsigned Reg = MO.getReg();
963
if (TargetRegisterInfo::isVirtualRegister(Reg)) {
964
if (!VRM.hasPhys(Reg))
966
Reg = VRM.getPhys(Reg);
968
if (TRI->regsOverlap(PhysReg, Reg))
974
/// FindFreeRegister - Find a free register of a given register class by looking
975
/// at (at most) the last two machine instructions.
976
static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
977
MachineBasicBlock &MBB,
978
const TargetRegisterClass *RC,
979
const TargetRegisterInfo *TRI,
980
BitVector &AllocatableRegs) {
981
BitVector Defs(TRI->getNumRegs());
982
BitVector Uses(TRI->getNumRegs());
983
SmallVector<unsigned, 4> LocalUses;
984
SmallVector<unsigned, 4> Kills;
986
// Take a look at 2 instructions at most.
989
if (MII == MBB.begin())
991
MachineInstr *PrevMI = prior(MII);
994
if (PrevMI->isDebugValue())
995
continue; // Skip over dbg_value instructions.
998
for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
999
MachineOperand &MO = PrevMI->getOperand(i);
1000
if (!MO.isReg() || MO.getReg() == 0)
1002
unsigned Reg = MO.getReg();
1005
for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1008
LocalUses.push_back(Reg);
1009
if (MO.isKill() && AllocatableRegs[Reg])
1010
Kills.push_back(Reg);
1014
for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1015
unsigned Kill = Kills[i];
1016
if (!Defs[Kill] && !Uses[Kill] &&
1020
for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1021
unsigned Reg = LocalUses[i];
1023
for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1032
void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1033
const TargetRegisterInfo &TRI) {
1034
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035
MachineOperand &MO = MI->getOperand(i);
1036
if (MO.isReg() && MO.getReg() == VirtReg)
1037
substitutePhysReg(MO, PhysReg, TRI);
1044
bool operator()(const std::pair<MachineInstr*, int> &A,
1045
const std::pair<MachineInstr*, int> &B) {
1046
return A.second < B.second;
1050
// ***************************** //
1051
// Local Spiller Implementation //
1052
// ***************************** //
1054
class LocalRewriter : public VirtRegRewriter {
1055
MachineRegisterInfo *MRI;
1056
const TargetRegisterInfo *TRI;
1057
const TargetInstrInfo *TII;
1059
BitVector AllocatableRegs;
1060
DenseMap<MachineInstr*, unsigned> DistanceMap;
1061
DenseMap<int, SmallVector<MachineInstr*,4> > Slot2DbgValues;
1063
MachineBasicBlock *MBB; // Basic block currently being processed.
1067
bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1068
LiveIntervals* LIs);
1072
bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1073
MachineBasicBlock::iterator &MII,
1074
std::vector<MachineInstr*> &MaybeDeadStores,
1075
AvailableSpills &Spills,
1076
BitVector &RegKills,
1077
std::vector<MachineOperand*> &KillOps);
1079
bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1080
std::vector<MachineInstr*> &MaybeDeadStores,
1081
AvailableSpills &Spills,
1082
BitVector &RegKills,
1083
std::vector<MachineOperand*> &KillOps);
1085
bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1086
unsigned VirtReg, unsigned SrcReg, int SS,
1087
AvailableSpills &Spills,
1088
BitVector &RegKills,
1089
std::vector<MachineOperand*> &KillOps,
1090
const TargetRegisterInfo *TRI);
1092
void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1093
int Idx, unsigned PhysReg, int StackSlot,
1094
const TargetRegisterClass *RC,
1095
bool isAvailable, MachineInstr *&LastStore,
1096
AvailableSpills &Spills,
1097
SmallSet<MachineInstr*, 4> &ReMatDefs,
1098
BitVector &RegKills,
1099
std::vector<MachineOperand*> &KillOps);
1101
void TransferDeadness(unsigned Reg, BitVector &RegKills,
1102
std::vector<MachineOperand*> &KillOps);
1104
bool InsertEmergencySpills(MachineInstr *MI);
1106
bool InsertRestores(MachineInstr *MI,
1107
AvailableSpills &Spills,
1108
BitVector &RegKills,
1109
std::vector<MachineOperand*> &KillOps);
1111
bool InsertSpills(MachineInstr *MI);
1113
void RewriteMBB(LiveIntervals *LIs,
1114
AvailableSpills &Spills, BitVector &RegKills,
1115
std::vector<MachineOperand*> &KillOps);
1119
bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1120
LiveIntervals* LIs) {
1121
MRI = &MF.getRegInfo();
1122
TRI = MF.getTarget().getRegisterInfo();
1123
TII = MF.getTarget().getInstrInfo();
1125
AllocatableRegs = TRI->getAllocatableSet(MF);
1126
DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1127
<< MF.getFunction()->getName() << "':\n");
1128
DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1129
" reloads!) ****\n");
1132
// Spills - Keep track of which spilled values are available in physregs
1133
// so that we can choose to reuse the physregs instead of emitting
1134
// reloads. This is usually refreshed per basic block.
1135
AvailableSpills Spills(TRI, TII);
1137
// Keep track of kill information.
1138
BitVector RegKills(TRI->getNumRegs());
1139
std::vector<MachineOperand*> KillOps;
1140
KillOps.resize(TRI->getNumRegs(), NULL);
1142
// SingleEntrySuccs - Successor blocks which have a single predecessor.
1143
SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1144
SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1146
// Traverse the basic blocks depth first.
1147
MachineBasicBlock *Entry = MF.begin();
1148
SmallPtrSet<MachineBasicBlock*,16> Visited;
1149
for (df_ext_iterator<MachineBasicBlock*,
1150
SmallPtrSet<MachineBasicBlock*,16> >
1151
DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1154
if (!EarlyVisited.count(MBB))
1155
RewriteMBB(LIs, Spills, RegKills, KillOps);
1157
// If this MBB is the only predecessor of a successor. Keep the
1158
// availability information and visit it next.
1160
// Keep visiting single predecessor successor as long as possible.
1161
SinglePredSuccs.clear();
1162
findSinglePredSuccessor(MBB, SinglePredSuccs);
1163
if (SinglePredSuccs.empty())
1166
// FIXME: More than one successors, each of which has MBB has
1167
// the only predecessor.
1168
MBB = SinglePredSuccs[0];
1169
if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1170
Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1171
RewriteMBB(LIs, Spills, RegKills, KillOps);
1176
// Clear the availability info.
1180
DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1183
// Mark unused spill slots.
1184
MachineFrameInfo *MFI = MF.getFrameInfo();
1185
int SS = VRM->getLowSpillSlot();
1186
if (SS != VirtRegMap::NO_STACK_SLOT) {
1187
for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS) {
1188
SmallVector<MachineInstr*, 4> &DbgValues = Slot2DbgValues[SS];
1189
if (!VRM->isSpillSlotUsed(SS)) {
1190
MFI->RemoveStackObject(SS);
1191
for (unsigned j = 0, ee = DbgValues.size(); j != ee; ++j) {
1192
MachineInstr *DVMI = DbgValues[j];
1193
MachineBasicBlock *DVMBB = DVMI->getParent();
1194
DEBUG(dbgs() << "Removing debug info referencing FI#" << SS << '\n');
1195
VRM->RemoveMachineInstrFromMaps(DVMI);
1203
Slot2DbgValues.clear();
1208
/// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1209
/// a scratch register is available.
1210
/// xorq %r12<kill>, %r13
1211
/// addq %rax, -184(%rbp)
1212
/// addq %r13, -184(%rbp)
1214
/// xorq %r12<kill>, %r13
1215
/// movq -184(%rbp), %r12
1218
/// movq %r12, -184(%rbp)
1219
bool LocalRewriter::
1220
OptimizeByUnfold2(unsigned VirtReg, int SS,
1221
MachineBasicBlock::iterator &MII,
1222
std::vector<MachineInstr*> &MaybeDeadStores,
1223
AvailableSpills &Spills,
1224
BitVector &RegKills,
1225
std::vector<MachineOperand*> &KillOps) {
1227
MachineBasicBlock::iterator NextMII = llvm::next(MII);
1228
// Skip over dbg_value instructions.
1229
while (NextMII != MBB->end() && NextMII->isDebugValue())
1230
NextMII = llvm::next(NextMII);
1231
if (NextMII == MBB->end())
1234
if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1237
// Now let's see if the last couple of instructions happens to have freed up
1239
const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1240
unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1244
MachineFunction &MF = *MBB->getParent();
1245
TRI = MF.getTarget().getRegisterInfo();
1246
MachineInstr &MI = *MII;
1247
if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1250
// If the next instruction also folds the same SS modref and can be unfoled,
1251
// then it's worthwhile to issue a load from SS into the free register and
1252
// then unfold these instructions.
1253
if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1256
// Back-schedule reloads and remats.
1257
ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1259
// Load from SS to the spare physical register.
1260
TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC, TRI);
1261
// This invalidates Phys.
1262
Spills.ClobberPhysReg(PhysReg);
1263
// Remember it's available.
1264
Spills.addAvailable(SS, PhysReg);
1265
MaybeDeadStores[SS] = NULL;
1267
// Unfold current MI.
1268
SmallVector<MachineInstr*, 4> NewMIs;
1269
if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1270
llvm_unreachable("Unable unfold the load / store folding instruction!");
1271
assert(NewMIs.size() == 1);
1272
AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1273
VRM->transferRestorePts(&MI, NewMIs[0]);
1274
MII = MBB->insert(MII, NewMIs[0]);
1275
InvalidateKills(MI, TRI, RegKills, KillOps);
1276
VRM->RemoveMachineInstrFromMaps(&MI);
1280
// Unfold next instructions that fold the same SS.
1282
MachineInstr &NextMI = *NextMII;
1283
NextMII = llvm::next(NextMII);
1285
if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1286
llvm_unreachable("Unable unfold the load / store folding instruction!");
1287
assert(NewMIs.size() == 1);
1288
AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1289
VRM->transferRestorePts(&NextMI, NewMIs[0]);
1290
MBB->insert(NextMII, NewMIs[0]);
1291
InvalidateKills(NextMI, TRI, RegKills, KillOps);
1292
VRM->RemoveMachineInstrFromMaps(&NextMI);
1293
MBB->erase(&NextMI);
1295
// Skip over dbg_value instructions.
1296
while (NextMII != MBB->end() && NextMII->isDebugValue())
1297
NextMII = llvm::next(NextMII);
1298
if (NextMII == MBB->end())
1300
} while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1302
// Store the value back into SS.
1303
TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC, TRI);
1304
MachineInstr *StoreMI = prior(NextMII);
1305
VRM->addSpillSlotUse(SS, StoreMI);
1306
VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1311
/// OptimizeByUnfold - Turn a store folding instruction into a load folding
1312
/// instruction. e.g.
1314
/// movl %eax, -32(%ebp)
1315
/// movl -36(%ebp), %eax
1316
/// orl %eax, -32(%ebp)
1319
/// orl -36(%ebp), %eax
1320
/// mov %eax, -32(%ebp)
1321
/// This enables unfolding optimization for a subsequent instruction which will
1322
/// also eliminate the newly introduced store instruction.
1323
bool LocalRewriter::
1324
OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1325
std::vector<MachineInstr*> &MaybeDeadStores,
1326
AvailableSpills &Spills,
1327
BitVector &RegKills,
1328
std::vector<MachineOperand*> &KillOps) {
1329
MachineFunction &MF = *MBB->getParent();
1330
MachineInstr &MI = *MII;
1331
unsigned UnfoldedOpc = 0;
1332
unsigned UnfoldPR = 0;
1333
unsigned UnfoldVR = 0;
1334
int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1335
VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1336
for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1337
// Only transform a MI that folds a single register.
1340
UnfoldVR = I->second.first;
1341
VirtRegMap::ModRef MR = I->second.second;
1342
// MI2VirtMap be can updated which invalidate the iterator.
1343
// Increment the iterator first.
1345
if (VRM->isAssignedReg(UnfoldVR))
1347
// If this reference is not a use, any previous store is now dead.
1348
// Otherwise, the store to this stack slot is not dead anymore.
1349
FoldedSS = VRM->getStackSlot(UnfoldVR);
1350
MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1351
if (DeadStore && (MR & VirtRegMap::isModRef)) {
1352
unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1353
if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1356
UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1365
// Look for other unfolding opportunities.
1366
return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1370
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1371
MachineOperand &MO = MI.getOperand(i);
1372
if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1374
unsigned VirtReg = MO.getReg();
1375
if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1377
if (VRM->isAssignedReg(VirtReg)) {
1378
unsigned PhysReg = VRM->getPhys(VirtReg);
1379
if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1381
} else if (VRM->isReMaterialized(VirtReg))
1383
int SS = VRM->getStackSlot(VirtReg);
1384
unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1386
if (TRI->regsOverlap(PhysReg, UnfoldPR))
1390
if (VRM->hasPhys(VirtReg)) {
1391
PhysReg = VRM->getPhys(VirtReg);
1392
if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1396
// Ok, we'll need to reload the value into a register which makes
1397
// it impossible to perform the store unfolding optimization later.
1398
// Let's see if it is possible to fold the load if the store is
1399
// unfolded. This allows us to perform the store unfolding
1401
SmallVector<MachineInstr*, 4> NewMIs;
1402
if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1403
assert(NewMIs.size() == 1);
1404
MachineInstr *NewMI = NewMIs.back();
1405
MBB->insert(MII, NewMI);
1407
int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1409
SmallVector<unsigned, 1> Ops;
1411
MachineInstr *FoldedMI = TII->foldMemoryOperand(NewMI, Ops, SS);
1412
NewMI->eraseFromParent();
1414
VRM->addSpillSlotUse(SS, FoldedMI);
1415
if (!VRM->hasPhys(UnfoldVR))
1416
VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1417
VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1419
InvalidateKills(MI, TRI, RegKills, KillOps);
1420
VRM->RemoveMachineInstrFromMaps(&MI);
1430
/// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1431
/// where SrcReg is r1 and it is tied to r0. Return true if after
1432
/// commuting this instruction it will be r0 = op r2, r1.
1433
static bool CommuteChangesDestination(MachineInstr *DefMI,
1434
const TargetInstrDesc &TID,
1436
const TargetInstrInfo *TII,
1438
if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1440
if (!DefMI->getOperand(1).isReg() ||
1441
DefMI->getOperand(1).getReg() != SrcReg)
1444
if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1446
unsigned SrcIdx1, SrcIdx2;
1447
if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1449
if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1456
/// CommuteToFoldReload -
1459
/// r1 = op r1, r2<kill>
1462
/// If op is commutable and r2 is killed, then we can xform these to
1463
/// r2 = op r2, fi#1
1465
bool LocalRewriter::
1466
CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1467
unsigned VirtReg, unsigned SrcReg, int SS,
1468
AvailableSpills &Spills,
1469
BitVector &RegKills,
1470
std::vector<MachineOperand*> &KillOps,
1471
const TargetRegisterInfo *TRI) {
1472
if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1475
MachineInstr &MI = *MII;
1476
MachineBasicBlock::iterator DefMII = prior(MII);
1477
MachineInstr *DefMI = DefMII;
1478
const TargetInstrDesc &TID = DefMI->getDesc();
1480
if (DefMII != MBB->begin() &&
1481
TID.isCommutable() &&
1482
CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1483
MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1484
unsigned NewReg = NewDstMO.getReg();
1485
if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1487
MachineInstr *ReloadMI = prior(DefMII);
1489
unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1490
if (DestReg != SrcReg || FrameIdx != SS)
1492
int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1496
if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1498
assert(DefMI->getOperand(DefIdx).isReg() &&
1499
DefMI->getOperand(DefIdx).getReg() == SrcReg);
1501
// Now commute def instruction.
1502
MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1505
MBB->insert(MII, CommutedMI);
1506
SmallVector<unsigned, 1> Ops;
1507
Ops.push_back(NewDstIdx);
1508
MachineInstr *FoldedMI = TII->foldMemoryOperand(CommutedMI, Ops, SS);
1509
// Not needed since foldMemoryOperand returns new MI.
1510
CommutedMI->eraseFromParent();
1514
VRM->addSpillSlotUse(SS, FoldedMI);
1515
VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1516
// Insert new def MI and spill MI.
1517
const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1518
TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC, TRI);
1520
MachineInstr *StoreMI = MII;
1521
VRM->addSpillSlotUse(SS, StoreMI);
1522
VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1523
MII = FoldedMI; // Update MII to backtrack.
1525
// Delete all 3 old instructions.
1526
InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1527
VRM->RemoveMachineInstrFromMaps(ReloadMI);
1528
MBB->erase(ReloadMI);
1529
InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1530
VRM->RemoveMachineInstrFromMaps(DefMI);
1532
InvalidateKills(MI, TRI, RegKills, KillOps);
1533
VRM->RemoveMachineInstrFromMaps(&MI);
1536
// If NewReg was previously holding value of some SS, it's now clobbered.
1537
// This has to be done now because it's a physical register. When this
1538
// instruction is re-visited, it's ignored.
1539
Spills.ClobberPhysReg(NewReg);
1548
/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1549
/// the last store to the same slot is now dead. If so, remove the last store.
1550
void LocalRewriter::
1551
SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1552
int Idx, unsigned PhysReg, int StackSlot,
1553
const TargetRegisterClass *RC,
1554
bool isAvailable, MachineInstr *&LastStore,
1555
AvailableSpills &Spills,
1556
SmallSet<MachineInstr*, 4> &ReMatDefs,
1557
BitVector &RegKills,
1558
std::vector<MachineOperand*> &KillOps) {
1560
MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1561
TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC,
1563
MachineInstr *StoreMI = prior(oldNextMII);
1564
VRM->addSpillSlotUse(StackSlot, StoreMI);
1565
DEBUG(dbgs() << "Store:\t" << *StoreMI);
1567
// If there is a dead store to this stack slot, nuke it now.
1569
DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1571
SmallVector<unsigned, 2> KillRegs;
1572
InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1573
MachineBasicBlock::iterator PrevMII = LastStore;
1574
bool CheckDef = PrevMII != MBB->begin();
1577
VRM->RemoveMachineInstrFromMaps(LastStore);
1578
MBB->erase(LastStore);
1580
// Look at defs of killed registers on the store. Mark the defs
1581
// as dead since the store has been deleted and they aren't
1583
for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1584
bool HasOtherDef = false;
1585
if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1586
MachineInstr *DeadDef = PrevMII;
1587
if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1588
// FIXME: This assumes a remat def does not have side effects.
1589
VRM->RemoveMachineInstrFromMaps(DeadDef);
1590
MBB->erase(DeadDef);
1598
// Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1599
// the last of multiple instructions is the actual store.
1600
LastStore = prior(oldNextMII);
1602
// If the stack slot value was previously available in some other
1603
// register, change it now. Otherwise, make the register available,
1605
Spills.ModifyStackSlotOrReMat(StackSlot);
1606
Spills.ClobberPhysReg(PhysReg);
1607
Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1611
/// isSafeToDelete - Return true if this instruction doesn't produce any side
1612
/// effect and all of its defs are dead.
1613
static bool isSafeToDelete(MachineInstr &MI) {
1614
const TargetInstrDesc &TID = MI.getDesc();
1615
if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1616
TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1617
TID.hasUnmodeledSideEffects())
1619
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1620
MachineOperand &MO = MI.getOperand(i);
1621
if (!MO.isReg() || !MO.getReg())
1623
if (MO.isDef() && !MO.isDead())
1625
if (MO.isUse() && MO.isKill())
1626
// FIXME: We can't remove kill markers or else the scavenger will assert.
1627
// An alternative is to add a ADD pseudo instruction to replace kill
1634
/// TransferDeadness - A identity copy definition is dead and it's being
1635
/// removed. Find the last def or use and mark it as dead / kill.
1636
void LocalRewriter::
1637
TransferDeadness(unsigned Reg, BitVector &RegKills,
1638
std::vector<MachineOperand*> &KillOps) {
1639
SmallPtrSet<MachineInstr*, 4> Seens;
1640
SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1641
for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1642
RE = MRI->reg_end(); RI != RE; ++RI) {
1643
MachineInstr *UDMI = &*RI;
1644
if (UDMI->isDebugValue() || UDMI->getParent() != MBB)
1646
DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1647
if (DI == DistanceMap.end())
1649
if (Seens.insert(UDMI))
1650
Refs.push_back(std::make_pair(UDMI, DI->second));
1655
std::sort(Refs.begin(), Refs.end(), RefSorter());
1657
while (!Refs.empty()) {
1658
MachineInstr *LastUDMI = Refs.back().first;
1661
MachineOperand *LastUD = NULL;
1662
for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1663
MachineOperand &MO = LastUDMI->getOperand(i);
1664
if (!MO.isReg() || MO.getReg() != Reg)
1666
if (!LastUD || (LastUD->isUse() && MO.isDef()))
1668
if (LastUDMI->isRegTiedToDefOperand(i))
1671
if (LastUD->isDef()) {
1672
// If the instruction has no side effect, delete it and propagate
1673
// backward further. Otherwise, mark is dead and we are done.
1674
if (!isSafeToDelete(*LastUDMI)) {
1675
LastUD->setIsDead();
1678
VRM->RemoveMachineInstrFromMaps(LastUDMI);
1679
MBB->erase(LastUDMI);
1681
LastUD->setIsKill();
1683
KillOps[Reg] = LastUD;
1689
/// InsertEmergencySpills - Insert emergency spills before MI if requested by
1690
/// VRM. Return true if spills were inserted.
1691
bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1692
if (!VRM->hasEmergencySpills(MI))
1694
MachineBasicBlock::iterator MII = MI;
1695
SmallSet<int, 4> UsedSS;
1696
std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1697
for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1698
unsigned PhysReg = EmSpills[i];
1699
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(PhysReg);
1700
assert(RC && "Unable to determine register class!");
1701
int SS = VRM->getEmergencySpillSlot(RC);
1702
if (UsedSS.count(SS))
1703
llvm_unreachable("Need to spill more than one physical registers!");
1705
TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC, TRI);
1706
MachineInstr *StoreMI = prior(MII);
1707
VRM->addSpillSlotUse(SS, StoreMI);
1709
// Back-schedule reloads and remats.
1710
MachineBasicBlock::iterator InsertLoc =
1711
ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1712
TII, *MBB->getParent());
1714
TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC, TRI);
1716
MachineInstr *LoadMI = prior(InsertLoc);
1717
VRM->addSpillSlotUse(SS, LoadMI);
1719
DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1724
/// InsertRestores - Restore registers before MI is requested by VRM. Return
1725
/// true is any instructions were inserted.
1726
bool LocalRewriter::InsertRestores(MachineInstr *MI,
1727
AvailableSpills &Spills,
1728
BitVector &RegKills,
1729
std::vector<MachineOperand*> &KillOps) {
1730
if (!VRM->isRestorePt(MI))
1732
MachineBasicBlock::iterator MII = MI;
1733
std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1734
for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1735
unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1736
if (!VRM->getPreSplitReg(VirtReg))
1737
continue; // Split interval spilled again.
1738
unsigned Phys = VRM->getPhys(VirtReg);
1739
MRI->setPhysRegUsed(Phys);
1741
// Check if the value being restored if available. If so, it must be
1742
// from a predecessor BB that fallthrough into this BB. We do not
1748
// ... # r1 not clobbered
1751
bool DoReMat = VRM->isReMaterialized(VirtReg);
1752
int SSorRMId = DoReMat
1753
? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1754
unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1755
if (InReg == Phys) {
1756
// If the value is already available in the expected register, save
1757
// a reload / remat.
1759
DEBUG(dbgs() << "Reusing RM#"
1760
<< SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1762
DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1763
DEBUG(dbgs() << " from physreg "
1764
<< TRI->getName(InReg) << " for vreg"
1765
<< VirtReg <<" instead of reloading into physreg "
1766
<< TRI->getName(Phys) << '\n');
1769
} else if (InReg && InReg != Phys) {
1771
DEBUG(dbgs() << "Reusing RM#"
1772
<< SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1774
DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1775
DEBUG(dbgs() << " from physreg "
1776
<< TRI->getName(InReg) << " for vreg"
1777
<< VirtReg <<" by copying it into physreg "
1778
<< TRI->getName(Phys) << '\n');
1780
// If the reloaded / remat value is available in another register,
1781
// copy it to the desired register.
1783
// Back-schedule reloads and remats.
1784
MachineBasicBlock::iterator InsertLoc =
1785
ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1787
MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI->getDebugLoc(),
1788
TII->get(TargetOpcode::COPY), Phys)
1789
.addReg(InReg, RegState::Kill);
1791
// This invalidates Phys.
1792
Spills.ClobberPhysReg(Phys);
1793
// Remember it's available.
1794
Spills.addAvailable(SSorRMId, Phys);
1796
CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1797
UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1799
DEBUG(dbgs() << '\t' << *CopyMI);
1804
// Back-schedule reloads and remats.
1805
MachineBasicBlock::iterator InsertLoc =
1806
ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1809
if (VRM->isReMaterialized(VirtReg)) {
1810
ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1812
const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1813
TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC, TRI);
1814
MachineInstr *LoadMI = prior(InsertLoc);
1815
VRM->addSpillSlotUse(SSorRMId, LoadMI);
1817
DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1820
// This invalidates Phys.
1821
Spills.ClobberPhysReg(Phys);
1822
// Remember it's available.
1823
Spills.addAvailable(SSorRMId, Phys);
1825
UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1826
DEBUG(dbgs() << '\t' << *prior(MII));
1831
/// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1832
/// true if spills were inserted.
1833
bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1834
if (!VRM->isSpillPt(MI))
1836
MachineBasicBlock::iterator MII = MI;
1837
std::vector<std::pair<unsigned,bool> > &SpillRegs =
1838
VRM->getSpillPtSpills(MI);
1839
for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1840
unsigned VirtReg = SpillRegs[i].first;
1841
bool isKill = SpillRegs[i].second;
1842
if (!VRM->getPreSplitReg(VirtReg))
1843
continue; // Split interval spilled again.
1844
const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1845
unsigned Phys = VRM->getPhys(VirtReg);
1846
int StackSlot = VRM->getStackSlot(VirtReg);
1847
MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1848
TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1850
MachineInstr *StoreMI = prior(oldNextMII);
1851
VRM->addSpillSlotUse(StackSlot, StoreMI);
1852
DEBUG(dbgs() << "Store:\t" << *StoreMI);
1853
VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1859
/// rewriteMBB - Keep track of which spills are available even after the
1860
/// register allocator is done with them. If possible, avoid reloading vregs.
1862
LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1863
AvailableSpills &Spills, BitVector &RegKills,
1864
std::vector<MachineOperand*> &KillOps) {
1866
DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1867
<< MBB->getName() << "':\n");
1869
MachineFunction &MF = *MBB->getParent();
1871
// MaybeDeadStores - When we need to write a value back into a stack slot,
1872
// keep track of the inserted store. If the stack slot value is never read
1873
// (because the value was used from some available register, for example), and
1874
// subsequently stored to, the original store is dead. This map keeps track
1875
// of inserted stores that are not used. If we see a subsequent store to the
1876
// same stack slot, the original store is deleted.
1877
std::vector<MachineInstr*> MaybeDeadStores;
1878
MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1880
// ReMatDefs - These are rematerializable def MIs which are not deleted.
1881
SmallSet<MachineInstr*, 4> ReMatDefs;
1884
SmallSet<unsigned, 2> KilledMIRegs;
1886
// Keep track of the registers we have already spilled in case there are
1887
// multiple defs of the same register in MI.
1888
SmallSet<unsigned, 8> SpilledMIRegs;
1892
KillOps.resize(TRI->getNumRegs(), NULL);
1894
DistanceMap.clear();
1895
for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1897
MachineBasicBlock::iterator NextMII = llvm::next(MII);
1899
if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1900
NextMII = llvm::next(MII);
1902
if (InsertEmergencySpills(MII))
1903
NextMII = llvm::next(MII);
1905
InsertRestores(MII, Spills, RegKills, KillOps);
1907
if (InsertSpills(MII))
1908
NextMII = llvm::next(MII);
1910
bool Erased = false;
1911
bool BackTracked = false;
1912
MachineInstr &MI = *MII;
1914
// Remember DbgValue's which reference stack slots.
1915
if (MI.isDebugValue() && MI.getOperand(0).isFI())
1916
Slot2DbgValues[MI.getOperand(0).getIndex()].push_back(&MI);
1918
/// ReusedOperands - Keep track of operand reuse in case we need to undo
1920
ReuseInfo ReusedOperands(MI, TRI);
1921
SmallVector<unsigned, 4> VirtUseOps;
1922
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1923
MachineOperand &MO = MI.getOperand(i);
1924
if (!MO.isReg() || MO.getReg() == 0)
1925
continue; // Ignore non-register operands.
1927
unsigned VirtReg = MO.getReg();
1928
if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1929
// Ignore physregs for spilling, but remember that it is used by this
1931
MRI->setPhysRegUsed(VirtReg);
1935
// We want to process implicit virtual register uses first.
1936
if (MO.isImplicit())
1937
// If the virtual register is implicitly defined, emit a implicit_def
1938
// before so scavenger knows it's "defined".
1939
// FIXME: This is a horrible hack done the by register allocator to
1940
// remat a definition with virtual register operand.
1941
VirtUseOps.insert(VirtUseOps.begin(), i);
1943
VirtUseOps.push_back(i);
1946
// Process all of the spilled uses and all non spilled reg references.
1947
SmallVector<int, 2> PotentialDeadStoreSlots;
1948
KilledMIRegs.clear();
1949
for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1950
unsigned i = VirtUseOps[j];
1951
unsigned VirtReg = MI.getOperand(i).getReg();
1952
assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1953
"Not a virtual register?");
1955
unsigned SubIdx = MI.getOperand(i).getSubReg();
1956
if (VRM->isAssignedReg(VirtReg)) {
1957
// This virtual register was assigned a physreg!
1958
unsigned Phys = VRM->getPhys(VirtReg);
1959
MRI->setPhysRegUsed(Phys);
1960
if (MI.getOperand(i).isDef())
1961
ReusedOperands.markClobbered(Phys);
1962
substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1963
if (VRM->isImplicitlyDefined(VirtReg))
1964
// FIXME: Is this needed?
1965
BuildMI(*MBB, &MI, MI.getDebugLoc(),
1966
TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1970
// This virtual register is now known to be a spilled value.
1971
if (!MI.getOperand(i).isUse())
1972
continue; // Handle defs in the loop below (handle use&def here though)
1974
bool AvoidReload = MI.getOperand(i).isUndef();
1975
// Check if it is defined by an implicit def. It should not be spilled.
1976
// Note, this is for correctness reason. e.g.
1977
// 8 %reg1024<def> = IMPLICIT_DEF
1978
// 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1979
// The live range [12, 14) are not part of the r1024 live interval since
1980
// it's defined by an implicit def. It will not conflicts with live
1981
// interval of r1025. Now suppose both registers are spilled, you can
1982
// easily see a situation where both registers are reloaded before
1983
// the INSERT_SUBREG and both target registers that would overlap.
1984
bool DoReMat = VRM->isReMaterialized(VirtReg);
1985
int SSorRMId = DoReMat
1986
? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1987
int ReuseSlot = SSorRMId;
1989
// Check to see if this stack slot is available.
1990
unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1992
// If this is a sub-register use, make sure the reuse register is in the
1993
// right register class. For example, for x86 not all of the 32-bit
1994
// registers have accessible sub-registers.
1995
// Similarly so for EXTRACT_SUBREG. Consider this:
1997
// MOV32_mr fi#1, EDI
1999
// = EXTRACT_SUBREG fi#1
2000
// fi#1 is available in EDI, but it cannot be reused because it's not in
2001
// the right register file.
2002
if (PhysReg && !AvoidReload && SubIdx) {
2003
const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2004
if (!RC->contains(PhysReg))
2008
if (PhysReg && !AvoidReload) {
2009
// This spilled operand might be part of a two-address operand. If this
2010
// is the case, then changing it will necessarily require changing the
2011
// def part of the instruction as well. However, in some cases, we
2012
// aren't allowed to modify the reused register. If none of these cases
2014
bool CanReuse = true;
2015
bool isTied = MI.isRegTiedToDefOperand(i);
2017
// Okay, we have a two address operand. We can reuse this physreg as
2018
// long as we are allowed to clobber the value and there isn't an
2019
// earlier def that has already clobbered the physreg.
2020
CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
2021
Spills.canClobberPhysReg(PhysReg);
2023
// If this is an asm, and a PhysReg alias is used elsewhere as an
2024
// earlyclobber operand, we can't also use it as an input.
2025
if (MI.isInlineAsm()) {
2026
for (unsigned k = 0, e = MI.getNumOperands(); k != e; ++k) {
2027
MachineOperand &MOk = MI.getOperand(k);
2028
if (MOk.isReg() && MOk.isEarlyClobber() &&
2029
TRI->regsOverlap(MOk.getReg(), PhysReg)) {
2031
DEBUG(dbgs() << "Not reusing physreg " << TRI->getName(PhysReg)
2032
<< " for vreg" << VirtReg << ": " << MOk << '\n');
2039
// If this stack slot value is already available, reuse it!
2040
if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2041
DEBUG(dbgs() << "Reusing RM#"
2042
<< ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2044
DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2045
DEBUG(dbgs() << " from physreg "
2046
<< TRI->getName(PhysReg) << " for vreg"
2047
<< VirtReg <<" instead of reloading into physreg "
2048
<< TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2049
unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2050
MI.getOperand(i).setReg(RReg);
2051
MI.getOperand(i).setSubReg(0);
2053
// The only technical detail we have is that we don't know that
2054
// PhysReg won't be clobbered by a reloaded stack slot that occurs
2055
// later in the instruction. In particular, consider 'op V1, V2'.
2056
// If V1 is available in physreg R0, we would choose to reuse it
2057
// here, instead of reloading it into the register the allocator
2058
// indicated (say R1). However, V2 might have to be reloaded
2059
// later, and it might indicate that it needs to live in R0. When
2060
// this occurs, we need to have information available that
2061
// indicates it is safe to use R1 for the reload instead of R0.
2063
// To further complicate matters, we might conflict with an alias,
2064
// or R0 and R1 might not be compatible with each other. In this
2065
// case, we actually insert a reload for V1 in R1, ensuring that
2066
// we can get at R0 or its alias.
2067
ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2068
VRM->getPhys(VirtReg), VirtReg);
2070
// Only mark it clobbered if this is a use&def operand.
2071
ReusedOperands.markClobbered(PhysReg);
2074
if (MI.getOperand(i).isKill() &&
2075
ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2077
// The store of this spilled value is potentially dead, but we
2078
// won't know for certain until we've confirmed that the re-use
2079
// above is valid, which means waiting until the other operands
2080
// are processed. For now we just track the spill slot, we'll
2081
// remove it after the other operands are processed if valid.
2083
PotentialDeadStoreSlots.push_back(ReuseSlot);
2086
// Mark is isKill if it's there no other uses of the same virtual
2087
// register and it's not a two-address operand. IsKill will be
2088
// unset if reg is reused.
2089
if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2090
MI.getOperand(i).setIsKill();
2091
KilledMIRegs.insert(VirtReg);
2097
// Otherwise we have a situation where we have a two-address instruction
2098
// whose mod/ref operand needs to be reloaded. This reload is already
2099
// available in some register "PhysReg", but if we used PhysReg as the
2100
// operand to our 2-addr instruction, the instruction would modify
2101
// PhysReg. This isn't cool if something later uses PhysReg and expects
2102
// to get its initial value.
2104
// To avoid this problem, and to avoid doing a load right after a store,
2105
// we emit a copy from PhysReg into the designated register for this
2108
// This case also applies to an earlyclobber'd PhysReg.
2109
unsigned DesignatedReg = VRM->getPhys(VirtReg);
2110
assert(DesignatedReg && "Must map virtreg to physreg!");
2112
// Note that, if we reused a register for a previous operand, the
2113
// register we want to reload into might not actually be
2114
// available. If this occurs, use the register indicated by the
2116
if (ReusedOperands.hasReuses())
2117
DesignatedReg = ReusedOperands.
2118
GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2119
MaybeDeadStores, RegKills, KillOps, *VRM);
2121
// If the mapped designated register is actually the physreg we have
2122
// incoming, we don't need to inserted a dead copy.
2123
if (DesignatedReg == PhysReg) {
2124
// If this stack slot value is already available, reuse it!
2125
if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2126
DEBUG(dbgs() << "Reusing RM#"
2127
<< ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2129
DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2130
DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2131
<< " for vreg" << VirtReg
2132
<< " instead of reloading into same physreg.\n");
2133
unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2134
MI.getOperand(i).setReg(RReg);
2135
MI.getOperand(i).setSubReg(0);
2136
ReusedOperands.markClobbered(RReg);
2141
MRI->setPhysRegUsed(DesignatedReg);
2142
ReusedOperands.markClobbered(DesignatedReg);
2144
// Back-schedule reloads and remats.
2145
MachineBasicBlock::iterator InsertLoc =
2146
ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2148
MachineInstr *CopyMI = BuildMI(*MBB, InsertLoc, MI.getDebugLoc(),
2149
TII->get(TargetOpcode::COPY),
2150
DesignatedReg).addReg(PhysReg);
2151
CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2152
UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2154
// This invalidates DesignatedReg.
2155
Spills.ClobberPhysReg(DesignatedReg);
2157
Spills.addAvailable(ReuseSlot, DesignatedReg);
2159
SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2160
MI.getOperand(i).setReg(RReg);
2161
MI.getOperand(i).setSubReg(0);
2162
DEBUG(dbgs() << '\t' << *prior(MII));
2167
// Otherwise, reload it and remember that we have it.
2168
PhysReg = VRM->getPhys(VirtReg);
2169
assert(PhysReg && "Must map virtreg to physreg!");
2171
// Note that, if we reused a register for a previous operand, the
2172
// register we want to reload into might not actually be
2173
// available. If this occurs, use the register indicated by the
2175
if (ReusedOperands.hasReuses())
2176
PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2177
Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2179
MRI->setPhysRegUsed(PhysReg);
2180
ReusedOperands.markClobbered(PhysReg);
2184
// Back-schedule reloads and remats.
2185
MachineBasicBlock::iterator InsertLoc =
2186
ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2190
ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2192
const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2193
TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC,TRI);
2194
MachineInstr *LoadMI = prior(InsertLoc);
2195
VRM->addSpillSlotUse(SSorRMId, LoadMI);
2197
DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
2199
// This invalidates PhysReg.
2200
Spills.ClobberPhysReg(PhysReg);
2202
// Any stores to this stack slot are not dead anymore.
2204
MaybeDeadStores[SSorRMId] = NULL;
2205
Spills.addAvailable(SSorRMId, PhysReg);
2206
// Assumes this is the last use. IsKill will be unset if reg is reused
2207
// unless it's a two-address operand.
2208
if (!MI.isRegTiedToDefOperand(i) &&
2209
KilledMIRegs.count(VirtReg) == 0) {
2210
MI.getOperand(i).setIsKill();
2211
KilledMIRegs.insert(VirtReg);
2214
UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2215
DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2217
unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2218
MI.getOperand(i).setReg(RReg);
2219
MI.getOperand(i).setSubReg(0);
2222
// Ok - now we can remove stores that have been confirmed dead.
2223
for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2224
// This was the last use and the spilled value is still available
2225
// for reuse. That means the spill was unnecessary!
2226
int PDSSlot = PotentialDeadStoreSlots[j];
2227
MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2229
DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2230
InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2231
VRM->RemoveMachineInstrFromMaps(DeadStore);
2232
MBB->erase(DeadStore);
2233
MaybeDeadStores[PDSSlot] = NULL;
2239
DEBUG(dbgs() << '\t' << MI);
2242
// If we have folded references to memory operands, make sure we clear all
2243
// physical registers that may contain the value of the spilled virtual
2246
// Copy the folded virts to a small vector, we may change MI2VirtMap.
2247
SmallVector<std::pair<unsigned, VirtRegMap::ModRef>, 4> FoldedVirts;
2249
for (std::pair<VirtRegMap::MI2VirtMapTy::const_iterator,
2250
VirtRegMap::MI2VirtMapTy::const_iterator> FVRange =
2251
VRM->getFoldedVirts(&MI);
2252
FVRange.first != FVRange.second; ++FVRange.first)
2253
FoldedVirts.push_back(FVRange.first->second);
2255
SmallSet<int, 2> FoldedSS;
2256
for (unsigned FVI = 0, FVE = FoldedVirts.size(); FVI != FVE; ++FVI) {
2257
unsigned VirtReg = FoldedVirts[FVI].first;
2258
VirtRegMap::ModRef MR = FoldedVirts[FVI].second;
2259
DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2261
int SS = VRM->getStackSlot(VirtReg);
2262
if (SS == VirtRegMap::NO_STACK_SLOT)
2264
FoldedSS.insert(SS);
2265
DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2267
// If this folded instruction is just a use, check to see if it's a
2268
// straight load from the virt reg slot.
2269
if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2271
unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2272
if (DestReg && FrameIdx == SS) {
2273
// If this spill slot is available, turn it into a copy (or nothing)
2274
// instead of leaving it as a load!
2275
if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2276
DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2277
if (DestReg != InReg) {
2278
MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2279
MachineInstr *CopyMI = BuildMI(*MBB, &MI, MI.getDebugLoc(),
2280
TII->get(TargetOpcode::COPY))
2281
.addReg(DestReg, RegState::Define, DefMO->getSubReg())
2282
.addReg(InReg, RegState::Kill);
2283
// Revisit the copy so we make sure to notice the effects of the
2284
// operation on the destreg (either needing to RA it if it's
2285
// virtual or needing to clobber any values if it's physical).
2287
NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2290
DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2291
// Unset last kill since it's being reused.
2292
InvalidateKill(InReg, TRI, RegKills, KillOps);
2293
Spills.disallowClobberPhysReg(InReg);
2296
InvalidateKills(MI, TRI, RegKills, KillOps);
2297
VRM->RemoveMachineInstrFromMaps(&MI);
2300
goto ProcessNextInst;
2303
unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2304
SmallVector<MachineInstr*, 4> NewMIs;
2306
TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)){
2307
MBB->insert(MII, NewMIs[0]);
2308
InvalidateKills(MI, TRI, RegKills, KillOps);
2309
VRM->RemoveMachineInstrFromMaps(&MI);
2312
--NextMII; // backtrack to the unfolded instruction.
2314
goto ProcessNextInst;
2319
// If this reference is not a use, any previous store is now dead.
2320
// Otherwise, the store to this stack slot is not dead anymore.
2321
MachineInstr* DeadStore = MaybeDeadStores[SS];
2323
bool isDead = !(MR & VirtRegMap::isRef);
2324
MachineInstr *NewStore = NULL;
2325
if (MR & VirtRegMap::isModRef) {
2326
unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2327
SmallVector<MachineInstr*, 4> NewMIs;
2328
// We can reuse this physreg as long as we are allowed to clobber
2329
// the value and there isn't an earlier def that has already clobbered
2332
!ReusedOperands.isClobbered(PhysReg) &&
2333
Spills.canClobberPhysReg(PhysReg) &&
2334
!TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2335
MachineOperand *KillOpnd =
2336
DeadStore->findRegisterUseOperand(PhysReg, true);
2337
// Note, if the store is storing a sub-register, it's possible the
2338
// super-register is needed below.
2339
if (KillOpnd && !KillOpnd->getSubReg() &&
2340
TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2341
MBB->insert(MII, NewMIs[0]);
2342
NewStore = NewMIs[1];
2343
MBB->insert(MII, NewStore);
2344
VRM->addSpillSlotUse(SS, NewStore);
2345
InvalidateKills(MI, TRI, RegKills, KillOps);
2346
VRM->RemoveMachineInstrFromMaps(&MI);
2350
--NextMII; // backtrack to the unfolded instruction.
2358
if (isDead) { // Previous store is dead.
2359
// If we get here, the store is dead, nuke it now.
2360
DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2361
InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2362
VRM->RemoveMachineInstrFromMaps(DeadStore);
2363
MBB->erase(DeadStore);
2368
MaybeDeadStores[SS] = NULL;
2370
// Treat this store as a spill merged into a copy. That makes the
2371
// stack slot value available.
2372
VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2373
goto ProcessNextInst;
2377
// If the spill slot value is available, and this is a new definition of
2378
// the value, the value is not available anymore.
2379
if (MR & VirtRegMap::isMod) {
2380
// Notice that the value in this stack slot has been modified.
2381
Spills.ModifyStackSlotOrReMat(SS);
2383
// If this is *just* a mod of the value, check to see if this is just a
2384
// store to the spill slot (i.e. the spill got merged into the copy). If
2385
// so, realize that the vreg is available now, and add the store to the
2386
// MaybeDeadStore info.
2388
if (!(MR & VirtRegMap::isRef)) {
2389
if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2390
assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2391
"Src hasn't been allocated yet?");
2393
if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2394
Spills, RegKills, KillOps, TRI)) {
2395
NextMII = llvm::next(MII);
2397
goto ProcessNextInst;
2400
// Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2401
// this as a potentially dead store in case there is a subsequent
2402
// store into the stack slot without a read from it.
2403
MaybeDeadStores[StackSlot] = &MI;
2405
// If the stack slot value was previously available in some other
2406
// register, change it now. Otherwise, make the register
2407
// available in PhysReg.
2408
Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2414
// Process all of the spilled defs.
2415
SpilledMIRegs.clear();
2416
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2417
MachineOperand &MO = MI.getOperand(i);
2418
if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2421
unsigned VirtReg = MO.getReg();
2422
if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2423
// Check to see if this is a noop copy. If so, eliminate the
2424
// instruction before considering the dest reg to be changed.
2425
// Also check if it's copying from an "undef", if so, we can't
2426
// eliminate this or else the undef marker is lost and it will
2427
// confuses the scavenger. This is extremely rare.
2428
if (MI.isIdentityCopy() && !MI.getOperand(1).isUndef() &&
2429
MI.getNumOperands() == 2) {
2431
DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2432
SmallVector<unsigned, 2> KillRegs;
2433
InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2434
if (MO.isDead() && !KillRegs.empty()) {
2435
// Source register or an implicit super/sub-register use is killed.
2436
assert(TRI->regsOverlap(KillRegs[0], MI.getOperand(0).getReg()));
2437
// Last def is now dead.
2438
TransferDeadness(MI.getOperand(1).getReg(), RegKills, KillOps);
2440
VRM->RemoveMachineInstrFromMaps(&MI);
2443
Spills.disallowClobberPhysReg(VirtReg);
2444
goto ProcessNextInst;
2447
// If it's not a no-op copy, it clobbers the value in the destreg.
2448
Spills.ClobberPhysReg(VirtReg);
2449
ReusedOperands.markClobbered(VirtReg);
2451
// Check to see if this instruction is a load from a stack slot into
2452
// a register. If so, this provides the stack slot value in the reg.
2454
if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2455
assert(DestReg == VirtReg && "Unknown load situation!");
2457
// If it is a folded reference, then it's not safe to clobber.
2458
bool Folded = FoldedSS.count(FrameIdx);
2459
// Otherwise, if it wasn't available, remember that it is now!
2460
Spills.addAvailable(FrameIdx, DestReg, !Folded);
2461
goto ProcessNextInst;
2467
unsigned SubIdx = MO.getSubReg();
2468
bool DoReMat = VRM->isReMaterialized(VirtReg);
2470
ReMatDefs.insert(&MI);
2472
// The only vregs left are stack slot definitions.
2473
int StackSlot = VRM->getStackSlot(VirtReg);
2474
const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2476
// If this def is part of a two-address operand, make sure to execute
2477
// the store from the correct physical register.
2480
if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2481
PhysReg = MI.getOperand(TiedOp).getReg();
2483
unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2484
assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2485
"Can't find corresponding super-register!");
2489
PhysReg = VRM->getPhys(VirtReg);
2490
if (ReusedOperands.isClobbered(PhysReg)) {
2491
// Another def has taken the assigned physreg. It must have been a
2492
// use&def which got it due to reuse. Undo the reuse!
2493
PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2494
Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2498
assert(PhysReg && "VR not assigned a physical register?");
2499
MRI->setPhysRegUsed(PhysReg);
2500
unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2501
ReusedOperands.markClobbered(RReg);
2502
MI.getOperand(i).setReg(RReg);
2503
MI.getOperand(i).setSubReg(0);
2505
if (!MO.isDead() && SpilledMIRegs.insert(VirtReg)) {
2506
MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2507
SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2508
LastStore, Spills, ReMatDefs, RegKills, KillOps);
2509
NextMII = llvm::next(MII);
2511
// Check to see if this is a noop copy. If so, eliminate the
2512
// instruction before considering the dest reg to be changed.
2513
if (MI.isIdentityCopy()) {
2515
DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2516
InvalidateKills(MI, TRI, RegKills, KillOps);
2517
VRM->RemoveMachineInstrFromMaps(&MI);
2520
UpdateKills(*LastStore, TRI, RegKills, KillOps);
2521
goto ProcessNextInst;
2526
// Delete dead instructions without side effects.
2527
if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2528
InvalidateKills(MI, TRI, RegKills, KillOps);
2529
VRM->RemoveMachineInstrFromMaps(&MI);
2534
DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
2535
if (!Erased && !BackTracked) {
2536
for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2537
UpdateKills(*II, TRI, RegKills, KillOps);
2544
llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2545
switch (RewriterOpt) {
2546
default: llvm_unreachable("Unreachable!");
2548
return new LocalRewriter();
2550
return new TrivialRewriter();